Beruflich Dokumente
Kultur Dokumente
10264A
Lab Instructions and Lab Answer Key:
Developing Web Applications with
Microsoft
Visual Studio
2010
Information in this document, including URL and other Internet Web site references, is subject to change without notice.
Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people,
places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain
name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright
laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be
reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft
Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject
matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this
document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no
representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the
products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of
Microsoft of the manufacturer or product. Links may be provided to third party sites. Such sites are not under the control of
Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any
changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from
any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply
endorsement of Microsoft of the site or the products contained therein.
2010 Microsoft Corporation. All rights reserved.
Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or
other countries.
All other trademarks are property of their respective owners.
Product Number: 10264A
Part Number: X17-47398
Released: 11/2010
Lab Instructions: Overview of Web Application Architecture and Design 1
Module 1
Lab Instructions: Overview of Web Application Architecture
and Design
Contents:
Exercise 1: Exploring the Adventure Works Website 4
Exercise 2: Comparing Web Forms and MVC 7
Exercise 3: Working with the Request Life Cycle 8
2 Lab Instructions: Overvie ew of Web Applicatioon Architecture and DDesign
LLab 1: Ex xploringg the AAdventu
O
In
In
Fu
ap
Fi
Objectives:
Describe th
Explain cod
Describe th
ntroduction
n this lab, you w
urthermore, yo
pplication dev
nally, you will
he Adventure W
de differences
he request life
n
will review the
ou will compar
velopment by u
explore how t
Works website
between Web
cycle for both
e existing Adve
re how applica
using the MVC
to create contr
re Works Webbsite
e.
b Forms and MVC.
Web Forms and MVC.
enture Works w
ation developm
C framework.
website and be
ment by using
ecome familia
Web Forms d
r with its desig
iffers from
gn.
rols dynamicallly by adding aan advertisemeent on the pagge.
Lab Instrucctions: Overview of WWeb Application Architecture and Design 3
L
A
ha
ac
en
pr
Lab Scen
s a web develo
ave limited ex
ccomplish the
nd, you want t
rogramming m
nario
oper at Adven
perience with
goals set by m
to examine the
model.
ture Works, yo
ASP.NET 4.0. Y
management f
e MVC framew
ou have worke
You need to fu
or the new Ad
work and unde
ed extensively
urther explore
dventure Work
erstand how it
with ASP.NET
the features o
ks website. As a
compares with
2.0. However,
of ASP.NET 4.0
a first step tow
h the Web For
you
to
ward this
rms
4 Lab Instructions: Overview of Web Application Architecture and Design
Exercise 1: Exploring the Adventure Works Website
The main tasks for this exercise are as follows:
1. Open the AdventureWorks solution in Visual Studio 2010.
2. Start the web application.
3. Browse the products list.
4. Add products to the shopping cart.
5. Place an order.
6. Explore the life cycle of a Web Forms page.
7. Open the AdventureWorksMvc solution in Visual Studio 2010.
8. Explore the life cycle of an MVC request.
Task 1: Open the AdventureWorks solution in Visual Studio 2010
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution at the following location.
Programming Language Location
Microsoft Visual C# D:\Lab Files\CS\Lab 01\Starter\WebForms
Microsoft Visual Basic D:\Lab Files\VB\Lab 01\Starter\WebForms
Task 2: Start the web application
Run the AdventureWorks solution in Debug mode.
Task 3: Browse the products list
In the Product Categories list, select Bib-Shorts, and then click the Submit button.
Note: Observe the products available in the Bib-Shorts product category.
Task 4: Add products to the shopping cart
1. Add one pair of Mens Bib-Shorts, size M, to the shopping cart.
2. Continue shopping.
Task 5: Place an order
1. Open the shopping cart.
2. Place the order.
Task 6: Explore the life cycle of a Web Forms page
1. Switch to Visual Studio 2010 with the AdventureWorks solution open.
2. Open the Default.aspx Web Form in Code view.
3. Place a breakpoint at the beginning of the Page_Load method.
Lab Instructions: Overview of Web Application Architecture and Design 5
4. Switch to Windows Internet Explorer.
5. Open the Home page.
Note: The debugger reaches your breakpoint in the Page_Load method.
6. Step through the web application startup until you reach the end of Page_Load method.
7. Continue the web application.
Note: The URL displayed in the address bar of Internet Explorer includes the name of the Web Form or
page (Default.aspx) displayed.
8. Close Windows Internet Explorer.
Task 7: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open a second instance of Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 01\Starter\MVC
Visual Basic D:\Lab Files\VB\Lab 01\Starter\MVC
Task 8: Explore the life cycle of an MVC request
1. In the Controllers folder, open the HomeController.cs or HomeController.vb file.
2. Notice the methods that are available and the way they relate to the actions that are available to the
user.
3. Close the HomeController.cs or HomeController.vb file.
4. Open the Global.asax file.
5. Place a breakpoint at the beginning of the Application_Start method.
6. Run the AdventureWorksMvc solution in Debug mode.
Note: The debugger reaches the breakpoint in the Application_Start method.
7. Examine the static/Shared RegisterRoutes method.
8. Step through the web application startup until you reach the last line of code in the Index action
method of the Home controller.
9. Continue the web application.
Note: The URL displayed in the address bar of Internet Explorer does not include the name of the page
(Index.aspx) displayed.
10. Close Windows Internet Explorer.
6 Lab Instructions: Overview of Web Application Architecture and Design
Results: After completing this exercise, you should have reviewed the Adventure Works website by
adding products to your shopping cart and checking out. You should also have reviewed the Page and
MVC request life cycles by placing breakpoints in methods that execute during the life cycle.
Lab Instructions: Overview of Web Application Architecture and Design 7
Exercise 2: Comparing Web Forms and MVC
The main tasks for this exercise are as follows:
1. View the AdventureWorks solution in Visual Studio 2010.
2. Examine the markup and code found in the Default.aspx Web Forms page.
3. View AdventureWorksMvc solution in Visual Studio 2010.
1. Examine the markup and code used for rendering the default MVC page.
2. Discuss as a group the differences in the way Web Forms and MVC responds and delivers content
to a request.
Task 1: View the AdventureWorks solution in Visual Studio 2010
Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.
Task 2: Examine the markup and code found in the Default.aspx Web Forms page
1. Examine the code in the Default.aspx.cs or Default.aspx.vb code file.
2. Examine the markup in the Default.aspx Web Form.
Task 3: View AdventureWorksMvc solution Microsoft Visual Studio 2010
Switch to the Visual Studio 2010 instance with the AdventureWorksMvc solution open.
Task 4: Examine the markup and code used for rendering the default MVC page
1. Open the Adventure Works MVC project at the following location:
Language Location
C# D:\Lab Files\CS\Lab 01\Starter\MVC
Visual Basic D:\Lab Files\VB\Lab 01\Starter\MVC
2. Examine the code in the HomeController.cs or HomeController.vb code file.
3. Examine the markup in the Index.aspx page.
Task 5: Discuss as a group the differences in the way Web Forms and MVC responds and
delivers content to a request
In the classroom, discuss the differences between the page life cycles of the two different web
application models, Web Forms and MVC, including the page-centric Web Forms request vs. the MVC
routing, the use of server controls in Web Forms vs. HTML controls, and MVC helper methods.
Results: After completing this exercise, you should have reviewed the code in a Web Forms and MVC
page, and discussed the differences as a class.
8 Lab Instructions: Overview of Web Application Architecture and Design
Exercise 3: Working with the Request Life Cycle
The main tasks for this exercise are as follows:
1. Exploring the life cycle of a Web Forms page.
2. Exploring the life cycle of a MVC request.
Task 1: Explore the life cycle of a Web Forms page
1. Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.
2. View the Default.aspx Web Form.
3. Locate the Content control with the ContentPlaceHolderID property set to MainContent.
4. Add the following Label control markup before any other content in the Content control.
<asp:Label ID="lblAdvertisement" runat="server" />
5. View the code-behind file for the Default Web Form.
6. In the Page_Load method, add the following code at the beginning of the method.
[Visual C#]
lblAdvertisement.Text = "My advertisement here";
[Visual Basic]
lblAdvertisement.Text = "My advertisement here"
7. Run the web application and view the rendered Default.aspx page.
Note: During the pages Load event, the text is added to the lblAdvertisement Label control.
8. Close Windows Internet Explorer.
9. Close Visual Studio 2010.
Task 2: Explore the life cycle of a MVC request
1. Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.
2. Open the Views\Home\Index.aspx view.
3. Locate the Content control with the ContentPlaceHolderID property value of MainContent.
4. Add the following code before any content in the Content control.
[Visual C#]
<p><%= ViewData["Advertisement"] %></p>
[Visual Basic]
<p><%: ViewData("Advertisement") %></p>
5. Open the file Controllers\HomeController.cs or Controllers\HomeController.vb.
In Solution Explorer, expand Controllers, and then double-click HomeController.cs or
HomeController.vb.
6. Locate the Index method in the file.
7. Add the following code at the beginning of the Index method.
[Visual C#]
Lab Instructions: Overview of Web Application Architecture and Design 9
ViewData["Advertisement"] = "My advertisement here";
[Visual Basic]
ViewData("Advertisement") = "My advertisement here"
8. Run the web application and view the rendered Index.aspx view.
Note: During the controllers Index action method, the text is added to Index view by using the
ViewData.
9. Close Windows Internet Explorer.
10. Close Visual Studio 2010.
Task 3: Turn off the virtual machine and revert the changes
1. In Microsoft Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and
then click Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Results: After completing this exercise, you should have explored the life cycle of both a Web Form and
an MVC page, by adding code to write to the page during the page request.
Lab Instructions: Designing a Web Application 1
Module 2
Lab Instructions: Designing a Web Application
Contents:
Exercise 1: Reviewing the Adventure Works Website Structure 4
Exercise 2: Redesigning the Adventure Works Website 5
Exercise 3: Adding MVC Capabilities to the Adventure Works Website 7
2 Lab Instructions: Designi ing a Web Applicatioon
LLab 2: Redesignning the
N
O
A
In
In
di
m
M
th
Note: Tasks in t
Objectives:
fter completin
Draw diagr
Identify wh
business re
Add MVC c
ntroduction
n this lab, you w
iagramming it
management, a
MVC. You will a
hat you can ge
this lab will be
ng this lab, you
rams showing t
hich pages of t
quirements.
capabilities to
n
will first captu
ts overall archi
and recommen
also do the gro
et started as so
e Advennture WWorks WWebsite
e the same reg
u will be able t
the overall arc
he website wil
the existing w
re your under
tecture and pa
nd which page
oundwork nece
oon as Manage
ardless of the
to:
chitecture and
l use Web For
ebsite.
standing of th
age flow. You
es of the websi
essary for add
ement approva
programming
page flow of t
rms, and which
e current Adve
will then revie
te will use We
ing MVC capa
al comes throu
g language youur solution is uusing.
the Adventuree Works websitte.
h pages will use MVC, based on
enture Works
ew the busines
eb Forms, and
abilities to the
ugh.
website by
s requirement
which pages w
existing websi
ts set by
will use
te so
Lab Instructions: Designingg a Web Application 3
L
N
M
de
th
re
co
en
Lab Scen
ow that you h
MVC to develop
etailing recom
he current web
edesigned web
osts and benef
numerate the
nario
have a better u
p some pages
mmendations fo
bsite and recom
bsite. Keep in m
fits of your dec
rationale unde
understanding
of the Advent
or redesigning
mmend an app
mind that you
cisions before
erlying your re
of Web Forms
ture Works we
g the website. Y
propriate prog
are operating
making recom
ecommendatio
s and MVC, yo
ebsite. Your nex
Your proposal
gramming mod
on a tight bu
mmendations.
ons to help ma
ou can see the
xt task is to cre
needs to desc
del for develo
dget, so you n
The proposal
anagement ass
benefits of us
eate a proposa
cribe the struc
ping the page
need to consid
should also
sess them.
ing
al
cture of
es of the
der the
4 Lab Instructions: Designing a Web Application
Exercise 1: Reviewing the Adventure Works Website Structure
The main tasks for this exercise are as follows:
Open the AdventureWorks solution in Visual Studio 2010.
Examine the code and markup location and purpose.
Draw a diagram showing the overall architecture.
Draw a diagram showing the page flow.
Discuss your findings with the class.
Task 1: Open the AdventureWorks solution in Visual Studio 2010
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution at the following location.
Programming Language Location
Visual C#
as your p
Objectives
fter completin
Create an M
List the exis
Create a ne
Edit a blog
Delete a blo
ntroduction
n this lab, you w
elete (CRUD) o
perform the ta
programming
ng this lab, you
MVC controlle
sting blog entr
ew blog entry.
entry.
og entry.
n
will create an
operations.
VC Controllers
asks in this lab
language.
u will be able t
r.
ries.
MVC controlle
b by using eithe
to:
er and add cod
er Microsoft V
de to it to perf
Visual C#
or MMicrosoft Visuaal
form create, reead, update, annd
Lab Innstructions: Developing MVC Controllers 3
L
Ba
de
A
op
Lab Scen
ased on your r
eveloped by u
DO.NET Entity
perations.
nario
recommendat
using MVC. You
y Data Model.
ions for redesi
u have already
Next, you nee
gning the Adv
y built your MV
ed to develop a
ventureWorks
VC model clas
an MVC contro
website, the b
ses by leverag
oller to handle
blog pages nee
ging an existing
e the database
ed to be
g
e
4 Lab Instructions: Developing MVC Controllers
Exercise 1: Creating an MVC Controller
The main tasks for this exercise are as follows:
Open the AdventureWorksMvc solution in Visual Studio 2010.
Create a controller named BlogController.
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 01
Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 01
Task 2: Create a controller named BlogController
1. Create a controller named BlogController in the Controllers folder. The controller should not
include action methods for create, update, delete, and details scenarios.
2. Add the HandleErrorAttribute attribute to the BlogController class.
[Visual C#]
[HandleError]
[Visual Basic]
<HandleError()>
3. Verify that the code in the BlogController code file matches the following code.
[Visual C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AdventureWorksMvc.Controllers
{
[HandleError]
public class BlogController : Controller
{
//
// GET: /Blog/
public ActionResult Index()
{
return View();
}
}
}
[Visual Basic]
Namespace AdventureWorksMvc
<HandleError()>
Public Class BlogController
Inherits System.Web.Mvc.Controller
'
Lab Instructions: Developing MVC Controllers 5
' GET: /Blog
Function Index() As ActionResult
Return View()
End Function
End Class
End Namespace
4. Build the solution, and fix any errors.
5. Close Visual Studio 2010.
Results: After this exercise, you should have created a new controller named BlogController that is
decorated with the HandleErrorAttribute attribute.
6 Lab Instructions: Developing MVC Controllers
Exercise 2: Adding code to list the existing blog entries
The main tasks for this exercise are as follows:
1. Open the AdventureWorksMvc solution in Visual Studio 2010.
2. Add a blogRepository object.
3. Add code to the Index action method.
4. Create a Blogger action method.
5. Create a Details action method.
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 02
Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 02
Task 2: Add a blogRepository object
1. Import the AdventureWorksMvc.Models namespace in the BlogController code file.
[Visual C#]
using AdventureWorksMvc.Models;
[Visual Basic]
Not applicable
2. Declare and instantiate a private BlogRepository object at the top of the BlogController class.
[Visual C#]
private BlogRepository blogRepository = new BlogRepository();
[Visual Basic]
Private blogRepository As New BlogRepository()
Task 3: Add code to the Index action method
1. Replace the existing code in the Index action method with code that returns all of the blog entries to
the view, by calling the GetAllBlogs method of the blogRepository object.
[Visual C#]
var blogs = blogRepository.GetAllBlogs();
return View(blogs);
[Visual Basic]
Dim blogs = blogRepository.GetAllBlogs()
Return View(blogs)
2. Verify that the final Index action method matches the following code:
[Visual C#]
public ActionResult Index()
{
var blogs = blogRepository.GetAllBlogs();
Lab Instructions: Developing MVC Controllers 7
return View(blogs);
}
[Visual Basic]
Function Index() As ActionResult
Dim blogs = blogRepository.GetAllBlogs()
Return View(blogs)
End Function
Task 4: Create a Blogger action method
1. Add a Blogger action method that takes the ID of the blogger as the only parameter.
[Visual C#]
public ActionResult Blogger(int id)
{
}
[Visual Basic]
Function Blogger(ByVal id As Integer) As ActionResult
End Function
2. Add code to the Blogger action method to return only the blog entries for the indicated blogger to
the view.
[Visual C#]
var blogs = blogRepository.GetAllBlogs(id);
return View(blogs);
[Visual Basic]
Dim blogs = blogRepository.GetAllBlogs(id)
Return View(blogs)
3. Verify that the final Blogger action method matches the following code.
[Visual C#]
public ActionResult Blogger(int id)
{
var blogs = blogRepository.GetAllBlogs(id);
return View(blogs);
}
[Visual Basic]
Function Blogger(ByVal id As Integer) As ActionResult
Dim blogs = blogRepository.GetAllBlogs(id)
Return View(blogs)
End Function
Task 5: Create a Details action method
1. Add a Details action method that takes the ID of the blog entry as its one parameter.
[Visual C#]
public ActionResult Details(int id)
{
}
[Visual Basic]
Function Details(ByVal id As Integer) As ActionResult
8 Lab Instructions: Developing MVC Controllers
End Function
2. Add code to the Details action method to return only the indicated blog entry, to the view. However,
if the blog entry no longer exists, redirect the user to the Index view.
[Visual C#]
var blogEntry = blogRepository.GetBlog(id);
if (blogEntry == null)
return RedirectToAction("Index");
return View(blogEntry);
[Visual Basic]
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
3. Verify that the final Details action method matches the following code.
[Visual C#]
public ActionResult Details(int id)
{
var blogEntry = blogRepository.GetBlog(id);
if (blogEntry == null)
return RedirectToAction("Index");
return View(blogEntry);
}
[Visual Basic]
Function Details(ByVal id As Integer) As ActionResult
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
End Function
4. Build the solution, and fix any errors.
5. Close Visual Studio 2010.
Results: After this exercise, you should have created a BlogRepository and action methods that allow
you to view all of the blog entries, to view just the blog entries for a particular blogger, and to view a
particular blog entry.
Lab Instructions: Developing MVC Controllers 9
Exercise 3: Adding code to create a new blog entry
The main tasks for this exercise are as follows:
1. Open the AdventureWorksMvc solution in Visual Studio 2010.
2. Create a Create action method.
3. Create a Create action method that accepts an HTTP Post.
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 03
Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 03
Task 2: Create a Create action method
1. Add a Create action method in the BlogController class.
[Visual C#]
public ActionResult Create()
{
}
[Visual Basic]
Function Create() As ActionResult
End Function
2. Add code to the Create action method to return an empty ActionResult to the view.
[Visual C#]
return View();
[Visual Basic]
Return View()
3. Verify that the final Create action method matches the following code:
[Visual C#]
public ActionResult Create()
{
return View();
}
[Visual Basic]
Function Create() As ActionResult
Return View()
End Function
Task 3: Create a Create action method for an HTTP Post request
1. Add a Create action method for an HTTP Post request that takes a Blog object as the only parameter.
[Visual C#]
[HttpPost]
10 Lab Instructions: Developing MVC Controllers
public ActionResult Create(Blog blog)
{
}
[Visual Basic]
<HttpPost()>
Function Create(ByVal blg As Blog) As ActionResult
End Function
2. Add code to the Create action method to save the new Blog object and redirect the user to the
Index view. However, if the call to the Save method fails, return the user to the Create view.
[Visual C#]
if (!ModelState.IsValid)
return View(blog);
try
{
blog.DatePosted = DateTime.Now;
blogRepository.AddBlog(blog);
blogRepository.Save();
TempData["ConfirmationMessage"] = blog.Title + " has been added.";
return RedirectToAction("Index");
}
catch (Exception)
{
return View(blog);
};
[Visual Basic]
If ModelState.IsValid Then
Try
blg.DatePosted = DateTime.Now
blogRepository.AddBlog(blg)
blogRepository.Save()
TempData("ConfirmationMessage") = blg.Title & " has been added"
Return RedirectToAction("Index")
Catch
Return View(blg)
End Try
End If
Return View(blg)
3. Verify that the final Create action method that for the HTTP Post request matches the following code.
[Visual C#]
[HttpPost]
public ActionResult Create(Blog blog)
{
if (!ModelState.IsValid)
return View(blog);
try
{
blog.DatePosted = DateTime.Now;
blogRepository.AddBlog(blog);
blogRepository.Save();
Lab Instructions: Developing MVC Controllers 11
TempData["ConfirmationMessage"] = blog.Title + " has been added.";
return RedirectToAction("Index");
}
catch (Exception)
{
return View(blog);
};
}
[Visual Basic]
<HttpPost()>
Function Create(ByVal blg As Blog) As ActionResult
If ModelState.IsValid Then
Try
blg.DatePosted = DateTime.Now
blogRepository.AddBlog(blg)
blogRepository.Save()
TempData("ConfirmationMessage") = blg.Title & " has been added"
Return RedirectToAction("Index")
Catch
Return View(blg)
End Try
End If
Return View(blg)
End Function
4. Build the solution, and fix any errors.
5. Close Visual Studio 2010.
Results: After this exercise, you should have created two action methods for creating new blog entries.
One of the action methods accepts HTTP Get requests and the other action method accepts HTTP Post
requests.
12 Lab Instructions: Developing MVC Controllers
Exercise 4: Adding code to edit a blog entry
The main tasks for this exercise are as follows:
1. Open the AdventureWorksMvc solution in Visual Studio 2010.
2. Create an Edit action method.
3. Create an Edit action method for an HTTP Post request.
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 04
Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 04
Task 2: Create an Edit action method
1. Add an Edit action method that takes the ID of a blog entry as the only parameter. The method
should be added to the BlogController class.
[Visual C#]
public ActionResult Edit(int id)
{
}
[Visual Basic]
Function Edit(ByVal id As Integer) As ActionResult
End Function
2. Add code to the Edit action method to return the indicated Blog entry, to the view. However, if the
blog entry no longer exists, redirect the user to the Index view.
[Visual C#]
var blog = blogRepository.GetBlog(id);
if (blog == null)
return RedirectToAction("Index");
return View(blog);
[Visual Basic]
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
3. Verify that the final Edit action method matches the following code.
[Visual C#]
public ActionResult Edit(int id)
{
var blog = blogRepository.GetBlog(id);
Lab Instructions: Developing MVC Controllers 13
if (blog == null)
return RedirectToAction("Index");
return View(blog);
}
[Visual Basic]
Function Edit(ByVal id As Integer) As ActionResult
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
End Function
Task 3: Create an Edit action method for an HTTP Post request
1. Add an Edit action method for an HTTP Post request that takes the ID of the blog entry and the
FormCollection as the two parameters.
[Visual C#]
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
}
[Visual Basic]
<HttpPost()>
Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
End Function
2. Add code to the Edit action method to save the blog entry and redirect the user to the Index view.
However, if the call to the Save method fails, return the user to the Edit view. Also, if the blog entry
no longer exists, redirect the user to the Index view.
[Visual C#]
var blog = blogRepository.GetBlog(id);
if (blog == null)
return RedirectToAction("Index");
try
{
UpdateModel(blog, collection.ToValueProvider());
blogRepository.UpdateBlog(blog);
blogRepository.Save();
TempData["ConfirmationMessage"] = blog.Title + " has been updated.";
return RedirectToAction("Index");
}
catch (Exception)
{
return View(blog);
};
[Visual Basic]
Dim blogEntry = blogRepository.GetBlog(id)
14 Lab Instructions: Developing MVC Controllers
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Try
UpdateModel(blogEntry, collection.ToValueProvider())
blogRepository.UpdateBlog(CType(blogEntry, Blog))
blogRepository.Save()
TempData("ConfirmationMessage") = blogEntry.Title & " has been updated"
Return RedirectToAction("Index")
Catch
Return View(blogEntry)
End Try
3. Verify that the final Edit action method for an HTTP Post request matches the following code.
[Visual C#]
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var blog = blogRepository.GetBlog(id);
if (blog == null)
return RedirectToAction("Index");
try
{
UpdateModel(blog, collection.ToValueProvider());
blogRepository.UpdateBlog(blog);
blogRepository.Save();
TempData["ConfirmationMessage"] = blog.Title + " has been updated.";
return RedirectToAction("Index");
}
catch (Exception)
{
return View(blog);
};
}
[Visual Basic]
<HttpPost()>
Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Try
UpdateModel(blogEntry, collection.ToValueProvider())
blogRepository.UpdateBlog(CType(blogEntry, Blog))
blogRepository.Save()
TempData("ConfirmationMessage") = blogEntry.Title & " has been updated"
Return RedirectToAction("Index")
Catch
Return View(blogEntry)
End Try
End Function
Lab Instructions: Developing MVC Controllers 15
4. Build the solution, and fix any errors.
5. Close Visual Studio 2010.
Results: After this exercise, you should have created two action methods for editing blog entries. One
of the action methods accepts HTTP Get requests and the other action method accepts HTTP Post
requests.
16 Lab Instructions: Developing MVC Controllers
Exercise 5: Adding code to delete a blog entry
The main tasks for this exercise are as follows:
1. Open the AdventureWorksMvc solution in Visual Studio 2010.
2. Create a Delete action method.
3. Create a Delete action method for an HTTP Post request
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 05\Starter\Exercise 03
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 03
Task 2: Create a Delete action method
1. Add a Delete action method that takes the ID of a blog entry as the only parameter. The method
should be added to the BlogController class.
[Visual C#]
public ActionResult Delete(int id)
{
}
[Visual Basic]
Function Delete(ByVal id As Integer) As ActionResult
End Function
2. Add code to the Delete action method to redirect to the Index view.
[Visual C#]
var blog = blogRepository.GetBlog(id);
if (blog == null)
return RedirectToAction("Index");
return View(blog);
[Visual Basic]
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
3. Verify that the final Delete action method matches the following code.
[Visual C#]
public ActionResult Delete(int id)
{
var blog = blogRepository.GetBlog(id);
Lab Instructions: Developing MVC Controllers 17
if (blog == null)
return RedirectToAction("Index");
return View(blog);
}
[Visual Basic]
Function Delete(ByVal id As Integer) As ActionResult
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
End Function
Task 3: Create a Delete action method for an HTTP Post request
1. Add a Delete action method for an HTTP Post request that takes the ID of the blog entry and a
confirmation string as the two parameters.
[Visual C#]
[HttpPost]
public ActionResult Delete(int id, string confirmation)
{
}
[Visual Basic]
<HttpPost()>
Function Delete(ByVal id As Integer, ByVal confirmation As String) As ActionResult
End Function
2. Add code to the Delete action method to delete the blog entry and redirect the user to the Index
view.
[Visual C#]
var blog = blogRepository.GetBlog(id);
if (blog == null)
return RedirectToAction("Index");
blogRepository.DeleteBlog((Blog) blog);
blogRepository.Save();
TempData["ConfirmationMessage"] = blog.Title + " has been deleted.";
return RedirectToAction("Index");
[Visual Basic]
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
blogRepository.DeleteBlog(CType(blogEntry, Blog))
blogRepository.Save()
TempData("ConfirmationMessage") = blogEntry.Title & " has been deleted."
Return RedirectToAction("Index")
18 Lab Instructions: Developing MVC Controllers
3. Verify that the final Delete action method for an HTTP Post request matches the following code.
[Visual C#]
[HttpPost]
public ActionResult Delete(int id, string confirmation)
{
var blog = blogRepository.GetBlog(id);
if (blog == null)
return RedirectToAction("Index");
blogRepository.DeleteBlog((Blog) blog);
blogRepository.Save();
TempData["ConfirmationMessage"] = blog.Title + " has been deleted.";
return RedirectToAction("Index");
}
[Visual Basic]
<HttpPost()>
Function Delete(ByVal id As Integer, ByVal confirmation As String) As ActionResult
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
blogRepository.DeleteBlog(CType(blogEntry, Blog))
blogRepository.Save()
TempData("ConfirmationMessage") = blogEntry.Title & " has been deleted."
Return RedirectToAction("Index")
End Function
4. Build the solution, and fix any errors.
5. Close Visual Studio 2010.
Task 4: Turn off the virtual machine and revert the changes
1. In Microsoft Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and
then click Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Results: After this exercise, you should have created two action methods for deleting blog entries. One
of the action methods accepts HTTP Gets and the other action method accepts HTTP Posts.
Lab Instructions: Developing MVC Views 1
Module 5
Lab Instructions: Developing MVC Views
Contents:
Exercise 1: Develop a List MVC View 4
Exercise 2: Develop a Details MVC view 7
Exercise 3: Develop a Create MVC view 9
Exercise 4: Develop an Edit MVC view 15
Exercise 5: Develop a Delete MVC view 19
2 Lab Instructions: Developing MVC Views
Lab 5: Developing MVC Views
Note: You can perform the tasks in this lab by using either Microsoft Visual C#
or Microsoft Visual
Basic
Internet Explorer
.
7. Close Visual Studio 2010.
Results: After this exercise, you should have created a custom error page for unhandled exceptions.
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 5
Exercise 2: Debugging Code
The main tasks for this exercise are as follows:
Run the application.
Debug Default.aspx.
Debug a java script error using breakpoints and single-stepping.
Debug Default.aspx.js.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 02 folder.
Task 2: Run the application
1. Set Default.aspx as the project start page.
2. Run the application in Debug mode.
Task 3: Debug Default.aspx
1. Click the Submit button.
Note: In Visual Studio, in the FormatException was unhandled by user code pane, the error text
Input string was not in a correct format is displayed.
2. Press F5 to continue.
Note: The custom error page is displayed. Do not close Internet Explorer.
3. In Visual Studio, place a breakpoint in Default.aspx.cs or Default.aspx.vb on the following line of
code.
[Visual C#]
string category = lbCategories.SelectedValue;
[Visual Basic]
Dim category As String = lbCategories.SelectedValue
4. Click the Back button on your browser.
Note: The Home page is displayed.
5. Click the Submit button.
Note: Visual Studio is now shown, with the breakpoint highlighted.
6. Press F10 to step over the line of code that sets the local variable category to the selected value of
the list.
6 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
7. Hover the mouse over category and notice it is an empty string, which cannot be parsed by the code
in the Products page.
8. Press SHIFT+F5 to end debugging.
9. In Visual Studio, modify the line of code that sets the local variable category to the selected value of
the list, as follows.
[Visual C#]
string category = lbCategories.SelectedValue == string.Empty ? "5" :
lbCategories.SelectedValue;
[Visual Basic]
Dim category As String = IIf(lbCategories.SelectedValue = String.Empty, "5",
lbCategories.SelectedValue)
Note: If the breakpoint disappears after modifying the line of code, place the cursor on the line of
code, and then press F9.
10. Run the application in Debug mode.
11. Click the Submit button.
Note: Visual Studio is now shown, with the breakpoint highlighted.
12. Press F10 to step over the line of code that sets the local variable category to the selected value of
the list.
13. Hover the mouse over category and notice it is a string with the value of 5.
14. Press F5 to continue.
Note: The Products page is displayed, showing a list of Mountain Bikes.
15. Close Windows Internet Explorer.
16. Remove all breakpoints by pressing CTRL+SHIFT+F9.
Task 4: Debug a java script error using breakpoints and single stepping
Run the application in Debug mode.
Note: The Home page is displayed.
Task 5: Debug Default.aspx.js
1. Click the Select First button.
Note: A dialog box with an alert message is now shown.
2. In the Message from webpage message box, click OK three times.
3. In Visual Studio, place a breakpoint in Default.aspx.js on the following line of code.
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 7
for (i = 0; i < 3; i++) {
4. Click the Back button in your browser.
Note: The Home page is displayed.
5. Click the Select First button.
Note: Visual Studio is now shown, with the breakpoint highlighted.
6. Press F10 to step over the statements of code, until a message box is displayed.
7. In the Message from webpage message box, click OK.
8. Repeat the previous two steps twice.
9. Press F5.
Note: The Products page is displayed.
10. Close Windows Internet Explorer.
11. Close Visual Studio 2010.
Results: After this exercise, you should have experience debugging Visual C# or Visual Basic, and java
script code.
8 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Exercise 3: Logging
The main tasks for this exercise are as follows:
Configure logging to an Error Log.
Set the logging level in the Web.config file to allow for future debugging.
Create a generic error handler.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 03 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 03 folder.
Task 2: Configure logging to an Error Log
1. Open Products.aspx in Code view.
2. Import the System.Diagnostics namespace.
[Visual C#]
using System.Diagnostics;
[Visual Basic]
Imports System.Diagnostics
3. Modify the Page_Load method with the following code.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string categoryName = string.Empty;
string categoryId = string.Empty;
if (Request["id"] != null)
{
categoryId = Request["id"];
}
try
{
categoryName =
DataAccessLayer.Products.GetCategoryName(int.Parse(categoryId));
}
catch (Exception ex)
{
EventLog Log = new EventLog();
Log.Source = "Application";
Log.WriteEntry(ex.Message, EventLogEntryType.Error);
}
lblCategory.Text = categoryName;
var data =
DataAccessLayer.Products.GetProductsByCategory(int.Parse(categoryId));
gvProducts.DataSource = data;
gvProducts.DataBind();
}
}
[Visual Basic]
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 9
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
If Not Page.IsPostBack Then
Dim categoryName As String = String.Empty
Dim categoryID As String = String.Empty
If Not Request("id") Is Nothing Then
categoryID = Request("id")
End If
Try
categoryName =
AdventureWorks.DataAccessLayer.Products.GetCategoryName(Integer.Parse(categoryID))
Catch ex As Exception
Dim Log As New EventLog()
Log.Source = "Application"
Log.WriteEntry(ex.Message, EventLogEntryType.[Error])
End Try
lblCategory.Text = categoryName
Dim data =
AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(Integer.Parse(categoryID
))
gvProducts.DataSource = data
gvProducts.DataBind()
End If
End Sub
4. Run the application.
Note: The custom error page is displayed.
5. Open the Event Viewer and show the Application log entry. If necessary, sort the Application log
entries by date and time.
10 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
6. Close the Event Viewer.
7. Close Windows Internet Explorer.
Task 3: Set the logging level in the Web.config file to allow for future debugging
1. Open the Web.config file.
2. In the opening compilation tag, ensure that the value of the debug attribute is set to true.
<compilation debug="true" ...>
3. Close the Web.config file.
Task 4: Create a generic error handler
1. Open the Global.asax file.
In Solution Explorer, double-click Global.asax.
2. Import the System.Diagnostics namespace.
[Visual C#]
using System.Diagnostics;
[Visual Basic]
Imports System.Diagnostics
3. Modify the Application_Error method with the following code.
[Visual C#]
void Application_Error(object sender, EventArgs e)
{
string message =
"Url: " + Request.Path + " Error: " +
Server.GetLastError().ToString();
EventLog log = new EventLog();
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 11
log.Source = "Application";
log.WriteEntry(message, EventLogEntryType.Error);
}
[Visual Basic]
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim message As String =
"Url: " & Request.Path & " Error: " &
Server.GetLastError().ToString()
Dim log As New EventLog()
log.Source = "Application"
log.WriteEntry(message, EventLogEntryType.Error)
End Sub
4. Build the project and fix any errors.
In the AdventureWorks Microsoft Visual Studio window, on the Build
menu, click Build AdventureWorks.
5. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the
Close button
Results: After this exercise, you should have experience installing a generic error handler for logging
that can be called by a single method and all modules.
12 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Exercise 4: Creating Unit Tests
The main tasks for this exercise are as follows:
Create a method to add two numbers.
Add a test project.
Edit the test method to pass.
Run the test.
Edit the test method to fail.
Run the tests.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the MyClassLibrary solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 04 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 04 folder.
Task 2: Create a method to add two numbers
1. Open the Calculator.cs or Calculator.vb file.
2. Add the following code to Calculator class.
[Visual C#]
public int Add(int p1, int p2)
{
return p1 + p2;
}
[Visual Basic]
Public Function Add(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Return p1 + p2
End Function
3. Save Calculator.cs or Calculator.vb.
4. Build the project and fix any errors.
Task 3: Add a test project
Add a test project named CalculatorTestProject for the Add method.
Task 4: Edit the test method to pass
1. In the AddTest method, modify the value assigned to local variable p1 to 2.
[Visual C#]
int p1 = 2;
[Visual Basic]
Dim p1 As Integer = 2
2. In the AddTest method, modify the value assigned to local variable p2 to 3.
[Visual C#]
int p2 = 3;
[Visual Basic]
Dim p2 As Integer = 3
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 13
3. In the AddTest method, modify the value assigned to local variable expected to 5.
[Visual C#]
int expected = 5;
[Visual Basic]
Dim expected As Integer = 5
4. Remove 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.")
5. Ensure the AddTest method appears as follows.
[Visual C#]
[TestMethod()]
public void AddTest()
{
Calculator target = new Calculator(); // TODO: Initialize to an appropriate value
int p1 = 2; // TODO: Initialize to an appropriate value
int p2 = 3; // TODO: Initialize to an appropriate value
int expected = 5; // TODO: Initialize to an appropriate value
int actual;
actual = target.Add(p1, p2);
Assert.AreEqual(expected, actual);
}
[Visual Basic]
<TestMethod()> _
Public Sub AddTest()
Dim target As Calculator = New Calculator() ' TODO: Initialize to an appropriate
value
Dim p1 As Integer = 2 ' TODO: Initialize to an appropriate value
Dim p2 As Integer = 3 ' TODO: Initialize to an appropriate value
Dim expected As Integer = 5 ' TODO: Initialize to an appropriate value
Dim actual As Integer
actual = target.Add(p1, p2)
Assert.AreEqual(expected, actual)
End Sub
Task 5: Run the test
Start the test.
Note: In the Test Result window, you can see that the AddTest test passed.
Task 6: Edit the test method to fail
1. In the AddTest method, modify the value assigned to local variable expected to 6.
[Visual C#]
int expected = 6;
[Visual Basic]
Dim expected As Integer = 6
2. Ensure the AddTest method appears as follows.
[Visual C#]
14 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
[TestMethod()]
public void AddTest()
{
Calculator target = new Calculator(); // TODO: Initialize to an appropriate value
int p1 = 2; // TODO: Initialize to an appropriate value
int p2 = 3; // TODO: Initialize to an appropriate value
int expected = 6; // TODO: Initialize to an appropriate value
int actual;
actual = target.Add(p1, p2);
Assert.AreEqual(expected, actual);
}
[Visual Basic]
<TestMethod()> _
Public Sub AddTest()
Dim target As Calculator = New Calculator() ' TODO: Initialize to an appropriate
value
Dim p1 As Integer = 2 ' TODO: Initialize to an appropriate value
Dim p2 As Integer = 3 ' TODO: Initialize to an appropriate value
Dim expected As Integer = 6 ' TODO: Initialize to an appropriate value
Dim actual As Integer
actual = target.Add(p1, p2)
Assert.AreEqual(expected, actual)
End Sub
Task 7: Run the tests
1. Start the test.
Note: In the Test Result window, you can see that the AddTest test failed.
2. Close Visual Studio 2010.
Results: After this exercise, you should have experience creating unit tests for existing methods.
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 15
Exercise 5: Implementing the Test-First/Test-Driven Development
Methodology
The main tasks for this exercise are as follows:
Create tests.
Create method stub.
Run the tests.
Add logic to stub methods.
Run the tests.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the MyClassLibrary solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 05 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 05 folder.
Task 2: Create tests
1. Open CalculatorTest.cs or CalculatorTest.vb file in the CalculatorTestProject project.
2. Add the following code to CalculatorTest class.
[Visual C#]
[TestMethod()]
public void ClassMultiplyMethodTest()
{
Calculator target = new Calculator();
Assert.IsNotNull(target);
int expected = 6;
int unexpected = 5;
int actual = target.Multiply(3, 2);
Assert.AreEqual(expected, actual);
Assert.AreNotEqual(unexpected, actual);
}
[TestMethod()]
public void ClassSubtractMethodTest()
{
Calculator target = new Calculator();
Assert.IsNotNull(target);
int expected = 1;
int unexpected = 6;
int actual = target.Subtract(3, 2);
Assert.AreEqual(expected, actual);
Assert.AreNotEqual(unexpected, actual);
}
[Visual Basic]
<TestMethod()>
Public Sub ClassMultiplyMethodTest()
Dim target As New Calculator()
Assert.IsNotNull(target)
16 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Dim expected As Integer = 6
Dim unexpected As Integer = 5
Dim actual As Integer = target.Multiply(3, 2)
Assert.AreEqual(expected, actual)
Assert.AreNotEqual(unexpected, actual)
End Sub
<TestMethod()>
Public Sub ClassSubtractMethodTest()
Dim target As New Calculator()
Assert.IsNotNull(target)
Dim expected As Integer = 1
Dim unexpected As Integer = 6
Dim actual As Integer = target.Subtract(3, 2)
Assert.AreEqual(expected, actual)
Assert.AreNotEqual(unexpected, actual)
End Sub
3. Save the CalculatorTest.cs or CalculatorTest.vb file.
Task 3: Create method stub
1. Open the Calculator.cs or Calculator.vb file in the ClassLibrary project.
2. Add the following code to the Calculator class.
[Visual C#]
public int Multiply(int p1, int p2)
{
throw new NotImplementedException();
}
public int Subtract(int p1, int p2)
{
throw new NotImplementedException();
}
[Visual Basic]
Public Function Multiply(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Throw New NotImplementedException()
End Function
Public Function Subtract(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Throw New NotImplementedException()
End Function
3. Build the solution and fix any errors.
Task 4: Run the tests
1. Open the CalculatorTest.cs or CalculatorTest.vb file.
2. Start the ClassMultiplyMethodTest test.
Note: In the Test Result window, you can see that the ClassMultiplyMethodTest test failed.
3. Start the ClassSubtractMethodTest test.
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 17
Note: In the Test Result window, you can see that the ClassSubtractMethodTest test failed.
4. Close the CalculatorTest.cs or CalculatorTest.vb file.
Task 5: Add logic to the stub methods
1. Replace the Multiply method in the Calculator class with following code.
[Visual C#]
public int Multiply(int p1, int p2)
{
return p1 * p2;
}
[Visual Basic]
Public Function Multiply (ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Return p1 * p2
End Function
2. Replace the Subtract method in the Calculator class with following code.
[Visual C#]
public int Subtract(int p1, int p2)
{
return p1 - p2;
}
[Visual Basic]
Public Function Subtract(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Return p1 - p2
End Function
3. Build the solution and fix any errors.
Task 6: Run the tests
1. Open CalculatorTest.cs or CalculatorTest.vb file in the CalculatorTestProject project.
2. Start the ClassMultiplyMethodTest test.
Note: In the Test Result window, you can see that the ClassMultiplyMethodTest test passed.
3. Start the ClassSubtractMethodTest test.
Note: In the Test Result window, you can see that the ClassSubtractMethodTest test passed.
4. Close the CalculatorTest.cs or CalculatorTest.vb file.
5. Close Visual Studio 2010.
Task 7: Turn off the virtual machine and revert the changes
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
18 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
4. In the Revert Virtual Machine dialog box, click Revert.
Results: After this exercise, you should have experience creating tests first, and then implementing
methods.
Lab Instructions: Securing a Web Application 1
Module 10
Lab Instructions: Securing a Web Application
Contents:
Exercise 1: Configuring ASP.NET Membership and Roles 4
Exercise 2: Authentication 6
Exercise 3: Authorization 10
2 Lab Instructions: Securin ng a Web Application
LLab 10: Securinng a We
O
A
In
In
us
le
Objectives
fter completin
Create and
Implement
Create acce
ntroduction
n this lab you w
sing the Login
earn to create a
ng this lab, you
manage users
the Login con
ess rules
n
will learn how
n control. You
an email passw
eb Appliication
u will be able tto:
using the ASP s and roles by P.NET Web Sitee Administratioon Tool
ntrol
to use the ASP
will also imple
word recovery
P.NET Web Sit
ement custom
page. Finally,
e Administrati
logic to expire
you will learn
on Tool, authe
e the password
how to create
enticate users
d in 90 days, a
e access rules.
by
and
Lab Instructions: Securingg a Web Application 3
L
Th
au
Th
au
Lab Scen
he Adventure
uthenticated u
his means you
uthentication a
nario
Works Sales te
users are able t
eam has reque
to access the s
ested that area
secure areas of
as of the websi
f the site.
ite be protecteed so that onlyy
must configu
and authorizat
re ASP.NET M
tion, impleme
embership, cre
nt Login contr
eate users, cre
rols, and test th
eate and assign
he web applica
n roles, implem
ation.
ment
4 Lab Instructions: Securing a Web Application
Exercise 1: Configuring ASP.NET Membership and Roles
The main tasks for this exercise are as follows:
Open an existing ASP.NET web application.
Open the ASP.NET Web Site Administration Tool.
Add Users.
Add Roles.
Assign Roles to Users.
Task 1: Open an existing ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 10\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 10\Starter\Exercise 01 folder.
Task 2: Open the ASP.NET Web Site Administration Tool
1. In Solution Explorer, click AdventureWorks.
2. Build the solution.
3. In Solution Explorer, click the ASP.NET Configuration button.
4. Change the authentication type from local to Internet (Windows to Forms), by using the Security
page.
5. Click Select authentication type.
6. Click From the internet, and then click Done.
Task 3: Add users
1. Click Create user.
2. Fill out the information to create a new user, using the following information.
User
Name Password E-mail
Security
Question Security Answer
Mary Pa$$w0rd mary@adventureworks.com Favorite pet Cat
3. Click Create User.
4. Click Continue.
5. Fill out the information to create a new user, using the following information.
User
Name Password E-mail
Security
Question Security Answer
John Pa$$w0rd john@adventureworks.com High School Central
6. Click Create User.
7. Click Continue.
Task 4: Add roles
1. In the ASP.NET Web Site Administration Tool, click Security.
Lab Instructions: Securing a Web Application 5
2. Click Enable roles.
3. Click Create or Manage roles.
4. In the New role name box, type Administration, and then click Add Role.
5. In the New role name box, type Contributor, and then click Add Role.
Task 5: Assign roles to users
1. Click Manage for the Contributor role.
2. Type * in the for box, and then click Find User.
3. Select the User Is In Role check box next to user Mary.
4. Click Back.
5. Click Manage for the Administration role.
6. Type * in the for box, and then click Find User.
7. Select the User Is In Role check boxes next to users John and Mary.
8. Close the ASP.NET Web Site Administration Tool.
9. Close Visual Studio 2010.
Result: In this exercise, you should have learned how to configure ASP.NET Membership provider by
using the ASP.NET Web Site Administration Tool. You should also have learned how to create users
and role for an ASP.NET web application.
6 Lab Instructions: Securing a Web Application
Exercise 2: Authentication
The main tasks for this exercise are as follows:
Open an existing ASP.NET web application.
Configure an application to use Forms authentication.
Use the Login control.
Set the password options.
Configure password recovery.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 10\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 10\Starter\Exercise 02 folder.
Task 2: Configure an application to use Forms authentication
1. Open the Web.config file.
2. Ensure that the value of the mode attribute it set to Forms, in the self-closing authentication
element.
<authentication mode="Forms" />
Note: When changing the authentication type in the ASP.NET Web Site Administration Tool to
From the internet, the Web.config file is updated automatically.
3. Add a redirect to the existing Login.aspx Web Form in the Account folder, by modifying the self-
closing authentication tag.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
Task 3: Use the Login control
1. In Solution Explorer, expand the Account folder.
2. Open the Login.aspx Web Form.
3. Examine the markup for the Login control, including the UserName and Password TextBox
controls, as well as the RememberMe CheckBox control.
<asp:Login ID="LoginUser" runat="server" EnableViewState="false"
RenderOuterTable="false">
<LayoutTemplate>
<span class="failureNotification">
<asp:Literal ID="FailureText" runat="server"></asp:Literal>
</span>
<asp:ValidationSummary ID="LoginUserValidationSummary" runat="server"
CssClass="failureNotification"
ValidationGroup="LoginUserValidationGroup"/>
<div class="accountInfo">
<fieldset class="login">
<legend>Account Information</legend>
<p>
<asp:Label ID="UserNameLabel" runat="server"
AssociatedControlID="UserName">Username:</asp:Label>
Lab Instructions: Securing a Web Application 7
<asp:TextBox ID="UserName" runat="server"
CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName"
CssClass="failureNotification" ErrorMessage="User Name is
required." ToolTip="User Name is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p>
<asp:Label ID="PasswordLabel" runat="server"
AssociatedControlID="Password">Password:</asp:Label>
<asp:TextBox ID="Password" runat="server"
CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
ControlToValidate="Password"
CssClass="failureNotification" ErrorMessage="Password is
required." ToolTip="Password is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p>
<asp:CheckBox ID="RememberMe" runat="server"/>
<asp:Label ID="RememberMeLabel" runat="server"
AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
</p>
</fieldset>
<p class="submitButton">
<asp:Button ID="LoginButton" runat="server" CommandName="Login"
Text="Log In" ValidationGroup="LoginUserValidationGroup"/>
</p>
</div>
</LayoutTemplate>
</asp:Login>
4. Add a redirect to the EmailPassword.aspx Web Form in the Account folder, by adding the following
markup above the PasswordLabel control.
<asp:HyperLink ID="EmailPasswordHyperLink" runat="server"
NavigateUrl="~/Account/EmailPassword.aspx">Forgot Password?</asp:HyperLink>
Note: The EmailPassword.aspx Web Form has not yet been created.
Task 4: Set the password options
1. Open Login.aspx in Code view.
2. Import the System.Web.Security namespace.
[Visual C#]
using System.Web.Security;
[Visual Basic]
Imports System.Web.Security
3. Add the following code to the Login class to handle the Authenticate event for the LoginUser
server control.
[Visual C#]
protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
{
// Get the membership details for the user
MembershipUser user = Membership.GetUser(LoginUser.UserName.Trim());
8 Lab Instructions: Securing a Web Application
// Did we find the user?
if (user != null)
{
// Check if the user password has expired after 90 days
if (DateTime.Now.Subtract(user.LastPasswordChangedDate).TotalDays >= 90)
{
Response.Redirect("PasswordExpired.aspx");
}
else
{
// Authenticate user
if (Membership.ValidateUser(LoginUser.UserName.Trim(),
LoginUser.Password.Trim()))
e.Authenticated = true;
}
}
[Visual Basic]
Protected Sub LoginUser_Authenticate(ByVal sender As Object, ByVal e As
AuthenticateEventArgs) Handles LoginUser.Authenticate
' Get the membership details for the user
Dim user As MembershipUser = Membership.GetUser(LoginUser.UserName.Trim())
' Did we find the user?
If Not user Is Nothing Then
' Check if the user password has expired after 90 days
If DateTime.Now.Subtract(user.LastPasswordChangedDate).TotalDays >= 90 Then
Response.Redirect("PasswordExpired.aspx")
Else
' Authenticate user
If Membership.ValidateUser(LoginUser.UserName.Trim(),
LoginUser.Password.Trim()) Then
e.Authenticated = True
End If
End If
End If
End Sub
4. Build the solution.
5. Close the Login.aspx code-behind file.
6. Close the Login.aspx Web Form.
Task 5: Configure password recovery
1. Add a new Web Form named EmailPassword to the Account folder. The Web Form must be based
on the Site.Master master page.
2. Drag a PasswordRecovery server control from the Login section of the Toolbox to the
EmailPassword.aspx Web Form, in the Content2 Content control. Keep the default settings.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:PasswordRecovery ID="PasswordRecovery1" runat="server">
</asp:PasswordRecovery>
</asp:Content>
3. Configure the Web.config file to use the mail settings as shown.
<system.net>
<mailSettings>
<smtp from="someone@adventureworks.com">
<network host="yourhost" userName="hostusername" password="hostpassword" />
</smtp>
Lab Instructions: Securing a Web Application 9
</mailSettings>
</system.net>
4. Build the solution and fix any errors.
5. Close Visual Studio 2010.
Result: In this exercise, you should have configured the web application to use Forms authentication,
and how to use the Login controls, including the Login and PasswordRecovery server controls.
10 Lab Instructions: Securing a Web Application
Exercise 3: Authorization
The main tasks for this exercise are as follows:
Open an existing ASP.NET web application.
Allow anonymous access to the EmailPassword Web Form.
Create the secured portion of the site.
Test the web application.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 10\Starter\Exercise 03 or D:\Lab
Files\VB\Lab 10\Starter\Exercise 03 folder.
Task 2: Allow anonymous access to the EmailPassword Web Form
1. Open the Web.config file in the Account folder.
2. Add the following markup to the Web.config file, above the existing location element.
<location path="EmailPassword.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
3. Save and close the Web.config file.
Task 3: Create the secured portion of the site
1. Create a new folder named Contributors.
2. Add a new Web Form named Home.aspx in the Contributors folder. The Web Form should be
based on the Site.Master master page.
3. Add the following header to the Home.aspx Web Form.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Contributors Home section</h2>
</asp:Content>
4. Save and close the Home.aspx file.
5. Open the Web.config file.
6. Add the following markup to the Web.config file, above the opening connectionStrings tag.
<location path="Contributors">
<system.web>
<authorization>
<allow roles="Contributor"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
7. Save and close the Web.config file.
Task 4: Test the web application
1. Build the solution and fix any errors.
Lab Instructions: Securing a Web Application 11
2. Run the application.
3. On the Home page, click Log In.
4. On the Login page, click Forgot Password?.
Note: You have access to the EmailPassword Web Form as an anonymous user.
5. Click the Back button in your browser.
Note: The Login is displayed.
6. Log on using John as the username and Pa$$w0rd as the password.
7. Access the Contributors/Home.aspx Web Form by typing in the following URL in the Internet
Explorer Address bar, and then press ENTER.
[Visual C#]
http://localhost:4378/Contributors/Home.aspx
[Visual Basic]
http://localhost:15237/Contributors/Home.aspx
Note: You are denied access, because the user John is not authorized to access the Contributors
folder.
8. Log on using Mary as the username and Pa$$w0rd as the password.
Note: You are now redirected to the Contributors/Home.aspx Web Form, because the user Mary
is authorized to access the Contributors folder.
9. Close Windows Internet Explorer.
10. Close Visual Studio 2010.
Task 5: Turn off the virtual machine and revert the changes
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Result: In this exercise, you should have configured authorization for web application, including a
Contributors folder and the EmailPassword.aspx specifically, and tested the web application.
Lab Instructions: Applying Master Pages and CSS 1
Module 11
Lab Instructions: Applying Master Pages and CSS
Contents:
Exercise 1: Modify a Master Page 4
Exercise 2: Create a Nested Master Page 6
Exercise 3: Integrate a Master Page 9
Exercise 4: Implement Control Skins 12
Exercise 5: Apply Styles and Themes 13
2 Lab Instructions: Applyin ng Master Pages and CSS
L
N
O
A
In
In
Co
cr
w
ex
th
Lab 11: A
Note: Tasks in
Objectives:
fter completin
Modify a m
Create nest
Apply mast
Apply Them
ntroduction
n this lab, you w
ontentPlaceH
reate an area i
will then create
xisting CSS sty
heme in the W
Applyin
this lab will b
ng this lab, you
master page.
ted master pag
ter pages.
mes, Skins, and
n
will first modif
Holder for the
n the existing
two control sk
yles, create two
Web.config file
ng Mast
e the same, re
u will be able t
ges.
d Styles.
fy the existing
footer conten
master page f
kins and apply
o themes for th
e.
ter Pagees and CCSS
egardless of th
to:
master page f
nt, and implem
for status mess
y them to cont
he website bas
e programmin
for the Advent
ment it in the A
sages and imp
trols in the exis
sed on the exis
ng language yoour solution iss using.
tureWorks web
About.aspx pa
plement it for a
sting website.
sting styles, an
bsite, add a ne
age. You will th
all child pages
You will also m
nd implement
ew
hen
. You
modify
one
Lab Instruuctions: Applying Maaster Pages and CSS 3
L
A
op
fu
Yo
ne
Lab Scen
dventure Wor
ptions using th
uture changes
ou will also ad
eed to implem
nario
ks is redesigni
he new color p
to the look-an
ng their Webs
palette, taking
nd-feel easy to
site in a corpor
advantage of
o perform.
rate branding
the theme an
initiative. You
d skin feature
will present tw
s of ASP.NET t
wo
to make
dd an applicati
ment this messa
on-wide locat
aging location
ion for reporti
n consistently a
ng errors and
across the app
sending mess
plication.
You sages to users.
4 Lab Instructions: Applying Master Pages and CSS
Exercise 1: Modify a Master Page
1. Open the Site.Master master page.
2. Add a third ContentPlaceHolder control.
3. Open the About.aspx page.
4. Add a new Content control to About.aspx.
5. Add the string Copyright notice to the control.
6. Test the About.aspx page.
Task 1: Open an existing ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 01 folder.
Task 2: Open the Site.Master master page
Open the Site.Master file in the root of the AdventureWorks project.
Task 3: Add a third ContentPlaceHolder control
Add the following markup to the Site.Master file to add the new ContentPlaceHolder with an ID
attribute value of FooterContent.
<div class="footer">
<asp:ContentPlaceHolder ID="FooterContent" runat="server" />
</div>
Task 4: Open the About.aspx page
Open the About.aspx file in the root of the AdventureWorks project.
Task 5: Add a new Content control to About.aspx
Add the following markup to the About.aspx file to add the Content control in the bottom of the
page.
<asp:Content ID="PageFooterContent" runat="server"
ContentPlaceHolderID="FooterContent">
</asp:Content>
Task 6: Add the string Copyright notice to the control
Add the following text to the Content control.
<asp:Content ID="PageFooterContent" runat=server
ContentPlaceHolderID="FooterContent">
Copyright AdventureWorks
</asp:Content>
Task 7: Test the About.aspx page
Run the application to test the page by pressing CTRL+F5.
Note: The rendered page should appear as follows. Notice the text you added at the bottom of the
image.
Lab Instructions: Applying Master Pages and CSS 5
1. Close Windows Internet Explorer.
2. Close Visual Studio 2010.
Results: After completing this exercise, you should have added a new ContentPlaceHolder in the
Site.Master master page, and added a new Content control in the About.aspx page displaying a
copyright string for the application using the new ContentPlaceHolder we added to the master page.
6 Lab Instructions: Applying Master Pages and CSS
Exercise 2: Create a Nested Master Page
The main tasks for this exercise are as follows:
1. Create a nested master page.
2. Add two ContentPlaceHolder controls.
3. Add footer content.
4. Change the Default.aspx page Web Form to use the Nested.master page.
5. Test the Default.aspx page.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 02 folder.
Task 2: Create a Nested Master page
1. Add a nested master page named Nested.master to the project. It should be based on the
Site.Master master page.
2. Rename each of the three Content controls to Header, Main, and Footer.
[Visual C#]
<%@ Master Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Nested.master.cs" Inherits="AdventureWorks.Nested" %>
<asp:Content ID="Header" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
<asp:Content ID="Footer" ContentPlaceHolderID="FooterContent" runat="server">
</asp:Content>
[Visual Basic]
<%@ Master Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Nested.master.vb" Inherits="AdventureWorks.Nested" %>
<asp:Content ID="Header" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
<asp:Content ID="Footer" ContentPlaceHolderID="FooterContent" runat="server">
</asp:Content>
Task 3: Add two ContentPlaceHolder controls
To add two ContentPlaceHolder controls to the Nested.master file, add the following markup, in
the Main Content control.
<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">
<div class="left">
<asp:ContentPlaceHolder ID="LeftContent" runat="server" />
</div>
<div class="right">
<asp:ContentPlaceHolder ID="RightContent" runat="server" />
</div>
</asp:Content>
Task 4: Add footer content
To add the footer content to the Nested.master file, add the following markup in the Footer
Content control.
Lab Instructions: Applying Master Pages and CSS 7
<asp:Content ID="Footer" ContentPlaceHolderID="FooterContent" runat="server">
Copyright AdventureWorks
</asp:Content>
Task 5: Change the Default.aspx page Web Form to use the Nested.master page
1. Modify the Page directive in the Default.aspx file, by adding following markup to change the master
page.
[Visual C#]
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Nested.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AdventureWorks._Default" %>
[Visual Basic]
<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Nested.master"
AutoEventWireup="false"
CodeBehind="Default.aspx.vb" Inherits="AdventureWorks._Default" %>
2. Change the ContentPlaceHolder controls to which the Content controls refer to RightContent and
LeftContent. Rename the Content controls to RightBodyContent and LeftBodyContent.
<asp:Content ID="RightBodyContent" runat="server"
ContentPlaceHolderID="RightContent">
...
<asp:Content ID="LeftBodyContent" runat="server" ContentPlaceHolderID="LeftContent">
3. Add the following markup to the Content control with an ID attribute value of RightBodyContent.
<asp:Content ID="RightBodyContent" runat="server"
ContentPlaceHolderID="RightContent">
<p>
Right Content
</p>
</asp:Content>
4. Move the Content control with an ID attribute value of RightBodyContent to after the Content
control with an ID attribute value of LeftBodyContent.
<asp:Content ID="LeftBodyContent" runat="server" ContentPlaceHolderID="LeftContent">
<h2>
Welcome to AdventureWorks!
</h2>
<p>
Product Categories
<br />
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"
DataValueField="ProductCategoryID"
Height="270px" Width="186px"></asp:ListBox>
<br />
<asp:Button ID="btnCategory" runat="server" Text="Submit"></asp:Button>
</p>
</asp:Content>
<asp:Content ID="RightBodyContent" runat="server"
ContentPlaceHolderID="RightContent">
<p>
Right Content
</p>
</asp:Content>
Task 5: Test the Default.aspx page
Test the page by pressing CTRL+F5.
8 Lab Instructions: Applying Master Pages and CSS
Note: The rendered page should appear as follows. Notice the content displayed in two columns.
Results: After completing this exercise, you should have added a new nested master page to the
project, configured the master page to have two new ContentPlaceHolder controls, configured the
Default.aspx page to use the new nested master page, and added configured the content in the page
to use the new ContentPlaceHolder controls.
Lab Instructions: Applying Master Pages and CSS 9
Exercise 3: Integrate a Master Page
The main tasks for this exercise are as follows:
1. Open the Site.Master master page.
2. Create an area on the master page to display status messages.
3. Create a property that populates the status area.
4. Set the status property in child pages.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 03 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 03 folder.
Task 2: Open the Site.Master master page
Open the Site.Master file.
Task 3: Create an area on the master page to display status messages
Create a Label control named StatusMessageLabel in the div element with a class attribute value of
main.
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
<asp:Label ID="StatusMessageLabel" runat="server" />
</div>
Task 4: Create a property that populates the status area
1. Open the Site.Master master page in Code view.
2. Create a new property named StatusMessage in the SiteMaster or Site class.
[Visual C#]
public string StatusMessage
{
get { return StatusMessageLabel.Text; }
set { StatusMessageLabel.Text = value; }
}
[Visual Basic]
Public Property StatusMessage() As String
Get
Return StatusMessageLabel.Text
End Get
Set(ByVal value As String)
StatusMessageLabel.Text = value
End Set
End Property
Task 5: Set the status property in child pages
1. To allow for the About.aspx and Products.aspx pages to access properties on the master using a
strongly typed reference, add a MasterType directive.
[Visual C#]
<%@ MasterType TypeName="AdventureWorks.SiteMaster" %>
[Visual Basic]
<%@ MasterType TypeName="AdventureWorks.Site" %>
10 Lab Instructions: Applying Master Pages and CSS
2. In the Page_Load event handler for the About.aspx page, set the StatusMessage property.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
Master.StatusMessage = "You are on the About page";
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Master.StatusMessage = "You are on the About page"
End Sub
3. In the Page_Load event handler for the Products.aspx page, set the StatusMessage property.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string categoryName;
string categoryId = "5";
if (Request["id"] != null)
{
categoryId = Request["id"];
}
categoryName =
DataAccessLayer.Products.GetCategoryName(int.Parse(categoryId));
lblCategory.Text = categoryName;
var data =
DataAccessLayer.Products.GetProductsByCategory(int.Parse(categoryId));
gvProducts.DataSource = data;
gvProducts.DataBind();
}
Master.StatusMessage = "You are on the Products page";
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
If Not Page.IsPostBack Then
Dim categoryName As String = Nothing
Dim categoryID As String = "5"
If Not Request("id") Is Nothing Then
categoryID = Request("id")
End If
categoryName =
AdventureWorks.DataAccessLayer.Products.GetCategoryName(Integer.Parse(categoryID))
lblCategory.Text = categoryName
Dim data =
AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(Integer.Parse(categoryI
D))
gvProducts.DataSource = data
gvProducts.DataBind()
End If
Lab Instructions: Applying Master Pages and CSS 11
Master.StatusMessage = "You are on the Products page"
End Sub
4. Run the application by pressing CTRL+F5.
5. On the Products page, scroll down to see the status message.
6. Open the About page.
7. On the About page, notice the status message.
8. Close Windows Internet Explorer.
9. Close Visual Studio 2010.
Results: After completing this exercise, you should have added a Label control in the Site.Master
master page to display status messages to users, created a property in the Site.Master master page to
set the value of the Label control, and set the value of the property on two pages consuming the
Site.Master master page.
12 Lab Instructions: Applying Master Pages and CSS
Exercise 4: Implement Control Skins
The main tasks for this exercise are as follows:
1. Create a new theme named Default.
2. Create a Controls.skin file in the Default theme.
3. Create two standard control skins.
4. Apply one skin to a ListBox control.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 04 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 04 folder.
Task 2: Create a new theme named Default
Add new theme folder named Default to project.
Task 3: Create a Controls.skin file in the Default theme
Add a new skin file named Controls.skin to the Default theme folder.
Task 4: Create two standard control skins
1. Replace the existing markup in the Controls.skin file with the following markup.
<asp:ListBox runat="server" SkinID="BlueListBox" Height="270px" Width="186px"
BackColor="AliceBlue" ForeColor="Black"/>
<asp:ListBox runat="server" SkinID="RedListBox" Height="270px" Width="186px"
BackColor="DarkCyan" ForeColor="White"/>
2. Save and close the Controls.skin file.
Task 5: Apply one skin to a ListBox control
1. Open the Default.aspx Web Form.
2. Add the following markup to the Page directive.
<%@ Page Title="Home Page" ... Theme="Default" %>
3. Add the SkinId attribute to the lbCategories ListBox control.
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"
DataValueField="ProductCategoryID" Height="270px" Width="186px" SkinID="BlueListBox">
4. Run the application.
Note: Observe the light blue background color in the ListBox control.
5. Close Windows Internet Explorer.
6. Close Visual Studio 2010.
Results: After completing this exercise, you should have created a new theme, added a skin file to the
theme containing two named skins for the ListBox control, and applied a named skin to the ListBox
control on the Default.aspx Web Form.
Lab Instructions: Applying Master Pages and CSS 13
Exercise 5: Apply Styles and Themes
The main tasks for this exercise are as follows:
1. Add existing style sheets to project.
2. Modify the existing styles.
3. Create two themes based on existing styles.
4. Change the theme in Web.config.
5. Test the new theme.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 05 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 05 folder.
Task 2: Add existing style sheets to project
Add the files StyleA.css and StyleB.css to the Styles folder. The files are located in the D:\Lab
Files\CS\Lab 11\Starter\Exercise 05 or D:\Lab Files\VB\Lab 11\Starter\Exercise 05 folder.
Task 3: Modify the existing styles
1. Open the StyleB.css file.
2. In the CSS Outline window, modify the .header, class, by using the Modify Style dialog box.
3. In the Modify Style dialog box, select the Background category.
14 Lab Instructions: Applying Master Pages and CSS
4. Change the background color to Red, and close the Modify Style dialog box.
5. Save and close the StyleB.css file.
Task 4: Create two themes based on existing styles
1. Create two new folders named Blue and Red, in the App_Themes folder.
2. Move the StyleA.css file to the Blue folder.
3. Move the StyleB.css file to the Red folder.
4. Open the Default.aspx Web Form.
5. Remove the SkinId attribute and value from the ListBox control.
SkinID="BlueListBox"
6. Remove the theme attribute and value from the Page directive.
Theme="Default"
7. Save and close the Default.aspx file.
Task 5: Change the theme in the Web.config file
1. Open the Web.config file.
2. Set the global page theme to the Red, by adding the pages element with the theme attribute to the
system.web element.
<pages theme="Red"/>
</system.web>
3. Save and close the Web.config file.
Task 6: Test the new theme
1. Run the application.
Note: Observe the new colors and slightly different layout.
2. Close Windows Internet Explorer.
3. Close Visual Studio 2010.
Task 7: Turn off the virtual machine and revert the changes
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Results: After completing this exercise, you should have applied styles to existing elements and
implemented a theme in your application.
Lab Instructions: Developing Client-side Scripts and Services 1
Module 12
Lab Instructions: Developing Client-side Scripts and Services
Contents:
Exercise 1: Using jQuery 4
Exercise 2: Using Advanced jQuery 7
Exercise 3: Creating a WCF Service 9
2 Lab Instructions: Develop ping Client-side Scrippts and Services
LLab 12: Creating Clien
O
A
In
In
jQ
in
Objectives
fter completin
Enable clien
Use jQuery
Embed jQu
Create a W
ntroduction
n this lab, you w
Query. You will
nvoke it using t
ng this lab, you
nt-side sorting
selectors.
uery visual effe
WCF Service and
n
will enhance t
l also embed jQ
the client-side
t-side SScripts aand Servvices
u will be able tto:
g.
ects.
d invoke it usinng the client-sside code.
he shopping c
Query visual e
e code.
cart interface t
effects in your
o support clie
application, cr
nt-side sorting
reate a WCF se
g, and use sele
ervice, and the
ectors in
en
Lab Instructions: Devveloping Client-side Scripts and Services 3
L
A
or
ite
Yo
ho
pr
Lab Scen
dventure Wor
r her shopping
ems in the car
ou have also b
over the mous
roducts, and t
nario
ks has designe
g cart. After th
rt.
ed a shopping
e products are
cart applicatio
e added, the u
on that allows
ser can click o
the user to ad
on the Cart lin
dd products in
k to view the c
to his
current
been requested
se over the pro
he service mus
d to display ad
oduct name. In
st be callable f
dvertisement in
n addition, you
from client-sid
nformation ab
u must create a
de code.
bout the produ
a WCF service
ucts when the
for retrieving
users
4 Lab Instructions: Developing Client-side Scripts and Services
Exercise 1: Using jQuery
The main tasks for this lab are as follows:
Register a jQuery library in the HTML header.
Use selectors and events.
Use the tableSorter jQuery library to allow client-side sorting.
Task 1: Open an existing ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 12\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 12\Starter\Exercise 01 folder.
Task 2: Register a jQuery library in the HTML header
1. Open the Site.Master master page.
2. Ensure that the jquery-1.4.1.js and jquery.tablesorter.min.js file are located in the Scripts folder.
3. In the head element of the Site.Master file, add the following script elements.
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script src='<%= ResolveUrl("~/Scripts/jquery-1.4.1.js") %>'
type="text/javascript"></script>
<script src='<%= ResolveUrl("~/Scripts/jquery.tablesorter.min.js") %>'
type="text/javascript"></script>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
Note: Make sure that you add the closing script tag (</script>) and not the self-closing script tag
(</>). The self-closing tag for the script references is not recognized by the browsers.
Best Practices: For Web Forms applications, you can use the ResolveUrl method, which correctly
resolves the URL relative to the request.
Task 3: Use selectors and events
1. Run the application.
2. Select the Bike Stands product category and click Submit.
3. Select the All-Purpose Bike Stand product.
4. Add the product to the shopping cart.
5. View the source for the rendered page.
6. Locate the gvCart GridView control, and note the ID for the rendered server control.
<table cellspacing="0" rules="all" border="1" id="MainContent_gvCart" style="border-
collapse:collapse;">
7. Close the source window.
Lab Instructions: Developing Client-side Scripts and Services 5
8. Close Windows Internet Explorer.
9. In the Site.Master master page, insert the following JavaScript element, after the closing html tag.
<script type="text/javascript">
$(document).ready(function () {
$("#MainContent_gvCart").tablesorter();
});
</script>
Task 4: Use the tableSorter jQuery library to allow client-side sorting
1. Open the ShoppingCart.aspx Web Form in Code view.
2. Update the Page_Load method to reflect the following code. (This ensures that the thead and tbody
HTML elements are rendered with the GridView control.)
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["_cart"] != null)
{
List<clsShoppingCart> cart = (List<clsShoppingCart>) Session["_cart"];
gvCart.DataSource = cart;
gvCart.DataBind();
}
else
{
lblMessage.Text = "Your cart is empty";
btnPlaceOrder.Visible = false;
}
}
if (this.gvCart.Rows.Count > 0)
{
gvCart.UseAccessibleHeader = true;
gvCart.HeaderRow.TableSection = TableRowSection.TableHeader;
gvCart.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
If Not Session("_cart") Is Nothing Then
Dim cart = CType(Session("_cart"), List(Of clsShoppingCart))
gvCart.DataSource = cart
gvCart.DataBind()
Else
lblMessage.Text = "Your cart is empty"
btnPlaceOrder.Visible = False
End If
If gvCart.Rows.Count > 0 Then
gvCart.UseAccessibleHeader = True
gvCart.HeaderRow.TableSection = TableRowSection.TableHeader
gvCart.FooterRow.TableSection = TableRowSection.TableFooter
End If
End Sub
3. Run the application.
4. Select the Bike Stands product category, and then click Submit.
6 Lab Instructions: Developing Client-side Scripts and Services
5. Select the All-Purpose Bike Stand product.
6. Add the product to the shopping cart.
7. Continue shopping.
8. Select the Bib-Shorts product category, and then click Submit.
9. Select the Men's Bib-Shorts, L product.
10. Add the product to the shopping cart.
11. View the source for the rendered page.
12. Locate the gvCart GridView control, and note that the thead and tbody HTML elements are
rendered.
<table cellspacing="0" rules="all" border="1" id="MainContent_gvCart" style="border-
collapse:collapse;">
<thead>
<tr>
<th scope="col">ID</th><th scope="col">Name</th><th
scope="col">Price</th><th scope="col">Quantity</th>
</tr>
</thead><tbody>
<tr>
<td>879</td><td>All-Purpose Bike Stand</td><td>1</td><td>159</td>
</tr>
</tbody><tfoot>
13. Close the source window.
14. Click the ID column header.
Note: Notice how the rows are sorted ascending according to the value of the ID column for the
individual rows.
15. Close Windows Internet Explorer.
16. Close Visual Studio 2010.
Result: At the end of this exercise, you should have enhanced the ShoppingCart interface to support
client-side sorting. You also learned how to perform script reference and use selectors in jQuery.
Lab Instructions: Developing Client-side Scripts and Services 7
Exercise 2: Using Advanced jQuery
The main tasks for this exercise are as follows:
1. Implement jQuery events and effects.
2. Create a custom plug-in.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 12\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 12\Starter\Exercise 02 folder.
Task 2: Implement jQuery events and effects
1. Open the Products.aspx Web Form.
2. Locate the markup for the GridView control named gvProducts.
3. Append a custom TemplateField column to the Columns element of the gvProducts GridView
control.
<asp:BoundField DataField="ListPrice" HeaderText="List Price"
DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="Ad">
<ItemTemplate>
<div style="display: none">
Advertisement for
<%# Eval("Name") %>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
4. Append the following script element to the Products.aspx Web Form, at the end of the Content
control with an ID attribute value of BodyContent.
<script type="text/javascript">
$(document).ready(function () {
$("a").mouseover(function () {
var divs = $(this).closest("tr").find("div").fadeIn("slow");
});
$("a").mouseout(function () {
var divs = $(this).closest("tr").find("div").fadeOut("slow");
});
});
</script>
</asp:Content>
5. Run the application.
6. On the Products page, hover the mouse over the name of the product.
Note: The custom advertisement message is displayed in the rightmost column.
7. Close Windows Internet Explorer.
Task 3: Create a custom plug-in
1. Add the following markup and code in the script element in the Products.aspx Web Form.
<script type="text/javascript">
8 Lab Instructions: Developing Client-side Scripts and Services
$(document).ready(function () {
$("a").mouseover(function () {
var divs = $(this).closest("tr").find("div").fadeIn("slow");
});
$("a").mouseout(function () {
var divs = $(this).closest("tr").find("div").fadeOut("slow");
});
});
jQuery.fn.fadeInFadeOut = function (speed) {
$(this).fadeIn(speed, function () {
$(this).fadeOut(speed);
});
}
$(document).ready(function () {
$("a").mouseover(function () {
$(this).closest("tr").find("div").fadeInFadeOut("slow");
});
});
</script>
2. Run the application.
3. On the Products page, hover the mouse over the name of the product.
Note: The custom advertisement message is displayed in the rightmost column, but now it closes after
a short period.
4. Close Windows Internet Explorer.
5. Close Visual Studio 2010.
Result: After this exercise, you should be able to embed jQuery effects in your application.
Lab Instructions: Developing Client-side Scripts and Services 9
Exercise 3: Creating a WCF Service
The main tasks for this exercise are as follows:
1. Create an Ajax-enabled WCF service.
2. Add logic to the query, and return a random product from the database.
3. Examine the service configuration in the Web.config file.
4. Invoke WCF service using client-side code from the master page.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 12\Starter\Exercise 03 or D:\Lab
Files\VB\Lab 12\Starter\Exercise 03 folder.
Task 2: Create an Ajax-enabled WCF service
Add a new Ajax-enabled WCF service named ProductsService to the project.
Task 3: Add Logic to the query and return a random product from the database
1. 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()>
2. Add the following GetRandomProduct method to the ProductsService.svc file.
[Visual C#]
public class ProductsService
{
[OperationContract]
public string GetRandomProduct()
{
var random = new Random();
10 Lab Instructions: Developing Client-side Scripts and Services
using (var db = new AdventureWorksEntities())
{
var randomNumber = random.Next(1, db.Products.Count() + 1);
var randomProduct = (from p in db.Products
where p.ProductID == randomNumber
select new { p.Name, p.ListPrice, p.ProductNumber
}).FirstOrDefault();
return new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(randomProduct);
}
}
}
[Visual Basic]
Public Class ProductsService
<OperationContract()>
Public Function GetRandomProduct() As String
Dim random = New Random()
Using db = New AdventureWorksEntities()
Dim randomNumber = random.[Next](1, db.Products.Count() + 1)
Dim randomProduct = (From p In db.Products
Where p.ProductID = randomNumber
Select New With {p.Name, p.ListPrice,
p.ProductNumber}).FirstOrDefault()
Return New
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(randomProduct)
End Using
End Function
End Class
Note: We are invoking the ProductsService from the client side. Hence, we want the returned format
to be XML or Json. For this reason, we are using the JavaScriptSerializer class to serialize the class into
a valid Json format.
Task 4: Examine the service configuration in the Web.config file
1. Open the Web.config file.
2. Examine the configuration markup in the system.serviceModel element, which has been created by
the Ajax-enabled WCF service project item template.
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="AdventureWorks.ProductsServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="AdventureWorks.ProductsService">
<endpoint address=""
behaviorConfiguration="AdventureWorks.ProductsServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="AdventureWorks.ProductsService" />
</service>
</services>
</system.serviceModel>
Lab Instructions: Developing Client-side Scripts and Services 11
Task 5: Invoke WCF service using client-side code from the master page
1. Open the Site.Master master page.
2. Add a reference to the ProductsService WCF by adding a ScriptManager control.
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/ProductsService.svc" />
</Services>
</asp:ScriptManager>
3. Add the following code to the Site.Master master page, after the closing html tag, at the end of the
script element.
getRandomProduct();
function getRandomProduct() {
ProductsService.GetRandomProduct(function (response) {
var product = eval('(' + response + ')');
document.getElementById("ProductName").innerHTML = product.Name;
document.getElementById("ProductNumber").innerHTML = product.ProductNumber;
document.getElementById("ProductPrice").innerHTML = product.ListPrice;
});
}
4. Add the following markup after the MainContent ContentPlaceHolder control.
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
<div style="margin: 10px 10px 10px 10px; padding: 10px 10px 10px 10px; border:
solid 2px black;
float: right; top: 150px; left: 500px; position: absolute;">
<h3>
FEATURED PRODUCT</h3>
Product Name:
<label id="ProductName">
</label>
<br />
Product Number:
<label id="ProductNumber">
</label>
<br />
Product Price: $<label id="ProductPrice"></label>
<br />
</div>
</div>
<div class="clear">
</div>
5. Run the application.
Note: The random product is displayed on the right side.
12 Lab Instructions: Developing Client-side Scripts and Services
6. Close Windows Internet Explorer.
Task 6: Turn off the virtual machine and revert the changes
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Result: After this exercise, you should have created a WCF service and invoked it using the client-side
code.
Lab Instructions: Implementing Advanced Ajax in a Web Application 1
Module 13
Lab Instructions: Implementing Advanced Ajax in a Web
Application
Contents:
Exercise 1: Using Microsoft Ajax in an MVC Page 4
Exercise 2: Using jQuery in an MVC View 7
Exercise 3: Handling Events 9
2 Lab Instructions: Implem menting Advanced Aja ax in a Web Application
L
A
Lab 13:
Adventu
Implem
ureWor
menting
ks Web
Advan
b Applic
ced Aja
cation
ax for thhe
Lab Insttructions: Implementing Advanced Ajax inn a Web Application 3
L
A
as
M
en
In
th
To
w
In
th
O
A
In
In
Yo
Lab Scen
dding the pro
sked to enhan
Management w
ncourage purc
n addition, they
he user selects
o do this, whe
when the user c
n this lab, you w
he different cli
Objectives
fter completin
Dynamicall
Dynamicall
Add Ajax ev
ntroduction
n this lab, you w
ou will also use
nario
duct catalog t
ce the usabilit
o the Adventu
y of the catalo
ureWorks webs
og.
site has been aa success. Noww, you have beeen
would like to d
chases.
isplay two Featured Productts when a user clicks a produuct category, too
y would like to
a category.
o show all of thhe products annd product cattegories on thhe same page wwhen
n a user clicks
clicks the Subm
and a category, yo
mit button, yo
ou will need to
ou will need to
o load the prod
load all produ
ducts featured
ucts.
d dynamically,
will explore th
ent events.
he features of jQuery and Aja ax in an MVC aapplication. Yoou will also exaamine
ng this lab, studdents will be aable to:
y load contentt into a view uusing Microsoftt Ajax Library.
y load contentt into a view uusing jQuery Ajjax.
vent handlers using jQuery AAjax.
n
will add Ajax l
e jQuery in an
ibraries to the
MVC view, an
pages and ma
nd handle even
view. aster page, an
nts using jQue
d create a par
ery.
rtial Ajax MVC
4 Lab Instructions: Implementing Advanced Ajax in a Web Application
Exercise 1: Using Microsoft Ajax in an MVC Page
The main tasks for this exercise are as follows:
1. Add the Ajax libraries to the pages.
2. Update the Index action method.
3. Create an Ajax Product Categories partial view.
4. Render the Partial view on the Index view.
Task 1: Open an existing ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorksMvc solution from the D:\Lab Files\CS\Lab 13\Starter\Exercise 01 or
D:\Lab Files\VB\Lab 13\Starter\Exercise 01 folder.
Task 2: Add the Ajax libraries to the pages
1. Open the Site.Master file, located in the Views/Shared folder.
2. At the top of the Site.Master file, in the head element, add a reference to the Microsoft Ajax
libraries.
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>"
type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
type="text/javascript"></script>
Task 3: Update the Index action method
1. Locate the Index action method in the Products controller.
2. Return the product categories from the Index action method by modifying the existing code.
[Visual C#]
public ActionResult Index(string CategoryID)
{
int id = int.Parse(CategoryID);
var prodCategories = pr.GetCategories();
return View(prodCategories);
}
[Visual Basic]
Public Function Index(ByVal CategoryID As String) As ActionResult
Dim id As Integer = CInt(CategoryID)
Dim prodCategories = pr.GetCategories()
Return View(prodCategories)
End Function
Task 4: Create an Ajax Product Categories partial view
1. Create a strongly typed, partial view named _AjaxProductCategories, based on the
IEnumerable<AdventureWorksMvc.Models.ProductCategory> or IEnumerable(Of
AdventureWorksMvc.Models.ProductCategory) data class.
Lab Instructions: Implementing Advanced Ajax in a Web Application 5
2. Insert the following markup and code in the _AjaxProductCategories.ascx file, after the Control
directive.
[Visual C#]
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "productCategories" }))
{ %>
<select size="4" id="CategoryID" name="CategoryID" style="height: 270px; width: 186px;">
<% foreach (var ProductCategory in Model)
{ %>
<option value="<%= ProductCategory.ProductCategoryID %>">
<%= Html.Encode(ProductCategory.Name)%>
</option>
<% } %>
</select>
<div id="productCategories">
</div>
<% } %>
[Visual Basic]
<% Using (Ajax.BeginForm(New AjaxOptions With {.UpdateTargetId = "productCategories"
}))%>
<select size="4" id="CategoryID" name="CategoryID" style="height: 270px; width: 186px;">
<% For Each ProductCategory In Model%>
<option value="<%= ProductCategory.ProductCategoryID %>">
<%= Html.Encode(ProductCategory.Name)%>
</option>
<% Next%>
</select>
<div id="productCategories">
</div>
<% End Using%>
6 Lab Instructions: Implementing Advanced Ajax in a Web Application
Task 5: Render the Partial view on the Index view
1. Open the Index.aspx view in the Views/Products folder.
2. Delete the existing markup in the Content2 Content control.
3. Add the following markup to the Index view, at the top of the Content2 Content control.
[Visual C#]
<h2>
Product Catalog</h2>
<label>
Choose a Category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model);%>
[Visual Basic]
<h2>
Product Catalog</h2>
<label>
Choose a category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model)%>
4. Delete the existing markup in the Content1 Content control.
5. Add the following markup to the Index view, at the top of the Content1 Content control.
Products
6. Base the Index view on a different data class, by modifying the Inherits attribute value in the Page
directive.
[Visual C#]
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Mo
dels.ProductCategory>>"
[Visual Basic]
Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of
AdventureWorksMvc.ProductCategory))"
7. Build the solution and fix any errors.
8. Close Visual Studio 2010.
Results: After this exercise, you should have added the product line to the index view using the
Microsoft Ajax Library.
Lab Instructions: Implementing Advanced Ajax in a Web Application 7
Exercise 2: Using jQuery in an MVC View
The main tasks for this exercise are as follows:
1. Add the jQuery library to the pages.
2. Create a Featured Products action.
3. Load the Featured Products when a category is clicked.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the D:\Lab Files\CS\Lab 13\Starter\Exercise 02 or
D:\Lab Files\VB\Lab 13\Starter\Exercise 02 folder.
Task 2: Add the jQuery library to the pages
1. Open the Site.Master file, located in the Views/Shared folder.
2. At the top of the Site.Master file, in the head element, add a reference to the Microsoft Ajax
libraries.
<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"
type="text/javascript"></script>
Task 3: Create the Featured Products action
1. Open the ProductsController.cs or ProductsController.vb file in the Controllers folder.
2. Create an action for the Ajax method to call. The following code returns a view populated with
products.
[Visual C#]
public ViewResult FeaturedProducts(string CategoryId)
{
int id = int.Parse(CategoryId);
var products = pr.GetProductsByCategory(id);
return View("_FeaturedProducts", products);
}
[Visual Basic]
Public Function FeaturedProducts(ByVal CategoryId As String) As ViewResult
Dim id As Integer = Integer.Parse(CategoryId)
Dim products = pr.GetProductsByCategory(id)
Return View("_FeaturedProducts", products)
End Function
Task 4: Load the Featured Products when a category is clicked
1. Open the Index.aspx view in the Views/Products folder.
2. The Ajax method needs a place to put the results from the called function. Add a div element at the
bottom of the page, before the closing Content tag.
<br />
<div id="featured-products"></div>
8 Lab Instructions: Implementing Advanced Ajax in a Web Application
3. Create the Ajax method call. This function calls the controller action, and then returns the results into
the featured products div created earlier. Add the following markup to handle the click event for
the rendered select element, at the bottom of the page, before the closing Content tag.
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryID").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>', {
CategoryId: id });
});
});
</script>
4. Run the application.
5. In Windows Internet Explorer, click Submit.
6. In Windows Internet Explorer, in the Choose a category list, click Bib-shorts.
Note: The products for the chosen category are displayed below the list.
7. Close Windows Internet Explorer.
8. Close Visual Studio 2010.
Results: After this exercise, you should have added a "Featured Products" section to the Index.aspx
page. Using jQuery, the page should update the featured products based on the selection in the
Product Categories list.
Lab Instructions: Implementing Advanced Ajax in a Web Application 9
Exercise 3: Handling Events
The main tasks for this exercise are as follows:
1. Display a status message.
2. Alert the user when an error occurs.
3. Test the Index view.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the D:\Lab Files\CS\Lab 13\Starter\Exercise 03 or
D:\Lab Files\VB\Lab 13\Starter\Exercise 03 folder.
Task 2: Display a status message
1. Open the Index.aspx page in the Views/Products folder.
2. Before the featured-products div element, add a div to display the Ajax status messages.
<div class="log"></div>
3. After the featured-products div element, add a div to display the Ajax error messages.
<div class="error"></div>
4. In the $(document).ready jQuery function, add the following functions to display and hide the status
messages.
$(document).ready(function () {
$("#CategoryID").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>', {
CategoryId: id });
});
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
});
Task 3: Alert the user when an error occurs
1. After the .ajaxComplete function, add the following function to display the alert.
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});
2. Ensure that the Index view page matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.ProductCategory>>
" %>
10 Lab Instructions: Implementing Advanced Ajax in a Web Application
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Products
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Product Catalog</h2>
<label>
Choose a category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model);%>
<br />
<div class="log">
</div>
<div id="featured-products">
</div>
<div class="error">
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryID").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>', {
CategoryId: id });
});
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});
});
</script>
</asp:Content>
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of
AdventureWorksMvc.ProductCategory))" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Products
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Product Catalog</h2>
<label>
Choose a category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model)%>
<br />
<div class="log">
</div>
<div id="featured-products">
</div>
<div class="error">
</div>
<script type="text/javascript">
Lab Instructions: Implementing Advanced Ajax in a Web Application 11
$(document).ready(function () {
$("#CategoryID").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>', {
CategoryId: id });
});
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});
});
</script>
</asp:Content>
Task 4: Test the Index view
1. Run the application.
2. In Windows Internet Explorer, click Submit.
3. In Windows Internet Explorer, in the Choose a category list, click Bib-shorts.
Note: The products for the chosen category are displayed below the list, but first you see the
Loading... notice.
4. Close Windows Internet Explorer.
5. Close Visual Studio 2010.
Task 5: Turn off the virtual machine and revert the changes
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Results: After this exercise, you should have used jQuery to provide feedback on the page.
Lab Instructions: ASP.NET Deployments 1
Module 14
Lab Instructions: ASP.NET Deployments
Contents:
Exercise 1: Creating a Profile for Deploying a Web Application Project
Using One-Click Publish 4
Exercise 2: Creating a Web Deployment Package 7
2 Lab Instructions: ASP.NE ET Deployments
LLab 14: Deploy
N
pr
O
A
In
In
w
Note: You can
rogramming la
Objectives
fter completin
Create
Create
ntroduction
n this lab, you w
will also create
ying AdvventureeWorks
perform the ta
anguage.
ng this lab, you
a One-Click P
and deploy a
n
will create ap
a web deploym
asks in this lab
u will be able t
Publish profile
web deploym
profile for depl
ment package
b by using eithe
to:
e.
ment package.
loying a web a
and use it to
er Visual C#
as your
application pro
deploy a web
oject using one
application to
e-click publish
o IIS.
h. You
Lab Instructions: ASP.NET Deployments 3
L
A
de
di
Lab Scen
dventureWork
eployment. Yo
isadvantages o
nario
ks is preparing
ou will investig
of each.
to deploy the
gate the differe
e application to
ent methods o
o the different
of deployment
t servers for te
and the advan
sting, staging,
ntages and
and
4 Lab Instructions: ASP.NET Deployments
Exercise 1: Creating a Profile for Deploying a Web Application Project
Using One-Click Publish
The main tasks for this exercise are as follows:
1. Create a new ASP.NET web application.
2. Create an ASP.NET Application Services database.
3. Set the active build configuration.
4. Specify which files and IIS settings to deploy.
5. Specify which SQL Server scripts run during deployment.
6. Update the connection string in the Web.config file by creating a transform file.
7. Create a publish profile.
Task 1: Create a new ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Create a new ASP.NET Web Application named Deployment in the D:\Lab Files\CS\Lab
14\Starter\Exercise 01 or D:\Lab Files\VB\Lab 14\Starter\Exercise 01 folder.
Task 2: Create an ASP.NET Application Services database
1. View the Account\Register.aspx Web Form in Windows Internet Explorer.
2. On the Create New Account page, type the following information, and then click Create User.
User Name: Student
E-mail: student@adventureworks.com
Password: Pa$$w0rd
Confirm Password: Pa$$w0rd
Note: An ASP.NET Application Services SQL Server database file ASPNETDB.MDF is created in the
App_Data folder, and the values that you entered have been saved to it.
3. Close Windows Internet Explorer.
Task 3: Set the active build configuration
1. In Solution Explorer, click Deployment.
2. On the Solutions Configuration list, click Release.
Task 4: Specify which files and IIS settings to deploy
1. Open the Project Designer for the Deployment project.
2. Select the Package/Publish Web tab.
3. Ensure that Active (Release) is selected in the Configuration list.
4. Select the Exclude generated debug symbols check box.
5. Ensure that the Include all databases configured in Package/Publish SQL tab check box is
selected.
Lab Instructions: ASP.NET Deployments 5
6. Save the changes.
Task 5: Specify which SQL Server scripts run during deployment
1. Select the Package/Publish SQL tab.
2. Import the database settings from the Web.config file.
3. In the Connection string for destination database box, type Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;Integrated
Security=True;User Instance=True. You can optionally copy the connection string from the
Connection string for source database box.
4. Ensure that the Pull data and/or schema from an existing database check box is selected.
5. Set the database scripting options to Schema and Data.
6. Save the changes.
Task 6: Update the connection string in the Web.config file by creating a transform file
1. [Visual Basic] Show all files for the Deployment project in Solution Explorer.
2. Expand the Web.config file.
3. Open the Web.Release.config file.
4. Examine and delete the block of comments that contains a connectionStrings element.
5. Insert the following markup after the opening configuration element.
<connectionStrings>
<add name="ApplicationServices"
connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>
Note: If you were not using a database file, as in this case, you would typically use the connection
string that you received from your hosting company.
6. Save and close the Web.Release.config file.
Task 7: Create a publish profile
1. Open the Publish Web dialog box, by clicking Publish Deployment on the Build menu.
2. Mark the web application as an IIS application on the destination server.
Note: If your hosting company advises you to allow untrusted certificates, select the Allow untrusted
certificate check box.
3. Enter the credentials for the local user admin.
4. Select the Save password check box.
5. Set the service URL to localhost.
6. Set the site/application URL to Default Web Site/Deployment.
6 Lab Instructions: ASP.NET Deployments
7. Save the profile and close the Publish Web dialog box.
8. Close Visual Studio 2010.
Results: After this exercise, you should have created a profile to deploy your web application project
using one-click publish.
Lab Instructions: ASP.NET Deployments 7
Exercise 2: Creating a Web Deployment Package
The main tasks for this exercise are as follows:
1. Open an existing ASP.NET web application.
2. Add an existing database and configure an ASP.NET web application.
3. Create a destination database.
4. Specify deployment packaging settings.
5. Specify SQL Server scripts to run during deployment.
6. Specify the scripts not to run in a transaction.
7. Change the connection string in the deployed Web.config file.
8. Create a package and import it into IIS.
9. Test the web application.
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the Deployment solution from the D:\Lab Files\CS\Lab 14\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 14\Starter\Exercise 02 folder.
Task 2: Add an existing database and configure an ASP.NET web application
1. Add the existing AdventureWorksLT2008R2_Data.mdf SQL Server database file to the App_Data
folder. The file is located in the D:\Lab Files\CS\Lab 14\Starter or D:\Lab Files\VB\Lab 14\Starter
folder.
2. Open the Web.config file.
3. In the connectionStrings element, add a connection string for the new database.
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="AW"
connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AdventureWorksLT2008R2_Data.mdf;I
ntegrated Security=True;Connect Timeout=30;User
Instance=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
4. Save and close the Web.config file.
5. Run the application.
6. Click the Log In link.
7. Enter credentials for the user student with a password of Pa$$w0rd, and then log in.
8. Close Windows Internet Explorer.
Task 3: Create a destination database
1. Open Server Explorer.
2. In Server Explorer, right-click Data Connections, and then click Create New SQL Server Database.
8 Lab Instructions: ASP.NET Deployments
3. In the Create New SQL Server Database dialog box, enter the following information, and then click
OK.
Server name: 10264a-gen-dev\SQLEXPRESS
New database name: DeploymentTest
Task 4: Specify deployment packaging settings
1. Open the Project Designer for the Deployment project.
2. Select the Package/Publish Web tab.
3. Ensure that the following settings have been specified:
Active (Debug) is selected in the Configuration list.
Only files needed to run this application is selected in the list in the Items to deploy (applies
to all deployment methods) section.
The Exclude generated debug symbols check box is cleared.
The Exclude files from the App_Data folder check box is selected.
The Include all databases configured in Package/Publish SQL tab check box is selected.
The Create deployment package as a zip file check box is selected.
The Location where package will be created box contains the following value.
obj\Debug\Package\Deployment.zip
4. In the IIS Web site/application name to use on the destination server box, type Default Web
Site/Deployment.
5. Save the changes.
Task 5: Specify SQL Server scripts to run during deployment
1. Select the Package/Publish SQL tab.
2. Ensure that All Configurations is selected in the Configuration list.
3. Import the database settings from the Web.config file.
4. Ensure that Active (Debug) is selected in the Configuration list.
5. Ensure that the ApplicationServices-Deployment row is selected in the Database Entries list.
6. In Server Explorer, expand the Data Connections folder and select the 10264a-gen-
dev\sqlexpress.DeploymentTest.dbo database.
7. Copy the value of the Connection String property from the Properties window.
8. In the Project Designer, in the Connection string for destination database box, paste the copied
value, Data Source=10264A-GEN-DEV\SQLEXPRESS;Initial Catalog=DeploymentTest;Integrated
Security=True;Pooling=False.
9. Ensure that the Pull data and/or schema from an existing database check box is selected.
10. Set the database scripting options to Schema and Data.
11. Ensure that the AW-Deployment row is selected in the Database Entries list.
12. In the Connection string for destination database box, paste the copied value, Data
Source=10264A-GEN-DEV\SQLEXPRESS;Initial Catalog=DeploymentTest;Integrated
Security=True;Pooling=False.
Lab Instructions: ASP.NET Deployments 9
Note: You are using the same destination connection string for both local databases. Therefore, during
deployment, the scripts that create and populate database objects will all run in the same database.
13. Ensure that the Pull data and/or schema from an existing database check box is selected.
14. In the Connection string for source database box, type Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AdventureWorksLT2008R2_Data.m
df;Integrated Security=True;Connect Timeout=30;User Instance=True.
15. Set the database scripting options to Schema and Data.
16. Add the D:\Lab Files\CS\Lab 14\Starter\DeploymentGrant.sql or D:\Lab Files\VB\Lab
14\Starter\DeploymentGrant.sql script, by clicking Add Script.
17. Save the changes.
Task 6: Specify the scripts not to run in a transaction
1. Open the D:\Lab Files\CS\Lab 14\Starter\Exercise 02\Deployment\Deployment.csproj or the
D:\Lab Files\VB\Lab 14\Starter\Exercise 02\Deployment\Deployment.vbproj file in Notepad.
2. Open the Replace dialog box.
3. In the Replace dialog box, search for Transacted="True" and replace with Transacted="False".
Replace all instances.
4. Save the changes and close the project file.
5. When Visual Studio asks if you want to reload the project, click the Reload button.
Task 7: Change the connection string in the deployed Web.config file
1. [Visual Basic] Show all files for the Deployment project in Solution Explorer.
2. Expand the Web.config file.
3. Open the Web.Debug.config file.
4. Examine and delete the block of comments that contains a connectionStrings element.
5. Insert the following markup after the opening configuration element.
<connectionStrings>
<add name="ApplicationServices"
connectionString="Data Source=10264A-GEN-DEV\SQLEXPRESS;Initial
Catalog=DeploymentTest;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient" xdt:Transform="SetAttributes"
xdt:Locator="Match(name)" />
<add name="AW"
connectionString="Data Source=10264A-GEN-DEV\SQLEXPRESS;Initial
Catalog=DeploymentTest;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>
6. Save and close the Web.Debug.config file.
Task 8: Create a package and import it into IIS
1. Build a deployment package by using the Project menu.
10 Lab Instructions: ASP.NET Deployments
Note: Visual Studio builds the project and creates the deployment package, displaying a log in the
Output window. As part of the package creation process, the Web Deploy dbFullSQL provider
creates two SQL server scriptsone for each source database. There is only one destination
database, and both of these scripts will run in that database when you import the package.
2. Open Internet Information Services (IIS) Manager as an administrator.
3. In Control Panel, click System and Security, and then click Administrative Tools.
4. Right-click Internet Information Services (IIS) Manager, and then click Run as administrator.
5. In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then press
ENTER.
6. In Internet Information Services (IIS) Manager, expand 10264A-GEN-DEV (10264A-GEN-
DEV\Admin), expand Sites, and then click Default Web Site.
7. In the Actions pane, under Deploy, click Import Application.
8. In the Import Application Package wizard, use the D:\Lab Files\CS\Lab 14\Starter\Exercise
02\Deployment\obj\Debug\Package\Deployment.zip or D:\Lab Files\VB\Lab
14\Starter\Exercise 02\Deployment\obj\Debug\Package\Deployment.zip package.
9. Accept the default selected contents of the package.
10. Accept the default application paths and connection strings.
11. Click Finish.
12. Close Internet Information Services (IIS) Manager.
Task 9: Test the web application
1. Open Windows Internet Explorer, and browse to the following URL.
http://localhost/Deployment
Note: The Default.aspx page is displayed. It looks the same as it does when you run it in Visual
Studio 2010.
2. Click the Log In link.
3. Enter credentials for the user student with a password of Pa$$w0rd, and then log in.
Note: The Default.aspx page is displayed, with Welcome student! next to the Log Out link. This
demonstrates that the ASP.NET membership database was deployed successfully.
4. Close Windows Internet Explorer.
5. Close Visual Studio 2010.
Task 10: Turn off the virtual machine and revert the changes
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
Lab Instructions: ASP.NET Deployments 11
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Results: After this exercise, you should have created and deployed a Web Application using a Web
Deployment Package.
Lab Instructions: Developing a Web Application by Using Silverlight 1
Module 15
Lab Instructions: Developing a Web Application by Using
Silverlight
Contents:
Exercise 1: Creating a Silverlight Project 5
Exercise 2: Creating a Silverlight WCF Service 6
Exercise 3: Displaying Data by Using Silverlight Controls 8
2 Lab Instructions: Develop ping a Web Applicatiion by Using Silverligght
LLab 15: A Addingg Silverliight to
O
A
In
In
Si
Si
Objectives
fter completin
Create a Sil
Create a Sil
Display dat
ntroduction
n this lab, you w
ilverlight appli
ilverlight contr
ng this lab, you
verlight projec
verlight WCF
ta by using Silv
n
will learn how
cation will be
rol.
u will be able t
ct.
service.
verlight contro
to add Silverl
used to consu
a Web Applicaation
to:
ols.
ight to an exis
ume a WCF Ser
sting Adventur
rvice and displ
reWorks web a
lay the data by
application. Th
y using the Da
he
ataGrid
Lab Instructions: Developingg a Web Application by Using Silverlight 3
L
So
M
de
si
Lab Scen
ome of Adven
Management w
eveloping the
mple prototyp
nario
tureWorks co
wants to explor
AdventureWo
pe. The resultin
mpetitors are
re the feasibilit
orks web site in
ng prototype s
experiencing
ty of using RIA
n future. For th
should look sim
higher web tra
A technology t
his purpose, yo
milar to the fo
affic than Adve
o increase use
ou have been t
llowing screen
entureWorks.
er stickiness wh
tasked with cr
nshot.
hen
eating a
4 Lab Instructions: Developing a Web Application by Using Silverlight
Lab Instructions: Developing a Web Application by Using Silverlight 5
Exercise 1: Creating a Silverlight Project
The main tasks for this exercise are as follows:
Add a new Silverlight project.
Task 1: Open an existing ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. Open Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 15\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 15\Starter\Exercise 01 folder.
Task 2: Add a new Silverlight project
1. Add a new Microsoft
Silverlight
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.
3. Open the AdventureWorks solution at the following location.
Programming Language Location
Microsoft Visual C#
press CTRL+SHIFT+A.
item templates.
1. In Microsoft Hyper-V Manager, in the Virtual Machines pane, rig
then click Turn Off.
Revert.
Lab Answer Key: Developing MVC Models 1
Module 3
Lab Answer Key: Developing MVC Models
Contents:
Exercise 1: Exploring the AdventureWorks Database 2
Exercise 2: Adding an ADO.NET Entity Data Model 4
Exercise 3: Model Data Validation 10
2 Lab Answer Key: Developing MVC Models
Lab 3: Creating MVC Models
Exercise 1: Exploring the AdventureWorks Database
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. 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.
3. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Visual C#
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.
3. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 01
Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 01
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:\Lab Files\CS\Lab
04\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise
01\AdventureWorksMvc.sln and then click Open.
Task 2: Create a controller named BlogController
1. Create a controller named BlogController in the Controllers folder. The controller should not
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, and then
click Add.
2. Add the HandleErrorAttribute attribute to the BlogController class.
[Visual C#]
[HandleError]
[Visual Basic]
<HandleError()>
Annotate the BlogController with the following attribute.
[Visual C#]
[HandleError]
[Visual Basic]
<HandleError()>
Lab Answer Key: Developing MVC Controllers 3
3. Verify that the code in the BlogController code file matches the following code.
[Visual C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AdventureWorksMvc.Controllers
{
[HandleError]
public class BlogController : Controller
{
//
// GET: /Blog/
public ActionResult Index()
{
return View();
}
}
}
[Visual Basic]
Namespace AdventureWorksMvc
<HandleError()>
Public Class BlogController
Inherits System.Web.Mvc.Controller
'
' GET: /Blog
Function Index() As ActionResult
Return View()
End Function
End Class
End Namespace
4. Build the solution, and fix any errors.
In the AdventureWorksMvc Microsoft Visual Studio window, on the Build menu, click Build
Solution, or press CTRL+SHIFT+B.
5. Close Visual Studio 2010.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Exercise 2: Adding code to list the existing blog entries
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
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.
2. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 02
4 Lab Answer Key: Developing MVC Controllers
Programming Language Location
Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 02
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:\Lab Files\CS\Lab
04\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise
02\AdventureWorksMvc.sln and then click Open.
Task 2: Add a blogRepository object
1. Import the AdventureWorksMvc.Models namespace in the BlogController code file.
[Visual C#]
using AdventureWorksMvc.Models;
[Visual Basic]
Not applicable
a. In Solution Explorer, expand Controllers, and then double-click BlogController.cs or
BlogController.vb.
b. In the BlogController code file, insert the following code at the top of the file.
[Visual C#]
using AdventureWorksMvc.Models;
[Visual Basic]
Not applicable
2. Declare and instantiate a private BlogRepository object at the top of the BlogController class.
[Visual C#]
private BlogRepository blogRepository = new BlogRepository();
[Visual Basic]
Private blogRepository As New BlogRepository()
Task 3: Add code to the Index action method
1. Replace the existing code in the Index action method with code that returns all of the blog entries to
the view, by calling the GetAllBlogs method of the blogRepository object.
[Visual C#]
var blogs = blogRepository.GetAllBlogs();
return View(blogs);
[Visual Basic]
Dim blogs = blogRepository.GetAllBlogs()
Lab Answer Key: Developing MVC Controllers 5
Return View(blogs)
2. Verify that the final Index action method matches the following code:
[Visual C#]
public ActionResult Index()
{
var blogs = blogRepository.GetAllBlogs();
return View(blogs);
}
[Visual Basic]
Function Index() As ActionResult
Dim blogs = blogRepository.GetAllBlogs()
Return View(blogs)
End Function
1. Add a Blogger action method that takes the ID
Task 4: Create a Blogger action method
of the blogger as the only parameter.
[Visual C#]
public ActionResult Blogger(int id)
{
}
[Visual Basic]
Function Blogger(ByVal id As Integer) As ActionResult
End Function
2. Add code to the Blogger action method to return only the blog entries for the indicated blogger to
the view.
[Visual C#]
var blogs = blogRepository.GetAllBlogs(id);
return View(blogs);
[Visual Basic]
Dim blogs = blogRepository.GetAllBlogs(id)
Return View(blogs)
3. Verify that the final Blogger action method matches the following code.
[Visual C#]
public ActionResult Blogger(int id)
{
var blogs = blogRepository.GetAllBlogs(id);
return View(blogs);
}
6 Lab Answer Key: Developing MVC Controllers
[Visual Basic]
Function Blogger(ByVal id As Integer) As ActionResult
Dim blogs = blogRepository.GetAllBlogs(id)
Return View(blogs)
End Function
Task 5: Create a Details action method
1. Add a Details action method that takes the ID of the blog entry as its one parameter.
[Visual C#]
public ActionResult Details(int id)
{
}
[Visual Basic]
Function Details(ByVal id As Integer) As ActionResult
End Function
2. Add code to the Details action method to return only the indicated blog entry, to the view. However,
if the blog entry no longer exists, redirect the user to the Index view.
[Visual C#]
var blogEntry = blogRepository.GetBlog(id);
if (blogEntry == null)
return RedirectToAction("Index");
return View(blogEntry);
[Visual Basic]
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
3. Verify that the final Details action method matches the following code.
[Visual C#]
public ActionResult Details(int id)
{
var blogEntry = blogRepository.GetBlog(id);
if (blogEntry == null)
return RedirectToAction("Index");
return View(blogEntry);
}
[Visual Basic]
Function Details(ByVal id As Integer) As ActionResult
Lab Answer Key: Developing MVC Controllers 7
Dim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")
End If
Return View(blogEntry)
End Function
4. Build the solution, and fix any errors.
In the AdventureWorksMvc Microsoft Visual Studio window, on the Build menu, click Build
5. Close Visual Studio 2010.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Exercise 3: Adding code to create a new blog entry
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2. Open the AdventureWorksMvc solution from the following location.
1. Open Microsoft Visual Studio 2010.
1. Open Microsoft Visual Studio 2010.
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.
3. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 05\Starter\Exercise 01
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 01
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:\Lab Files\CS\Lab
05\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise
01\AdventureWorksMvc.sln and then click Open.
Task 2: Add a Blog menu item to the Site.Master page
1. Open the Site.Master page.
a. In Solution Explorer, expand Views, and then expand Shared.
b. Right-click Site.Master, and then click Open.
2. Add a menu item to the menu on the Site.Master master page, by using an Html.ActionLink
method wrapped in a li HTML element within the ul element with an id attribute value of menu. Add
the new menu item between the Home and About menu items.
[Visual C#]
<li><%= Html.ActionLink("Blog", "", "Blog")%></li>
[Visual Basic]
<li><%: Html.ActionLink("Blog", "", "Blog")%></li>
3. Verify that the ul element matches the following markup.
[Visual C#]
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("Blog", "", "Blog")%></li>
<li><%= Html.ActionLink("About", "About", "Home")%></li>
/ul>
[Visual Basic]
<ul id="menu">
Lab Answer Key: Developing MVC Views 3
<li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<li><%: Html.ActionLink("Blog", "", "Blog")%></li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>
1. Add a Blog subfolder to the Views folder.
Task 3: Add a view to display the complete list of blogs
a. In Solution Explorer, right-click Views, and then point to Add, and then click New Folder.
b. In Solution Explorer, in the new folder, type Blog, and then press ENTER.
2. d an empty view named Index.aspx, based on the Site.Master page, to the Blog folder.
a. In Solution Explorer, right-click Blog, point to Add, and then click View.
b. In the Add View dialog box, in the View name box, type Index, ensure the Select master page
3. Update the new view to a strongly-typed view of type
reWorksMvc.Models.Blog>> or
Update the Inherits property of the Page directive to the following.
Ad
check box is selected, and then click Add.
System.Web.Mvc.ViewPage<IEnumerable<Adventu
System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog)).
[Visual C#]
System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.Blog>
>
[Visual Basic]
System.Web.Mvc.ViewPage(Of IEnumerable (Of
AdventureWorksMvc.Blog))
4. Add the following markup and code to the Index view in the Content2 Content control,
immediately after the h2 element.
[Visual C#]
<% foreach (var item in Model)
{ %>
<div>
<%: Html.ActionLink("Details", "Details", new { id=item.BlogID })%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% } %>
[Visual Basic]
<% For Each item As AdventureWorksMvc.Blog In Model%>
<div>
<%: Html.ActionLink("Details", "Details", New With {.id = item.BlogID})%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% Next%>
4 Lab Answer Key: Developing MVC Views
5. Verify that the markup and code in the Index view matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.Blog>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Index</h2>
<% foreach (var item in Model)
{ %>
<div>
<%: Html.ActionLink("Details", "Details", new { id=item.BlogID })%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% } %>
</asp:Content>
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog))" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Index</h2>
<% For Each item As AdventureWorksMvc.Blog In Model%>
<div>
<%: Html.ActionLink("Details", "Details", New With {.id = item.BlogID})%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% Next%>
</asp:Content>
6. Build the solution, and fix any errors.
In the AdventureWorksMvc Microsoft Visual Studio window, on the Build menu, click Build
Solution, or press CTRL+SHIFT+B.
Task 4: Test the new view
1. Run the application.
a. In Solution Explorer, click AdventureWorksMvc.
b. In the AdventureWorksMvc Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.
2. Display the Blog view.
In the Welcome to AdventureWorks Windows Internet Explorer window, click Blog.
3. Close Windows
Internet Explorer
.
Lab Answer Key: Developing MVC Views 5
In the Index Windows Internet Explorer window, click the Close button.
4. Close Visual Studio 2010.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Exercise 2: Develop a Details MVC view
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
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.
2. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 05\Starter\Exercise 02
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 02
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:\Lab Files\CS\Lab
05\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise
02\AdventureWorksMvc.sln and then click Open.
Task 2: Add a strongly-typed details view named Details
1. Add an empty, strongly-typed view of type Blog, named Details based on the Site.Master master
page, to the Blog folder.
a. In Solution Explorer, expand Views, right-click Blog, point to Add, and then click View.
b. [Visual C#] In the Add View dialog box, in the View name box, type Details, select the Create a
strongly-typed view check box, in the View data class box, type
AdventureWorksMvc.Models.Blog, and then click Add.
-or-
[Visual Basic] In the Add View dialog box, in the View name box, type Details, select the
Create a strongly-typed view check box, in the View data class box, type
AdventureWorksMvc.Blog, and then click Add.
2. Add the following markup and code to the Details view in the Content2 Content control,
immediately after the h2 element.
Blogger:
<%: Model.Blogger.Name %>
DatePosted:
<%: Model.DatePosted %>
<h3>
<%: Model.Title %></h3>
<%: Model.BlogEntry %>
<p>
<%: Html.ActionLink("Back to List", "Index") %>
</p>
6 Lab Answer Key: Developing MVC Views
3. Verify that the markup and code in the Details view matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AdventureWorksMvc.Models.Blog>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Details</h2>
Blogger:
<%: Model.Blogger.Name %>
DatePosted:
<%: Model.DatePosted %>
<h3>
<%: Model.Title %></h3>
<%: Model.BlogEntry %>
<p>
<%: Html.ActionLink("Back to List", "Index") %>
</p>
</asp:Content>
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of AdventureWorksMvc.Blog)" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Details</h2>
Blogger:
<%: Model.Blogger.Name %>
DatePosted:
<%: Model.DatePosted %>
<h3>
<%: Model.Title %></h3>
<%: Model.BlogEntry %>
<p>
<%: Html.ActionLink("Back to List", "Index") %>
</p>
</asp:Content>
4. Test the Details view.
a. In Solution Explorer, click AdventureWorksMvc.
b. In the AdventureWorksMvc Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.
c. In the Welcome to AdventureWorks Windows Internet Explorer window, click Blog.
d. In the Index Windows Internet Explorer window, click Details.
5. Close Internet Explorer.
In the Details Windows Internet Explorer window, click the Close button.
6. Close Visual Studio 2010.
Lab Answer Key: Developing MVC Views 7
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Exercise 3: Develop a Create MVC view
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
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.
2. Open the AdventureWorksMvc solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 05\Starter\Exercise 03
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 03
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:\Lab Files\CS\Lab
05\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise
03\AdventureWorksMvc.sln and then click Open.
Task 2: Add a strongly-typed view named Blogger to list all of the blogs for a particular
blogger
1. Add an empty, strongly-typed view named Blogger based on the Site.Master master page, to the
Blog folder.
a. In Solution Explorer, expand Views, right-click Blog, point to Add, and then click View.
b. In the Add View dialog box, in the View name box, type Blogger, and then click Add.
2. Update the Blogger view to a strongly-typed view of type IEnumerable of type Blog.
[Visual C#]
System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.Blog>>
[Visual Basic]
System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog))
Update the Inherits property of the Page directive to the following.
[Visual C#]
System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.Blog>>
[Visual Basic]
System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog))
3. Add the following markup and code to the Blogger view in the Content2 Content control,
immediately after the h2 element.
[Visual C#]
<% foreach (var item in Model)
8 Lab Answer Key: Developing MVC Views
{ %>
<div>
<%: Html.ActionLink("Edit", "Edit", new { id=item.BlogID })%>
<%: Html.ActionLink("Delete", "Delete", new { id=item.BlogID })%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% } %>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
[Visual Basic]
<% For Each item As AdventureWorksMvc.Blog In Model%>
<div>
<%: Html.ActionLink("Edit", "Edit", New With {.id = item.BlogID})%>
<%: Html.ActionLink("Delete", "Delete", New With {.id = item.BlogID})%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% Next%>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
4. Verify that the markup and code in the Blogger view matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.Blog>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Blogger
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Blogger</h2>
<% foreach (var item in Model)
{ %>
<div>
<%: Html.ActionLink("Edit", "Edit", new { id=item.BlogID })%>
<%: Html.ActionLink("Delete", "Delete", new { id=item.BlogID })%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% } %>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
</asp:Content>
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog))" %>
Lab Answer Key: Developing MVC Views 9
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Blogger
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Blogger</h2>
<% For Each item As AdventureWorksMvc.Blog In Model%>
<div>
<%: Html.ActionLink("Edit", "Edit", New With {.id = item.BlogID})%>
<%: Html.ActionLink("Delete", "Delete", New With {.id = item.BlogID})%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% Next%>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
</asp:Content>
Task 3: Add a strongly-typed view named Create
1. Add an empty, strongly-typed view named Create based on the Site.Master master page, to the
Blog folder.
a. In Solution Explorer, expand Views, right-click Blog, point to Add, and then click View.
b. [Visual C#] In the Add View dialog box, in the View name box, type Create, select the Create a
strongly-typed view check box, in the View data class box, type
AdventureWorksMvc.Models.Blog, and then click Add.
-or-
[Visual Basic] In the Add View dialog box, in the View name box, type Create, select the
Create a strongly-typed view check box, in the View data class box, type
AdventureWorksMvc.Blog, and then click Add.
2. Add the following markup and code to the Create view in the Content2 Content control,
immediately after the h2 element.
[Visual C#]
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Title) %>
<%: Html.ValidationMessageFor(model => model.Title) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.BlogEntry) %>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(model => model.BlogEntry, new { cols = "85" })%>
<%: Html.ValidationMessageFor(model => model.BlogEntry) %>
</div>
</fieldset>
<input type="submit" value="Submit" />
<% } %>
10 Lab Answer Key: Developing MVC Views
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
</div>
[Visual Basic]
<% Using (Html.BeginForm())%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.Title)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(Function(m) m.Title)%>
<%: Html.ValidationMessageFor(Function(m) m.Title)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.BlogEntry)%>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(Function(m) m.BlogEntry, New With {.cols = "85"})%>
<%: Html.ValidationMessageFor(Function(m) m.BlogEntry)%>
</div>
</fieldset>
<input type="submit" value="Submit" />
<% End Using%>
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
</div>
3. Verify that the markup and code in the Create view matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AdventureWorksMvc.Models.Blog>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Create</h2>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Title) %>
<%: Html.ValidationMessageFor(model => model.Title) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.BlogEntry) %>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(model => model.BlogEntry, new { cols = "85" })%>
<%: Html.ValidationMessageFor(model => model.BlogEntry) %>
</div>
Lab Answer Key: Developing MVC Views 11
</fieldset>
<input type="submit" value="Submit" />
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
</div>
</asp:Content>
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of AdventureWorksMvc.Blog)" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Create</h2>
<% Using (Html.BeginForm())%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.Title)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(Function(m) m.Title)%>
<%: Html.ValidationMessageFor(Function(m) m.Title)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.BlogEntry)%>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(Function(m) m.BlogEntry, New With {.cols = "85"})%>
<%: Html.ValidationMessageFor(Function(m) m.BlogEntry)%>
</div>
</fieldset>
<input type="submit" value="Submit" />
<% End Using%>
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
</div>
</asp:Content>
4. Run the application.
a. In Solution Explorer, click AdventureWorksMvc.
b. In the AdventureWorksMvc Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.
5. Navigate directly to the Blogger view by using the following route.
blog/blogger/1
In the Welcome to AdventureWorks Windows Internet Explorer window, in the address bar,
append the following text.
blog/blogger/1
6. Add a blog entry.
12 Lab Answer Key: Developing MVC Views
a. In the Blogger Windows Internet Explorer window, click Create New.
b. In the Create Windows Internet Explorer window, in the Title box, type New Entry, in the
Blog Entry box, type This is a new blog entry, and then click Submit.
7. Close Internet Explorer.
In the Index Windows Internet Explorer window, click the Close button.
Task 4: Use TempData to add a confirmation message to the Index view
1. Open the Index view.
In Solution Explorer, in the Views\Blog folder, double-click Index.aspx.
2. Add the following markup and code to the Index view, right below the h2 element.
[Visual C#]
<% if (TempData["ConfirmationMessage"] != null)
{ %>
<div class="message">
<%: TempData["ConfirmationMessage"]%>
</div>
<% } %>
[Visual Basic]
<% If Not TempData("ConfirmationMessage") Is Nothing Then%>
<div class="message">
<%: TempData("ConfirmationMessage")%>
</div>
<% End If%>
3. Verify that the markup and code in the Index view matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.Blog>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Index</h2>
<% if (TempData["ConfirmationMessage"] != null)
{ %>
<div class="message">
<%: TempData["ConfirmationMessage"]%>
</div>
<% } %>
<% foreach (var item in Model)
{ %>
<div>
<%: Html.ActionLink("Details", "Details", new { id=item.BlogID })%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% } %>
</asp:Content>
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog))" %>
Lab Answer Key: Developing MVC Views 13
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Index</h2>
<% If Not TempData("ConfirmationMessage") Is Nothing Then%>
<div class="message">
<%: TempData("ConfirmationMessage")%>
</div>
<% End If%>
<% For Each item As AdventureWorksMvc.Blog In Model%>
<div>
<%: Html.ActionLink("Details", "Details", New With {.id = item.BlogID})%>
<%: item.DatePosted %>
-
<%: item.Title %>
</div>
<% Next%>
</asp:Content>
4. Run the application.
a. In Solution Explorer, click AdventureWorksMvc.
b. In the AdventureWorksMvc Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.
5. Navigate directly to the Blogger view by using the following route.
blog/blogger/1
In the Welcome to AdventureWorks Windows Internet Explorer window, in the address bar,
append the following text.
blog/blogger/1
6. Add another blog entry.
a. In the Blogger Windows Internet Explorer window, click Create New.
b. In the Create Windows Internet Explorer window, in the Title box, type Another New Entry,
in the Blog Entry box, type This is another new blog entry, and then click Submit.
7. Close Internet Explorer.
In the Index Windows Internet Explorer window, click the Close button.
8. Close Visual Studio 2010.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Exercise 4: Develop an Edit MVC view
Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
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.
2. Open the AdventureWorksMvc solution from the following location.
14 Lab Answer Key: Developing MVC Views
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 05\Starter\Exercise 04
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 04
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:\Lab Files\CS\Lab
05\Starter\Exercise 04\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise
04\AdventureWorksMvc.sln and then click Open.
Task 2: Create a partial view named Blog
1. Build the solution.
In the AdventureWorksMvc Microsoft Visual Studio window, on the Build menu, click Build
Solution, or press CTRL+SHIFT+B.
2. Add an empty, strongly-typed partial view of type Blog, named Blog, to the Blog folder.
a. In Solution Explorer, expand Views, right-click Blog, point to Add, and then click View.
b. [Visual C#] In the Add View dialog box, in the View name box, type Blog, select the Create a
partial view (.ascx) and Create a strongly-typed view check boxes, in the View data class
box, type AdventureWorksMvc.Models.Blog, and then click Add.
-or-
[Visual Basic] In the Add View dialog box, in the View name box, type Blog, select the Create
a partial view (.ascx) and Create a strongly-typed view check boxes, in the View data class
box, type AdventureWorksMvc.Blog, and then click Add.
3. Copy all of the markup and code from the Content2 Content element in the Create view to the
partial Blog view.
a. In Solution Explorer, in the Views\Blog folder, double-click Create.aspx.
b. Select the markup and code from immediately after the h2 element, till the closing the Content
element, and then press CTRL+C.
[Visual C#]
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Title) %>
<%: Html.ValidationMessageFor(model => model.Title) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.BlogEntry) %>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(model => model.BlogEntry, new { cols = "85" })%>
<%: Html.ValidationMessageFor(model => model.BlogEntry) %>
</div>
</fieldset>
<input type="submit" value="Submit" />
Lab Answer Key: Developing MVC Views 15
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
<div>
[Visual Basic]
<% Using (Html.BeginForm())%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.Title)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(Function(m) m.Title)%>
<%: Html.ValidationMessageFor(Function(m) m.Title)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.BlogEntry)%>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(Function(m) m.BlogEntry, New With {.cols = "85"})%>
<%: Html.ValidationMessageFor(Function(m) m.BlogEntry)%>
</div>
</fieldset>
<input type="submit" value="Submit" />
<% End Using%>
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
</div>
a. In the AdventureWorks Microsoft Visual Studio window, click Blog.ascx.
b. In the Blog.ascx window, place the cursor on the line following the Page directive, and press
4. Verify that the markup and code in the partial Blog view matches the following.
CTRL+V.
[Visual C#]
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AdventureWorksMvc.Models.Blog>" %>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Title) %>
<%: Html.ValidationMessageFor(model => model.Title) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.BlogEntry) %>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(model => model.BlogEntry, new { cols = "85" })%>
<%: Html.ValidationMessageFor(model => model.BlogEntry) %>
</div>
</fieldset>
16 Lab Answer Key: Developing MVC Views
<input type="submit" value="Submit" />
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
</div>
[Visual Basic]
<%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(Of
AdventureWorksMvc.Blog)" %>
<% Using (Html.BeginForm())%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.Title)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(Function(m) m.Title)%>
<%: Html.ValidationMessageFor(Function(m) m.Title)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(Function(m) m.BlogEntry)%>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(Function(m) m.BlogEntry, New With {.cols = "85"})%>
<%: Html.ValidationMessageFor(Function(m) m.BlogEntry)%>
</div>
</fieldset>
<input type="submit" value="Submit" />
<% End Using%>
<div>
<%: Html.ActionLink("Back to List", "Blogger") %>
</div>
1. Add an empty, strongly-typed view of type Blog, named Edit, based on the Site.M
Task 3: Create an edit view, named Edit, that uses the Blog partial view
aster master page,
a. In Solution Explorer, expand Views, right-click Blog, point to Add, and then click View.
b. [Visual C#] In the Add View dialog box, in the View name box, type Edit, select the Create a
-or-
al Basic] In the Add View dialog box, in the View name box, type Edit, select the Create a
2. Add the following markup and code to the Edit view in the Content2 Content control, immediately
to the Blog folder.
strongly-typed view check box, in the View data class box, type
AdventureWorksMvc.Models.Blog, and then click Add.
[Visu
strongly-typed view check box, in the View data class box, type AdventureWorksMvc.Blog,
and then click Add.
after the h2 element.
[Visual C#]
<% Html.RenderPartial("Blog"); %>
[Visual Basic]
Lab Answer Key: Developing MVC Views 17
<% Html.RenderPartial("Blog") %>
3. Verify that the markup and code in the Edit view matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AdventureWorksMvc.Models.Blog>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Edit</h2>
<% Html.RenderPartial("Blog"); %>
</asp:Content>
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of AdventureWorksMvc.Blog)" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Edit</h2>
<% Html.RenderPartial("Blog")%>
</asp:Content>
1. Run the application.
Task 4: Edit a blog entry
a. In Solution Explorer, click AdventureWorksMvc.
b. In the AdventureWorksMvc Microsoft Visual Studio window, on the Debug menu, click
2. Navigate directly to the Blogger view by using the following route.
Start Without Debugging, or press CTRL+F5.
blog/blogger/1
In the Welcome to AdventureWorks Windows Internet Explorer window, in the address bar,
append the following text.
blog/blogger/1
3. Edit a blog entry.
a. In the Blogger Windows Internet Explorer window, next to the first blog entry from the top,
b. In the Edit Windows Internet Explorer window, in the Title box, type Modified Entry, in the
c. If the AutoComplete dialog box appears, in the AutoComplete dialog box, click No.
4. Close Internet Explorer.
In the Index Windows Internet Explorer window, click the Close button.
click Edit.
Blog Entry box, type This entry has been modified, and then click Submit.
1. Open Microsoft Visual Studio 2010.
1. In Microsoft Hyper-V Manager, in the Virtual Machines pane, rig
then click Turn Off.
Revert.
Lab Answer Key: Designing for Discoverability 1
Module 6
Lab Answer Key: Designing for Discoverability
Contents:
Exercise 1: Mapping URLs of Web Forms Pages 2
Exercise 2: Creating a Sitemap File 7
Exercise 3: Building the Application Infrastructure 8
2 Lab Answer Key: Designing for Discoverability
Lab 6: Designing for Discoverability
Exercise 1: Mapping URLs of Web Forms Pages
Task 1: Open the AdventureWorks solution in Visual Studio 2010
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. 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.
3. Open the AdventureWorks solution at the following location.
Programming Language Location
Visual C#
.
In the http://localhost:xxxx/products/1 Windows Internet Explorer window, click the Close
button.
Task 5: Add a second route to map a URL to a product ID
1. Open the Global.asax file.
In the AdventureWorks Microsoft Visual Studio window, click Global.asax.cs or
Global.asax.vb.
2. Modify the RegisterRoutes method as shown.
[Visual C#]
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"products-browse", // Route name
"products/{category}", // URL with parameters
"~/Products.aspx" // Web forms page to handle it
);
routes.MapPageRoute(
"product-browse", // Route name
"product/{id}", // URL with parameters
"~/ProductDetail.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("products-browse", "products/{category}", "~/Products.aspx")
' Route name
' URL with parameters
' Web forms page to handle it
routes.MapPageRoute("product-browse", "product/{id}", "~/ProductDetail.aspx")
End Sub
6 Lab Answer Key: Designing for Discoverability
3. Open the ProductDetail.aspx.cs or ProductDetail.aspx.vb code file.
In Solution Explorer, right-click ProductDetail.aspx, and then click View Code.
4. Modify the Page_Load method in the ProductDetail class as shown.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string productId;
// Retrieve id param from /Products/{Id} URL
productId = Page.RouteData.Values["id"].ToString();
var data = DataAccessLayer.Products.GetProduct(int.Parse(productId));
lblName.Text = data.Name;
lblId.Text = data.ProductID.ToString();
lblColor.Text = data.Color;
lblSize.Text = data.Size;
lblWeight.Text = data.Weight.ToString();
lblListPrice.Text = data.ListPrice.ToString();
hdnProductId.Value = data.ProductID.ToString();
hdnProductName.Value = data.Name;
hdnListPrice.Value = data.ListPrice.ToString();
}
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
If Not Page.IsPostBack Then
Dim productID As String = Nothing
' Retrieve id param from /Products/{Id} URL
productID = Page.RouteData.Values("id").ToString()
Dim data =
AdventureWorks.DataAccessLayer.Products.GetProduct(Integer.Parse(productID))
lblName.Text = data.Name
lblId.Text = data.ProductID.ToString()
lblColor.Text = data.Color
lblSize.Text = data.Size
lblWeight.Text = data.Weight.ToString()
lblListPrice.Text = data.ListPrice.ToString()
hdnProductId.Value = data.ProductID.ToString()
hdnProductName.Value = data.Name
hdnListPrice.Value = data.ListPrice.ToString()
End If
End Sub
sk 6: Test the pages Ta
1. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks Microsoft Visual Studio window, on the Debug menu, click Start
Without Debugging, or press CTRL+F5.
Lab Answer Key: Designing for Discoverability 7
2. Navigate directly to the ProductDetail page by using the following route.
product/680
In the Home Page Windows Internet Explorer window, in the address bar, append the
following text.
product/680
Note: A grid should render with a single row containing details of the product with an ID value of
680.
3. Close Internet Explorer.
In the http://localhost:xxxx/products/1 Windows Internet Explorer window, click the Close
button.
4. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Exercise 2: Creating a Sitemap File
Task 1: Create a sitemap file to list products
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.
In the right pane, in the Management Group section, double-click Search Engine
Optimization.
6. 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, in the Change
Frequency list, click Daily, in the Last Modified list, click Do Not Set, in the Priority list, click 1,
and then click OK.
Task 2: Modify the robots.txt file to include the sitemap
1. Select the default website.
In the Connections pane, click Default Web Site.
2. Open the Search Engine Optimization feature.
8 Lab Answer Key: Designing for Discoverability
In the right pane, in the Management Group section, double-click Search Engine
Optimization.
3. Add a new allow rule for the default website and Sitemap.xml file.
a. In the Search Engine Optimization pane, in the Robots Exclusion section, click Add a new
allow rule.
b. In the Add Allow Rules dialog box, in the URL Paths list, select the Default Web Site and
Sitemap.xml check boxes, and then click OK.
4. Close Internet Information Services (IIS) Manager.
In the Internet Information Services (IIS) Manager window, click the Close button.
5. Close Administrative Tools.
In the Control Panel\System and Security\Administrative Tools window, click the Close
button.
6. Close System and Security.
In the Control Panel\System and Security window, click the Close button.
Exercise 3: Building the Application Infrastructure
Task 1: Open the AdventureWorks solution in Visual Studio 2010
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.
2. Open the AdventureWorks solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 06\Starter\Exercise 03
Visual Basic D:\Lab Files\VB\Lab 06\Starter\Exercise 03
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:\Lab Files\CS\Lab
06\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 06\Starter\Exercise
03\AdventureWorks.sln and then click Open.
Task 2: Add Navigation Controls to the web application
1. Create a Web.sitemap file in the root directory of the website.
a. In Solution Explorer, right-click AdventureWorks, point to Add, and then click New Item.
b. In the Add New Item dialog box, in the middle pane, click Site Map, and then click OK.
2. Replace the existing content of the Web.sitemap file with the following markup.
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode roles="*">
<siteMapNode url="~/Default.aspx" title="Home" description="Home"></siteMapNode>
<siteMapNode url="~/ShoppingCart.aspx" title="Shopping"
description="Shopping"></siteMapNode>
Lab Answer Key: Designing for Discoverability 9
<siteMapNode url="~/About.aspx" title="About" description="About"></siteMapNode>
</siteMapNode>
</siteMap>
3. Save and close the Web.sitemap file.
a. In the AdventureWorks Microsoft Visual Studio window, on the File menu, click Save
Web.sitemap, or press CTRL+S.
b. In the Web.sitemap window, click the Close button.
4. Open the Site.Master master page.
In Solution Explorer, double-click Site.Master.
5. Locate the div element with a class attribute value of clear hideSkiplink.
<div class="clear hideSkiplink">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu"
EnableViewState="false"
IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" />
<asp:MenuItem NavigateUrl="~/ShoppingCart.aspx" Text="Cart" />
<asp:MenuItem NavigateUrl="~/About.aspx" Text="About" />
</Items>
</asp:Menu>
</div>
6. Replace the content of the div element with a class attribute value of clear hideSkiplink, with the
following markup.
<div class="clear hideSkiplink">
<asp:SiteMapDataSource runat="server" ID="siteMapDataSource"
ShowStartingNode="false" />
<asp:Menu runat="server" ID="MainMenu" Orientation="Horizontal"
DataSourceID="siteMapDataSource" />
</div>
7. Save and close the Site.Master file.
a. In the AdventureWorks Microsoft Visual Studio window, on the File menu, click Save
Site.Master, or press CTRL+S.
b. In the Site.Master window, click the Close button.
8. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks Microsoft Visual Studio window, on the Debug menu, click Start
Without Debugging, or press CTRL+F5.
9. Close Internet Explorer.
In the http://localhost:xxxx/products/1 Windows Internet Explorer window, click the Close
button.
Task 3: Use the FindControl function to locate a control
1. Open the Site.Master code-behind file.
In Solution Explorer, right-click Site.Master, and then click View Code.
10 Lab Answer Key: Designing for Discoverability
2. In the Page_Load method add the following code.
[Visual C#]
Menu NavigationMenu = (Menu)this.FindControl("NavigationMenu");
[Visual Basic]
Dim NavigationMenu as Menu = Me.FindControl("NavigationMenu")
3. Place Breakpoint on the new line of code.
In the Site.Master.cs or Site.Master.vb window, in the Page_Load method, place the cursor on
the following line of code, and press F9.
[Visual C#]
Menu NavigationMenu = (Menu) this.FindControl("NavigationMenu");
[Visual Basic]
Dim NavigationMenu as Menu = Me.FindControl("NavigationMenu")
4. Debug the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks Microsoft Visual Studio window, on the Debug menu, click Start
Debugging, or press F5.
5. Single-step over the selected line of code.
In the Site.Master.cs or Site.Master.vb window, on the Debug menu, click Step Over, or press
F10.
6. Hover the mouse over the NavigationMenu variable.
Note: IntelliSense
will show you details about the Menu control. You can expand the different levels
by clicking the +-sign.
7. Stop debugging.
In the AdventureWorks Microsoft Visual Studio window, on the Debug menu, click Stop
Debugging, or press SHIFT+F5.
8. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Task 4: Turn off the virtual machine and revert the changes
1. In Microsoft Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and
then click Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Lab Answer Key: Writing Server-Side Code for Web Forms 1
Module 7
Lab Answer Key: Writing Server-Side Code for Web Forms
Contents:
Exercise 1: Modifying a Web Forms Page to Display Localized Content 2
Exercise 2: Persisting Data on Web Forms Pages 7
Exercise 3: Utilizing View State Effectively 13
2 Lab Answer Key: Writing Server-Side Code for Web Forms
Lab 7: Writing Server-Side Code for Web Forms
Exercise 1: Modifying a Web Forms Page to Display Localized Content
Task 1: Open the AdventureWorks solution in Visual Studio 2010
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. 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.
3. Open the AdventureWorks solution from the following location.
Programming Language Location
Visual C#
.
In the Home Page Windows Internet Explorer window, click the Close button.
18. Add an existing German resource file for the Default.aspx Web Form to the App_LocalResources
folder. The file is named Default.aspx.de.resx and it is located in the D:\Lab Files\CS\Lab
07\Starter\Exercise 01 or D:\Lab Files\VB\Lab 07\Starter\Exercise 01 folder.
a. In Solution Explorer, right-click App_LocalResources, point to Add, and then click Existing
Item.
b. In the Add Existing Item dialog box, in the File name box, type D:\Lab Files\CS\Lab
07\Starter\Exercise 01\Default.aspx.de.resx or D:\Lab Files\VB\Lab 07\Starter\Exercise
01\Default.aspx.de.resx, and then click Add.
Task 3: Localize the Site.Master master page
1. Open the Site.Master master page.
In Solution Explorer, double-click Site.Master.
Lab Answer Key: Writing Server-Side Code for Web Forms 5
2. Localize the hard-coded Log In text, by adding a Literal server control within the a element, with the
following attributes.
Attribute Value
ID LoginLiteral
Text Log In
a. Place the cursor between the opening and closing a tags within the AnonymousTemplate
element, just before the text Log In.
b. Open the Toolbox, expand Standard, and then double-click Literal.
c. Modify the Literal server control to appear as follows.
<asp:Literal ID="LoginLiteral" runat="server" Text="Log In">
3. Delete the text Log In from the a element.
Note: Make sure that you do not delete the text Log In from the Literal server control.
4. Localize the hard-coded Welcome text, by adding a Literal server control within the
LoggedInTemplate element, with the following attributes.
Attribute Value
ID WelcomeLiteral
Text Welcome
a. Place the cursor between the opening and closing LoggedInTemplate tags, just before the text
Welcome.
b. Open the Toolbox, expand Standard, and then double-click Literal.
c. Modify the Literal server control to appear as follows.
<asp:Literal ID="WelcomeLiteral" runat="server" Text="Welcome"></asp:Literal>
5. Delete the text Welcome from the LoggedInTemplate element.
Note: Make sure that you do not delete the text Welcome from the Literal server control.
6. Open the Site.Master master page in Design view.
In the Site.Master window, click Design.
7. Generate local resources for Site.Master, by using the Generate Local Resource functionality.
In the AdventureWorks Microsoft Visual Studio window, on the Tools menu, click Generate
Local Resource.
Note: This generates a new file called Site.Master.resx in the App_LocalResources folder.
6 Lab Answer Key: Writing Server-Side Code for Web Forms
8. Add an existing German resource file for the Site.Master master page to the App_LocalResources
folder. The file is named Site.Master.de.resx and it is located in the D:\Lab Files\CS\Lab
07\Starter\Exercise 01 or D:\Lab Files\VB\Lab 07\Starter\Exercise 01 folder.
a. In Solution Explorer, right-click App_LocalResources, point to Add, and then click Existing
Item.
b. In the Add Existing Item dialog box, in the File name box, type D:\Lab Files\CS\Lab
07\Starter\Exercise 01\Site.Master.de.resx or D:\Lab Files\VB\Lab 07\Starter\Exercise
01\Site.Master.de.resx, and then click Add.
Task 4: Test the web application
1. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks Microsoft Visual Studio window, on the Debug menu, click Start
Without Debugging, or press CTRL+F5.
2. Show the AdventureWorks 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) [de-DE], 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.
Lab Answer Key: Writing Server-Side Code for Web Forms 7
f. In the Language Preference dialog box, click OK.
g. In the Internet Options dialog box, click OK.
3. Refresh the page in Internet Explorer.
In the Home Page Windows Internet Explorer window, press F5.
Note: The page should now be shown in German.
4. Close Internet Explorer.
In the Startseite Windows Internet Explorer window, click the Close button.
5. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Exercise 2: Persisting Data on Web Forms Pages
Task 1: Open the AdventureWorks solution in Visual Studio 2010
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.
2. Open the AdventureWorks solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 07\Starter\Exercise 02
Visual Basic D:\Lab Files\VB\Lab 07\Starter\Exercise 02
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:\Lab Files\CS\Lab
07\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 07\Starter\Exercise
02\AdventureWorks.sln and then click Open.
Task 2: Use a cookie collection to persist user information and set scope and lifetime to
save the last chosen category
1. Open the Default.aspx Web Form in Code view.
In Solution Explorer, right-click Default.aspx, and then click View Code.
2. On postback, create a cookie object called Preferences that holds the current product category,
saved as a value named LastCategory. Make sure that the cookie will expire after one minute. The
cookie must be appended to the response.
[Visual C#]
else
{
if (lbCategories.SelectedIndex != -1)
{
string category = lbCategories.SelectedValue;
HttpCookie cookie = new HttpCookie("Preferences");
8 Lab Answer Key: Writing Server-Side Code for Web Forms
cookie["LastCategory"] = category;
cookie.Expires = DateTime.Now.AddMinutes(1);
Response.AppendCookie(cookie);
Response.Redirect("/Products.aspx?id=" + category);
}
}
[Visual Basic]
Else
If lbCategories.SelectedIndex <> -1 Then
Dim category = lbCategories.SelectedValue
Dim cookie As New HttpCookie("Preferences")
cookie("LastCategory") = category
cookie.Expires = DateTime.Now.AddMinutes(1)
Response.AppendCookie(cookie)
Response.Redirect("/Products.aspx?id=" & category, True)
End If
End If
In the Default/_Default class, add the following code to the Page_Load event handler.
[Visual C#]
HttpCookie cookie = new HttpCookie("Preferences");
cookie["LastCategory"] = category;
cookie.Expires = DateTime.Now.AddMinutes(1);
Response.AppendCookie(cookie);
[Visual Basic]
Dim cookie As New HttpCookie("Preferences")
cookie("LastCategory") = category
cookie.Expires = DateTime.Now.AddMinutes(1)
Response.AppendCookie(cookie)
After the following code:
[Visual C#]
else
{
if (lbCategories.SelectedIndex != -1)
{
string category = lbCategories.SelectedValue;
[Visual Basic]
Else
If lbCategories.SelectedIndex <> -1 Then
Dim category = lbCategories.SelectedValue
3. If the page is rendered for the first time, add code to check that a cookie named Preferences exists in
the request cookie collection, and if there is, read the LastCategory value from the cookie, and assign
it to the SelectedValue property of the ListBox control.
[Visual C#]
if (!Page.IsPostBack)
Lab Answer Key: Writing Server-Side Code for Web Forms 9
{
List<ProductCategory> data = DataAccessLayer.Products.GetCategories();
lbCategories.DataSource = data;
lbCategories.DataBind();
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie != null)
{
lbCategories.SelectedValue = cookie["LastCategory"];
}
}
[Visual Basic]
If Not Page.IsPostBack Then
Dim data As List(Of ProductCategory) =
AdventureWorks.DataAccessLayer.Products.GetCategories
lbCategories.DataSource = data
lbCategories.DataBind()
Dim cookie As HttpCookie = Request.Cookies("Preferences")
If Not cookie Is Nothing Then
lbCategories.SelectedValue = cookie("LastCategory")
End If
In the Default/_Default class, add the following code to the Page_Load event handler.
[Visual C#]
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie != null)
{
lbCategories.SelectedValue = cookie["LastCategory"];
}
[Visual Basic]
Dim cookie As HttpCookie = Request.Cookies("Preferences")
If Not cookie Is Nothing Then
lbCategories.SelectedValue = cookie("LastCategory")
End If
After the following code:
[Visual C#]
if (!Page.IsPostBack)
{
List<ProductCategory> data = DataAccessLayer.Products.GetCategories();
lbCategories.DataSource = data;
lbCategories.DataBind();
[Visual Basic]
If Not Page.IsPostBack Then
Dim data As List(Of ProductCategory) =
AdventureWorks.DataAccessLayer.Products.GetCategories
10 Lab Answer Key: Writing Server-Side Code for Web Forms
lbCategories.DataSource = data
lbCategories.DataBind()
4. Build the solution, and fix any errors.
In the AdventureWorks Microsoft Visual Studio window, on the Build menu, click Build
Solution, or press CTRL+SHIFT+B.
Task 3: Store system-wide information in the Application object
1. Open Global.asax in Code view.
In Solution Explorer, right-click Global.asax, and then click View Code.
2. In the Application_Start method, overwrite the existing code, by adding a new application variable
named OnlineVisitors, to the Application object. The variable must have a starting value of 0.
[Visual C#]
void Application_Start(object sender, EventArgs e)
{
Application["OnlineVisitors"] = 0;
}
[Visual Basic]
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application("OnlineVisitors") = 0
End Sub
3. In the Session_Start method increment the value of the OnlineVisitors application variable by 1.
Make sure you prevent multiple threads from writing to the application variable, by locking the
Application object before writing, and unlocking once you have finished writing to it.
[Visual C#]
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
int visitors = (int)Application["OnlineVisitors"];
visitors++;
Application["OnlineVisitors"] = visitors;
Application.UnLock();
}
Lab Answer Key: Writing Server-Side Code for Web Forms 11
[Visual Basic]
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Application.Lock()
Dim visitors As Integer = Integer.Parse(Application("OnlineVisitors"))
visitors += 1
Application("OnlineVisitors") = visitors
Application.UnLock()
End Sub
4. In the Session_End decrement the value of the OnlineVisitors application variable by 1, if the
current value is not 0. Make sure you prevent multiple threads from writing to the application
variable, by locking the Application object before writing, and unlocking once you have finished
writing to it.
[Visual C#]
void Session_End(object sender, EventArgs e)
{
Application.Lock();
int visitors = (int)Application["OnlineVisitors"];
if (visitors > 0)
{
visitors++;
Application["OnlineVisitors"] = visitors;
}
Application.UnLock();
}
[Visual Basic]
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Application.Lock()
Dim visitors As Integer = Integer.Parse(Application("OnlineVisitors"))
If visitors > 0 Then
visitors -= 1
Application("OnlineVisitors") = visitors
End If
Application.UnLock()
End Sub
5. Build the solution, and fix any errors.
In the AdventureWorks Microsoft Visual Studio window, on the Build menu, click Build
Solution, or press CTRL+SHIFT+B.
Task 4: Use the session object to store the shopping cart
1. Open the ProductDetails Web Form in Code view.
In Solution Explorer, right-click ProductDetails.aspx, and then click View Code.
2. Upon postback, the Order button has been pressed, so the information entered in the Web Form is
persisted. In the Page_Load method, notice how the product ID, product name, and list price, which
are not displayed to the user, are saved to hidden fields. In the btnOrder_Click event handler, notice
that a new List object of type clsShoppingCart is created and saved to Session state. Finally, the user
is redirected to the ShoppingCart Web Form.
3. Open the ShoppingCart Web Form in Code view.
12 Lab Answer Key: Writing Server-Side Code for Web Forms
In Solution Explorer, right-click ShoppingCart.aspx, and then click View Code.
4. Analyze the code in the Page_Load method.
In the ShoppingCart.aspx.cs or ShoppingCart.aspx.vb window, check the code in the
Page_Load event handler method. A check to see if a Session object named _cart exists is
performed. If it does exist, the object is retrieved and assigned to the DataSource property of
gvCart GridView server control.
Task 5: Configure session state to run in SQL Server
1. Open the Web.config file.
In Solution Explorer, double-click Web.config.
2. Configure your application to use the local SQL Server
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.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 01 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:\Lab Files\CS\Lab
09\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise
01\AdventureWorks.sln, and then click Open.
Task 2: Create a generic error page for unhandled errors
1. Add a new Web Form named CustomErrorPage.
a. In Solution Explorer, right-click AdventureWorks, point to Add, and then click New Item, or
press CTRL+ SHIFT+ A.
b. In the Add New Item - AdventureWorks dialog box, in the middle pane, click Web Form, in
the Name box, type CustomErrorPage.aspx, and then click Add.
2. Add the text CUSTOM ERROR PAGE to the CustomErrorPage Web Form.
In the CustomErrorPage.aspx window, in the div element, type CUSTOM ERROR PAGE.
3. Save the AdventureWorks project.
In the AdventureWorks Microsoft Visual Studio window, on the File menu, click Save All, or
press CTRL+SHIFT+S.
4. Close the CustomErrorPage Web Form.
In the CustomErrorPage.aspx window, click the Close button.
Task 3: Modify web.config to redirect to the generic error page when an unhandled
error occurs
1. Open the Web.config file.
In Solution Explorer, double-click Web.config.
2. Add the following markup to the system.web element.
<customErrors mode="On" defaultRedirect="~/CustomErrorPage.aspx"/>
In the Web.config window, add the following markup after the closing compilation tag.
</compilation>
<customErrors mode="On" defaultRedirect="~/CustomErrorPage.aspx"/>
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 3
3. Save and close the Web.config file.
a. In the AdventureWorks Microsoft Visual Studio window, on the File menu, click Save
Web.config, or press CTRL+ S.
b. In the Web.config window, click the Close button.
4. Run the application.
In Solution Explorer, click AdventureWorks, and then press CTRL+F5.
5. Click the Submit button.
In the Home Page Windows Internet Explorer window, click Submit.
Note: The custom error page is displayed.
6. Close Windows
Internet Explorer
.
In the http://localhost:xxxx/CustomErrorPage.aspx?aspxerrorpath=/Products.aspx Windows
Internet Explorer window, click the Close button.
7. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Exercise 2: Debugging Code
Task 1: Open an existing ASP.NET web application
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.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 02 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:\Lab Files\CS\Lab
09\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise
02\AdventureWorks.sln, and then click Open.
Task 2: Run the application
1. Set Default.aspx as the project start page.
In Solution Explorer, right-click Default.aspx, and then click Set As Start Page.
2. Run the application in Debug mode.
In Solution Explorer, click AdventureWorks, and then press F5.
Task 3: Debug Default.aspx
1. Click the Submit button.
In the Home Page Windows Internet Explorer window, click Submit.
Note: In Visual Studio, in the FormatException was unhandled by user code pane, the error text
Input string was not in a correct format is displayed.
4 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
2. Press F5 to continue.
Note: The custom error page is displayed. Do not close Internet Explorer.
3. In Visual Studio, place a breakpoint in Default.aspx.cs or Default.aspx.vb on the following line of
code.
[Visual C#]
string category = lbCategories.SelectedValue;
[Visual Basic]
Dim category As String = lbCategories.SelectedValue
a. On the Windows taskbar, click AdventureWorks (Running) Microsoft Visual Studio.
b. In Solution Explorer, right-click Default.aspx, and then click View Code.
c. Place the cursor on the following line of code, and then press F9.
[Visual C#]
string category = lbCategories.SelectedValue;
[Visual Basic]
Dim category As String = lbCategories.SelectedValue
4. Click the Back button on your browser.
a. On the Windows taskbar, click
http://localhost:xxxx/CustomErrorPage.aspx?aspxerrorpath=/Products.aspx Windows
Internet Explorer.
b. In the http://localhost:xxxx/CustomErrorPage.aspx?aspxerrorpath=/Products.aspx
Windows Internet Explorer window, click the Back button.
Note: The Home page is displayed.
5. Click the Submit button.
In the Home Page Windows Internet Explorer window, click Submit.
Note: Visual Studio is now shown, with the breakpoint highlighted.
6. Press F10 to step over the line of code that sets the local variable category to the selected value of
the list.
7. Hover the mouse over category and notice it is an empty string, which cannot be parsed by the code
in the Products page.
8. Press SHIFT+F5 to end debugging.
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 5
9. In Visual Studio, modify the line of code that sets the local variable category to the selected value of
the list, as follows.
[Visual C#]
string category = lbCategories.SelectedValue == string.Empty ? "5" :
lbCategories.SelectedValue;
[Visual Basic]
Dim category As String = IIf(lbCategories.SelectedValue = String.Empty, "5",
lbCategories.SelectedValue)
Note: If the breakpoint disappears after modifying the line of code, place the cursor on the line of
code, and then press F9.
10. Run the application in Debug mode.
In Solution Explorer, click AdventureWorks, and then press F5.
11. Click the Submit button.
In the Home Page Windows Internet Explorer window, click Submit.
Note: Visual Studio is now shown, with the breakpoint highlighted.
12. Press F10 to step over the line of code that sets the local variable category to the selected value of
the list.
13. Hover the mouse over category and notice it is a string with the value of 5.
14. Press F5 to continue.
Note: The Products page is displayed, showing a list of Mountain Bikes.
15. Close Windows Internet Explorer.
In the http://localhost:xxxx/Products.aspx?id=5 Windows Internet Explorer window, click the
Close button.
16. Remove all breakpoints by pressing CTRL+SHIFT+F9.
In the Microsoft Visual Studio dialog box, click Yes.
Task 4: Debug a java script error using breakpoints and single stepping
Run the application in Debug mode.
In Solution Explorer, click AdventureWorks, and then press F5.
Note: The Home page is displayed.
Task 5: Debug Default.aspx.js
1. Click the Select First button.
6 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
In the Home Page Windows Internet Explorer window, click Select First.
Note: A dialog box with an alert message is now shown.
2. In the Message from webpage message box, click OK three times.
3. In Visual Studio, place a breakpoint in Default.aspx.js on the following line of code.
for (i = 0; i < 3; i++) {
a. On the Windows taskbar, click AdventureWorks (Running) Microsoft Visual Studio.
b. In Solution Explorer, double-click Default.aspx.js.
c. Place the cursor on the following line of code, and then press F9.
for (i = 0; i < 3; i++) {
4. Click the Back button in your browser.
a. On the Windows taskbar, click http://localhost:xxxx/Products.aspx?id=5 Windows Internet
Explorer.
b. In the http://localhost:xxxx/Products.aspx?id=5 Windows Internet Explorer window, click the
Back button.
Note: The Home page is displayed.
5. Click the Select First button.
In the Home Page Windows Internet Explorer window, click Select First.
Note: Visual Studio is now shown, with the breakpoint highlighted.
6. Press F10 to step over the statements of code, until a message box is displayed.
7. In the Message from webpage message box, click OK.
8. Repeat steps 6 and 7 twice.
9. Press F5.
Note: The Products page is displayed.
10. Close Windows Internet Explorer.
In the http://localhost:xxxx/Products.aspx?id=5 Windows Internet Explorer window, click the
Close button.
11. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 7
Exercise 3: Logging
Task 1: Open an existing ASP.NET web application
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.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 03 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 03 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:\Lab Files\CS\Lab
09\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise
03\AdventureWorks.sln, and then click Open.
Task 2: Configure logging to an Error Log
1. Open Products.aspx in Code view.
In Solution Explorer, right-click Products.aspx, and then click View Code.
2. Import the System.Diagnostics namespace.
[Visual C#]
using System.Diagnostics;
[Visual Basic]
Imports System.Diagnostics
3. Modify the Page_Load method with the following code.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string categoryName = string.Empty;
string categoryId = string.Empty;
if (Request["id"] != null)
{
categoryId = Request["id"];
}
try
{
categoryName =
DataAccessLayer.Products.GetCategoryName(int.Parse(categoryId));
}
catch (Exception ex)
{
EventLog Log = new EventLog();
Log.Source = "Application";
Log.WriteEntry(ex.Message, EventLogEntryType.Error);
}
lblCategory.Text = categoryName;
var data =
DataAccessLayer.Products.GetProductsByCategory(int.Parse(categoryId));
8 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
gvProducts.DataSource = data;
gvProducts.DataBind();
}
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
If Not Page.IsPostBack Then
Dim categoryName As String = String.Empty
Dim categoryID As String = String.Empty
If Not Request("id") Is Nothing Then
categoryID = Request("id")
End If
Try
categoryName =
AdventureWorks.DataAccessLayer.Products.GetCategoryName(Integer.Parse(categoryID))
Catch ex As Exception
Dim Log As New EventLog()
Log.Source = "Application"
Log.WriteEntry(ex.Message, EventLogEntryType.[Error])
End Try
lblCategory.Text = categoryName
Dim data =
AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(Integer.Parse(categoryI
D))
gvProducts.DataSource = data
gvProducts.DataBind()
End If
End Sub
4. Run the application.
Press CTRL+F5.
Note: The custom error page is displayed.
5. Open the Event Viewer and show the Application log entry. If necessary, sort the Application log
entries by date and time.
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 9
a. On the Start menu, point to Administrative Tools, and then click Event Viewer.
b. In the Event Viewer, in the left pane, expand Windows Logs, and then click Application.
c. If needed, click Date and Time to sort by date and time.
d. View the logged Application error, by double-clicking it in the middle pane.
6. Close the Event Viewer.
In the Event Viewer window, click Close button.
7. Close Windows Internet Explorer.
In the http://localhost:xxxx/CustomErrorPage.aspx?aspxerrorpath=/Products.aspx Windows
Internet Explorer window, click the Close button.
Task 3: Set the logging level in the Web.config file to allow for future debugging
1. Open the Web.config file.
In Solution Explorer, double-click Web.config.
2. In the opening compilation tag, ensure that the value of the debug attribute is set to true.
<compilation debug="true" ...>
3. Close the Web.config file.
In the Web.config window, click the Close button.
Task 4: Create a generic error handler
1. Open the Global.asax file.
In Solution Explorer, double-click Global.asax.
2. Import the System.Diagnostics namespace.
[Visual C#]
10 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
using System.Diagnostics;
[Visual Basic]
Imports System.Diagnostics
3. Modify the Application_Error method with the following code.
[Visual C#]
void Application_Error(object sender, EventArgs e)
{
string message =
"Url: " + Request.Path + " Error: " +
Server.GetLastError().ToString();
EventLog log = new EventLog();
log.Source = "Application";
log.WriteEntry(message, EventLogEntryType.Error);
}
[Visual Basic]
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim message As String =
"Url: " & Request.Path & " Error: " &
Server.GetLastError().ToString()
Dim log As New EventLog()
log.Source = "Application"
log.WriteEntry(message, EventLogEntryType.Error)
End Sub
4. Build the project and fix any errors.
In the AdventureWorks Microsoft Visual Studio window, on the Build menu, click Build
AdventureWorks.
5. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Exercise 4: Creating Unit Tests
Task 1: Open an existing ASP.NET web application
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.
2. Open the MyClassLibrary solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 04 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 04 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:\Lab Files\CS\Lab
09\Starter\Exercise 04\MyClassLibrary.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise
04\MyClassLibrary.sln, and then click Open.
Task 2: Create a method to add two numbers
1. Open the Calculator.cs or Calculator.vb file.
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 11
a. In Solution Explorer, double-click Calculator.cs or Calculator.vb.
b. Add the following code to Calculator class.
[Visual C#]
public int Add(int p1, int p2)
{
return p1 + p2;
}
[Visual Basic]
Public Function Add(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Return p1 + p2
End Function
2. Save Calculator.cs or Calculator.vb.
In the MyClassLibrary Microsoft Visual Studio window, on the File menu, click Save
Calculator.cs, or Save Calculator.vb.
3. Build the project and fix any errors.
In the MyClassLibrary Microsoft Visual Studio window, on the Build menu, click Build
ClassLibrary.
Task 3: Add a test project
Add a test project named CalculatorTestProject for the Add method.
a. In the Calculator.cs, or Calculator.vb window, right-click to the Add method declaration, and
then click Create Unit Tests.
b. In the Create Unit Tests dialog box, ensure the Add(System.Int32, System.Int32) check box is
selected, and then click OK.
c. In the New Test Project dialog box, in the Enter a name for your new project box, type
CalculatorTestProject, and then click Create.
Task 4: Edit the test method to pass
1. In the AddTest method, modify the value assigned to local variable p1 to 2.
[Visual C#]
int p1 = 2;
[Visual Basic]
Dim p1 As Integer = 2
2. In the AddTest method, modify the value assigned to local variable p2 to 3.
[Visual C#]
int p2 = 3;
[Visual Basic]
Dim p2 As Integer = 3
12 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
3. In the AddTest method, modify the value assigned to local variable expected to 5.
[Visual C#]
int expected = 5;
[Visual Basic]
Dim expected As Integer = 5
4. Remove 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.")
5. Ensure the AddTest method appears as follows.
[Visual C#]
[TestMethod()]
public void AddTest()
{
Calculator target = new Calculator(); // TODO: Initialize to an appropriate value
int p1 = 2; // TODO: Initialize to an appropriate value
int p2 = 3; // TODO: Initialize to an appropriate value
int expected = 5; // TODO: Initialize to an appropriate value
int actual;
actual = target.Add(p1, p2);
Assert.AreEqual(expected, actual);
}
[Visual Basic]
<TestMethod()> _
Public Sub AddTest()
Dim target As Calculator = New Calculator() ' TODO: Initialize to an appropriate
value
Dim p1 As Integer = 2 ' TODO: Initialize to an appropriate value
Dim p2 As Integer = 3 ' TODO: Initialize to an appropriate value
Dim expected As Integer = 5 ' TODO: Initialize to an appropriate value
Dim actual As Integer
actual = target.Add(p1, p2)
Assert.AreEqual(expected, actual)
End Sub
Task 5: Run the test
Start the test.
In the CalculatorTest.cs, or CalculatorTest.vb window, right-click the AddTest method
declaration, and then click Run Tests.
Note: In the Test Result window, you can see that the AddTest test passed.
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 13
Task 6: Edit the test method to fail
1. In the AddTest method, modify the value assigned to local variable expected to 6.
[Visual C#]
int expected = 6;
[Visual Basic]
Dim expected As Integer = 6
2. Ensure the AddTest method appears as follows.
[Visual C#]
[TestMethod()]
public void AddTest()
{
Calculator target = new Calculator(); // TODO: Initialize to an appropriate value
int p1 = 2; // TODO: Initialize to an appropriate value
int p2 = 3; // TODO: Initialize to an appropriate value
int expected = 6; // TODO: Initialize to an appropriate value
int actual;
actual = target.Add(p1, p2);
Assert.AreEqual(expected, actual);
}
[Visual Basic]
<TestMethod()> _
Public Sub AddTest()
Dim target As Calculator = New Calculator() ' TODO: Initialize to an appropriate
value
Dim p1 As Integer = 2 ' TODO: Initialize to an appropriate value
Dim p2 As Integer = 3 ' TODO: Initialize to an appropriate value
Dim expected As Integer = 6 ' TODO: Initialize to an appropriate value
Dim actual As Integer
actual = target.Add(p1, p2)
Assert.AreEqual(expected, actual)
End Sub
Task 7: Run the tests
1. Start the test.
In the CalculatorTest.cs, or CalculatorTest.vb window, right-click the AddTest method
declaration, and then click Run Tests.
Note: In the Test Result window, you can see that the AddTest test failed.
2. Close Visual Studio 2010.
In the MyClassLibrary Microsoft Visual Studio window, click the Close button.
14 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Exercise 5: Implementing the Test-First/Test-Driven Development Methodology
Task 1: Open an existing ASP.NET web application
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.
2. Open the MyClassLibrary solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 05 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 05 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:\Lab Files\CS\Lab
09\Starter\Exercise 05\MyClassLibrary.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise
05\MyClassLibrary.sln, and then click Open.
Task 2: Create tests
1. Open CalculatorTest.cs or CalculatorTest.vb file in the CalculatorTestProject project.
In Solution Explorer, under CalculatorTestProject, double-click CalculatorTest.cs or
CalculatorTest.vb.
2. Add the following code to CalculatorTest class.
[Visual C#]
[TestMethod()]
public void ClassMultiplyMethodTest()
{
Calculator target = new Calculator();
Assert.IsNotNull(target);
int expected = 6;
int unexpected = 5;
int actual = target.Multiply(3, 2);
Assert.AreEqual(expected, actual);
Assert.AreNotEqual(unexpected, actual);
}
[TestMethod()]
public void ClassSubtractMethodTest()
{
Calculator target = new Calculator();
Assert.IsNotNull(target);
int expected = 1;
int unexpected = 6;
int actual = target.Subtract(3, 2);
Assert.AreEqual(expected, actual);
Assert.AreNotEqual(unexpected, actual);
}
[Visual Basic]
<TestMethod()>
Public Sub ClassMultiplyMethodTest()
Dim target As New Calculator()
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 15
Assert.IsNotNull(target)
Dim expected As Integer = 6
Dim unexpected As Integer = 5
Dim actual As Integer = target.Multiply(3, 2)
Assert.AreEqual(expected, actual)
Assert.AreNotEqual(unexpected, actual)
End Sub
<TestMethod()>
Public Sub ClassSubtractMethodTest()
Dim target As New Calculator()
Assert.IsNotNull(target)
Dim expected As Integer = 1
Dim unexpected As Integer = 6
Dim actual As Integer = target.Subtract(3, 2)
Assert.AreEqual(expected, actual)
Assert.AreNotEqual(unexpected, actual)
End Sub
3. Save the CalculatorTest.cs or CalculatorTest.vb file.
In the MyClassLibrary Microsoft Visual Studio window, on the File menu, click Save
CalculatorTest.cs or Save CalculatorTest.vb.
Task 3: Create method stub
1. Open the Calculator.cs or Calculator.vb file in the ClassLibrary project.
In Solution Explorer, under ClassLibrary, double-click Calculator.cs or Calculator.vb.
2. Add the following code to the Calculator class.
[Visual C#]
public int Multiply(int p1, int p2)
{
throw new NotImplementedException();
}
public int Subtract(int p1, int p2)
{
throw new NotImplementedException();
}
[Visual Basic]
Public Function Multiply(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Throw New NotImplementedException()
End Function
Public Function Subtract(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Throw New NotImplementedException()
End Function
3. Build the solution and fix any errors.
16 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
In the MyClassLibrary Microsoft Visual Studio window, on the Build menu, click Build
Solution or press CTRL+SHIFT+B.
Task 4: Run the tests
1. Open the CalculatorTest.cs or CalculatorTest.vb file.
In the MyClassLibrary Microsoft Visual Studio window, click CalculatorTest.cs or
CalculatorTest.vb.
2. Start the ClassMultiplyMethodTest test.
In the CalculatorTest.cs, or CalculatorTest.vb window, right-click the
ClassMultiplyMethodTest method declaration, and then click Run Tests.
Note: In the Test Result window, you can see that the ClassMultiplyMethodTest test failed.
3. Start the ClassSubtractMethodTest test.
In the CalculatorTest.cs, or CalculatorTest.vb window, right-click the
ClassSubtractMethodTest method declaration, and then click Run Tests.
Note: In the Test Result window, you can see that the ClassSubtractMethodTest test failed.
4. Close the CalculatorTest.cs or CalculatorTest.vb file.
In the CalculatorTest.cs, or CalculatorTest.vb window, click the Close button.
Task 5: Add logic to stub methods
1. Replace the Multiply method in the Calculator class with following code.
[Visual C#]
public int Multiply(int p1, int p2)
{
return p1 * p2;
}
[Visual Basic]
Public Function Multiply (ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Return p1 * p2
End Function
2. Replace the Subtract method in the Calculator class with following code.
[Visual C#]
public int Subtract(int p1, int p2)
{
return p1 - p2;
}
[Visual Basic]
Public Function Subtract(ByVal p1 As Integer, ByVal p2 As Integer) As Integer
Return p1 - p2
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 17
End Function
3. Build the solution and fix any errors.
In the MyClassLibrary Microsoft Visual Studio window, on the Build menu, click Build
Solution or press CTRL+SHIFT+B.
Task 6: Run the tests
1. Open CalculatorTest.cs or CalculatorTest.vb file in the CalculatorTestProject project.
In Solution Explorer, under CalculatorTestProject, double-click CalculatorTest.cs or
CalculatorTest.vb.
2. Start the ClassMultiplyMethodTest test.
In the CalculatorTest.cs, or CalculatorTest.vb window, right-click the
ClassMultiplyMethodTest method declaration, and then click Run Tests.
Note: In the Test Result window, you can see that the ClassMultiplyMethodTest test passed.
3. Start the ClassSubtractMethodTest test.
In the CalculatorTest.cs, or CalculatorTest.vb window, right-click the
ClassSubtractMethodTest method declaration, and then click Run Tests.
Note: In the Test Result window, you can see that the ClassSubtractMethodTest test passed.
4. Close the CalculatorTest.cs or CalculatorTest.vb file.
In the CalculatorTest.cs, or CalculatorTest.vb window, click the Close button.
5. Close Visual Studio 2010.
In the MyClassLibrary Microsoft Visual Studio window, click the Close button.
Task 7: Turn off the virtual machine and revert the changes
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Lab Answer Key: Securing a Web Application 1
Module 10
Lab Answer Key: Securing a Web Application
Contents:
Exercise 1: Configuring ASP.NET Membership and Roles 2
Exercise 2: Authentication 3
Exercise 3: Authorization 8
2 Lab Answer Key: Securing a Web Application
Lab 10: Securing a Web Application
Exercise 1: Configuring ASP.NET Membership and Roles
Task 1: Open an existing ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. 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.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 10\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 10\Starter\Exercise 01 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:\Lab Files\CS\Lab
10\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 10\Starter\Exercise
01\AdventureWorks.sln, and then click Open.
Task 2: Open the ASP.NET Web Site Administration Tool
1. In Solution Explorer, click AdventureWorks.
2. Build the solution.
On the Build menu, click Build Solution, or press CTRL+SHIFT+B.
3. In Solution Explorer, click the ASP.NET Configuration button.
4. Change the authentication type from local to Internet (Windows to Forms), by using the Security
page.
In the ASP.Net Web Application Administration Windows Internet Explorer window, click
Security.
5. Click Select authentication type.
6. Click From the internet, and then click Done.
Task 3: Add users
1. Click Create user.
2. Fill out the information to create a new user, using the following information.
User Name Password E-mail
Security
Question Security Answer
Mary Pa$$w0rd mary@adventureworks.com Favorite pet Cat
In the User Name box, type Mary, in the Password box, type Pa$$w0rd, in the Confirm
Password box, type Pa$$w0rd, in the E-mail box, type mary@adventureworks.com, in the
Security Question box, type Favorite pet, in the Security Answer box, type Cat.
3. Click Create User.
4. Click Continue.
5. Fill out the information to create a new user, using the following information.
Lab Answer Key: Securing a Web Application 3
User
Name Password E-mail
Security
Question Security Answer
John Pa$$w0rd john@adventureworks.com High School Central
In the User Name box, type John, in the Password box, type Pa$$w0rd, in the Confirm
Password box, type Pa$$w0rd, in the E-mail box, type john@adventureworks.com, in the
Security Question box, type High School, in the Security Answer box, type Central.
6. Click Create User.
7. Click Continue.
Task 4: Add roles
1. In the ASP.NET Web Site Administration Tool, click Security.
In the ASP.Net Web Application Administration Windows Internet Explorer window, click
Security.
2. Click Enable roles.
3. Click Create or Manage roles.
4. In the New role name box, type Administration, and then click Add Role.
If the AutoComplete dialog box appears, in the AutoComplete dialog box, click No.
5. In the New role name box, type Contributor, and then click Add Role.
Task 5: Assign roles to users
1. Click Manage for the Contributor role.
Next to the Contributor role, click Manage.
2. Type * in the for box, and then click Find User.
3. Select the User Is In Role check box next to user Mary.
4. Click Back.
5. Click Manage for the Administration role.
Next to the Administration role, click Manage.
6. Type * in the for box, and then click Find User.
7. Select the User Is In Role check boxes next to users John and Mary.
8. Close the ASP.NET Web Site Administration Tool.
In the ASP.Net Web Application Administration Windows Internet Explorer window, click the
Close button.
9. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Exercise 2: Authentication
Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
4 Lab Answer Key: Securing a Web Application
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 10\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 10\Starter\Exercise 02 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:\Lab Files\CS\Lab
10\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 10\Starter\Exercise
02\AdventureWorks.sln, and then click Open.
Task 2: Configure an application to use Forms authentication
1. Open the Web.config file.
In Solution Explorer, double-click Web.config.
2. Ensure that the value of the mode attribute it set to Forms, in the self-closing authentication
element.
<authentication mode="Forms" />
Note: When changing the authentication type in the ASP.NET Web Site Administration Tool to From
the internet, the Web.config file is updated automatically.
3. Add a redirect to the existing Login.aspx Web Form in the Account folder, by modifying the self-
closing authentication tag.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
Task 3: Use the Login control
1. In Solution Explorer, expand the Account folder.
2. Open the Login.aspx Web Form.
In Solution Explorer, under Account, double-click Login.aspx.
3. Examine the markup for the Login control, including the UserName and Password TextBox
controls, as well as the RememberMe CheckBox control.
<asp:Login ID="LoginUser" runat="server" EnableViewState="false"
RenderOuterTable="false">
<LayoutTemplate>
<span class="failureNotification">
<asp:Literal ID="FailureText" runat="server"></asp:Literal>
</span>
<asp:ValidationSummary ID="LoginUserValidationSummary" runat="server"
CssClass="failureNotification"
ValidationGroup="LoginUserValidationGroup"/>
<div class="accountInfo">
<fieldset class="login">
<legend>Account Information</legend>
<p>
<asp:Label ID="UserNameLabel" runat="server"
AssociatedControlID="UserName">Username:</asp:Label>
Lab Answer Key: Securing a Web Application 5
<asp:TextBox ID="UserName" runat="server"
CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName"
CssClass="failureNotification" ErrorMessage="User Name is
required." ToolTip="User Name is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p>
<asp:Label ID="PasswordLabel" runat="server"
AssociatedControlID="Password">Password:</asp:Label>
<asp:TextBox ID="Password" runat="server"
CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
ControlToValidate="Password"
CssClass="failureNotification" ErrorMessage="Password is
required." ToolTip="Password is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p>
<asp:CheckBox ID="RememberMe" runat="server"/>
<asp:Label ID="RememberMeLabel" runat="server"
AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
</p>
</fieldset>
<p class="submitButton">
<asp:Button ID="LoginButton" runat="server" CommandName="Login"
Text="Log In" ValidationGroup="LoginUserValidationGroup"/>
</p>
</div>
</LayoutTemplate>
</asp:Login>
4. Add a redirect to the EmailPassword.aspx Web Form in the Account folder, by adding the following
markup above the PasswordLabel control.
<asp:HyperLink ID="EmailPasswordHyperLink" runat="server"
NavigateUrl="~/Account/EmailPassword.aspx">Forgot Password?</asp:HyperLink>
In the Login.aspx window, type the following markup.
<p>
<asp:HyperLink ID="EmailPasswordHyperLink" runat="server"
NavigateUrl="~/Account/EmailPassword.aspx">Forgot Password?</asp:HyperLink>
<asp:Label ID="PasswordLabel" runat="server"
AssociatedControlID="Password">Password:</asp:Label>
Note: The EmailPassword.aspx Web Form has not yet been created.
Task 4: Set the password options
1. Open Login.aspx in Code view.
In the Login.aspx window, right-click anywhere, and then click View Code.
2. Import the System.Web.Security namespace.
[Visual C#]
6 Lab Answer Key: Securing a Web Application
using System.Web.Security;
[Visual Basic]
Imports System.Web.Security
At the top of the Login.aspx code-behind file, type the following code.
[Visual C#]
using System.Web.Security;
[Visual Basic]
Imports System.Web.Security
3. Add the following code to the Login class to handle the Authenticate event for the LoginUser
server control.
[Visual C#]
protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
{
// Get the membership details for the user
MembershipUser user = Membership.GetUser(LoginUser.UserName.Trim());
// Did we find the user?
if (user != null)
{
// Check if the user password has expired after 90 days
if (DateTime.Now.Subtract(user.LastPasswordChangedDate).TotalDays >= 90)
{
Response.Redirect("PasswordExpired.aspx");
}
else
{
// Authenticate user
if (Membership.ValidateUser(LoginUser.UserName.Trim(),
LoginUser.Password.Trim()))
e.Authenticated = true;
}
}
[Visual Basic]
Protected Sub LoginUser_Authenticate(ByVal sender As Object, ByVal e As
AuthenticateEventArgs) Handles LoginUser.Authenticate
' Get the membership details for the user
Dim user As MembershipUser = Membership.GetUser(LoginUser.UserName.Trim())
' Did we find the user?
If Not user Is Nothing Then
' Check if the user password has expired after 90 days
If DateTime.Now.Subtract(user.LastPasswordChangedDate).TotalDays >= 90 Then
Response.Redirect("PasswordExpired.aspx")
Else
' Authenticate user
If Membership.ValidateUser(LoginUser.UserName.Trim(),
LoginUser.Password.Trim()) Then
e.Authenticated = True
End If
Lab Answer Key: Securing a Web Application 7
End If
End If
End Sub
4. Build the solution.
On the Build menu, click Build Solution, or press CTRL+SHIFT+B.
5. Close the Login.aspx code-behind file.
In the Login.aspx.cs or Login.aspx.vb window, click the Close button.
6. Close the Login.aspx Web Form.
In the Login.aspx window, click the Close button.
Task 5: Configure password recovery
1. Add a new Web Form named EmailPassword to the Account folder. The Web Form must be based
on the Site.Master master page.
a. In Solution Explorer, right-click Account, 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 EmailPassword.aspx, 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.
2. Drag a PasswordRecovery server control from the Login section of the Toolbox to the
EmailPassword.aspx Web Form, in the Content2 Content control. Keep the default settings.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:PasswordRecovery ID="PasswordRecovery1" runat="server">
</asp:PasswordRecovery>
</asp:Content>
3. Configure the Web.config file to use the mail settings as shown.
<system.net>
<mailSettings>
<smtp from="someone@adventureworks.com">
<network host="yourhost" userName="hostusername" password="hostpassword" />
</smtp>
</mailSettings>
</system.net>
a. In the AdventureWorks Microsoft Visual Studio window, click Web.config.
b. In the configuration element, add the following markup before the closing configuration tag.
<system.net>
<mailSettings>
<smtp from="someone@adventureworks.com">
<network host="yourhost" userName="hostusername"
password="hostpassword" />
</smtp>
</mailSettings>
</system.net>
4. Build the solution and fix any errors.
On the Build menu, click Build Solution, or press CTRL+SHIFT+B.
8 Lab Answer Key: Securing a Web Application
5. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Exercise 3: Authorization
Task 1: Open an existing ASP.NET web application
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.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 10\Starter\Exercise 03 or D:\Lab
Files\VB\Lab 10\Starter\Exercise 03 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:\Lab Files\CS\Lab
10\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 10\Starter\Exercise
03\AdventureWorks.sln, and then click Open.
Task 2: Allow anonymous access to the EmailPassword Web Form
1. Open the Web.config file in the Account folder.
In Solution Explorer, expand Account, and then double-click Web.config.
2. Add the following markup to the Web.config file, above the existing location element.
<location path="EmailPassword.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
3. Save and close the Web.config file.
a. Press CTRL+S.
b. In the Web.config window, click the Close button.
Task 3: Create the secured portion of the site
1. Create a new folder named Contributors.
a. In Solution Explorer, right-click AdventureWorks, point to Add, and then click New Folder.
b. In the box, type Contributors, and then press ENTER.
2. Add a new Web Form named Home.aspx in the Contributors folder. The Web Form should be
based on the Site.Master master page.
a. Right-click Contributors, 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 Home.aspx, 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.
3. Add the following header to the Home.aspx Web Form.
Lab Answer Key: Securing a Web Application 9
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Contributors Home section</h2>
</asp:Content>
In the Home.aspx window, in the Content2 Content control, type the following markup.
<h2>Contributors Home section</h2>
4. Save and close the Home.aspx file.
a. Press CTRL+S.
b. In the Home.aspx window, click the Close button.
5. Open the Web.config file.
In Solution Explorer, double-click Web.config.
6. Add the following markup to the Web.config file, above the opening connectionStrings tag.
<location path="Contributors">
<system.web>
<authorization>
<allow roles="Contributor"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
7. Save and close the Web.config file.
a. Press CTRL+S.
b. In the Web.config window, click the Close button.
Task 4: Test the web application
1. Build the solution and fix any errors.
On the Build menu, click Build Solution, or press CTRL+SHIFT+B.
2. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. Press CTRL+F5.
3. On the Home page, click Log In.
4. On the Login page, click Forgot Password?.
Note: You have access to the EmailPassword Web Form as an anonymous user.
5. Click the Back button in your browser.
In the http://localhost:xxxx/Account/EmailPassword.aspx Windows Internet Explorer window,
click the Back button.
Note: The Login is displayed.
10 Lab Answer Key: Securing a Web Application
6. Log on using John as the username and Pa$$w0rd as the password.
In the Username box, type John, in the Password box, type Pa$$w0rd, and then click Log In.
7. Access the Contributors/Home.aspx Web Form.
Type the following URL in the Windows
Internet Explorer
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.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 01 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:\Lab Files\CS\Lab
11\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starter\Exercise
01\AdventureWorks.sln, and then click Open.
Task 2: Open the Site.Master master page
Open the Site.Master file in the root of the AdventureWorks project.
In Solution Explorer, double-click Site.Master.
Task 3: Add a third ContentPlaceHolder control
Add the following markup to the Site.Master file to add the new ContentPlaceHolder with an ID
attribute value of FooterContent.
<div class="footer">
<asp:ContentPlaceHolder ID="FooterContent" runat="server" />
</div>
In the Site.Master window, add the following markup to the div element with an ID attribute
value of FooterContent.
<asp:ContentPlaceHolder ID="FooterContent" runat="server" />
Task 4: Open the About.aspx page
Open the About.aspx file in the root of the AdventureWorks project.
In Solution Explorer, double-click About.aspx.
Task 5: Add a new Content control to About.aspx
Add the following markup to the About.aspx file to add the Content control in the bottom of the
page.
<asp:Content ID="PageFooterContent" runat="server"
ContentPlaceHolderID="FooterContent">
</asp:Content>
In the About.aspx window, append the following markup to the existing markup.
Lab Answer Key: Applying Master Pages and CSS 3
<asp:Content ID="PageFooterContent" runat=="server"
ContentPlaceHolderID="FooterContent">
</asp:Content>
Task 6: Add the string Copyright notice to the control
Add the following text to the Content control.
<asp:Content ID="PageFooterContent" runat=server
ContentPlaceHolderID="FooterContent">
Copyright AdventureWorks
</asp:Content>
In the About.aspx window, add the following markup to the Content control with an ID
attribute value of PageFooterContent.
Copyright AdventureWorks
Task 7: Test the About.aspx page
1. Run the application to test the page by pressing CTRL+F5.
Note: The rendered page should appear as follows. Notice the text you added at the bottom of the
image.
2. Close Windows
Internet Explorer
.
In the About Us Windows Internet Explorer window, click the Close button.
3. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
4 Lab Answer Key: Applying Master Pages and CSS
Exercise 2: Create a Nested Master Page
Task 1: Open an existing ASP.NET web application
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.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 02 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 02 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:\Lab Files\CS\Lab
11\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starter\Exercise
02\AdventureWorks.sln, and then click Open.
Task 2: Create a Nested Master page
1. Add a nested master page named Nested.master to the project. It should be based on the
Site.Master master page.
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 Nested Master
Page, in the Name box, type Nested.master, 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.
2. Rename each of the three Content controls to Header, Main, and Footer.
[Visual C#]
<%@ Master Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Nested.master.cs" Inherits="AdventureWorks.Nested" %>
<asp:Content ID="Header" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
<asp:Content ID="Footer" ContentPlaceHolderID="FooterContent" runat="server">
</asp:Content>
[Visual Basic]
<%@ Master Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Nested.master.vb" Inherits="AdventureWorks.Nested" %>
<asp:Content ID="Header" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
<asp:Content ID="Footer" ContentPlaceHolderID="FooterContent" runat="server">
</asp:Content>
a. In the Nested.master window, locate the Content control with an ID attribute value of
Content1, and change it to Header.
b. Locate the Content control with an ID attribute value of Content2, and change it to Main.
c. Locate the Content control with an ID attribute value of Content3, and change it to Footer.
Lab Answer Key: Applying Master Pages and CSS 5
Task 3: Add two ContentPlaceHolder controls
To add two ContentPlaceHolder controls to the Nested.master file, add the following markup, in
the Main Content control.
<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">
<div class="left">
<asp:ContentPlaceHolder ID="LeftContent" runat="server" />
</div>
<div class="right">
<asp:ContentPlaceHolder ID="RightContent" runat="server" />
</div>
</asp:Content>
In the Nested.master window, in the Content control with an ID attribute value of Main, type
the following markup.
<div class="left">
<asp:ContentPlaceHolder ID="LeftContent" runat="server" />
</div>
<div class="right">
<asp:ContentPlaceHolder ID="RightContent" runat="server" />
</div>
Task 4: Add footer content
To add the footer content to the Nested.master file, add the following markup in the Footer
Content control.
<asp:Content ID="Footer" ContentPlaceHolderID="FooterContent" runat="server">
Copyright AdventureWorks
</asp:Content>
In the Nested.master window, in the Content control with an ID attribute value of Footer, type
the following markup.
Copyright AdventureWorks
Task 5: Change the Default.aspx page Web Form to use the Nested.master page
1. Modify the Page directive in the Default.aspx file, by adding following markup to change the master
page.
[Visual C#]
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Nested.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AdventureWorks._Default" %>
[Visual Basic]
<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Nested.master"
AutoEventWireup="false"
CodeBehind="Default.aspx.vb" Inherits="AdventureWorks._Default" %>
a. In Solution Explorer, double-click Default.aspx.
b. In the Default.aspx window, in the Page directive, change the value of the MasterPageFile
attribute from ~/Site.Master to ~/Nested.master.
6 Lab Answer Key: Applying Master Pages and CSS
2. Change the ContentPlaceHolder controls to which the Content controls refer to RightContent and
LeftContent. Rename the Content controls to RightBodyContent and LeftBodyContent.
<asp:Content ID="RightBodyContent" runat="server"
ContentPlaceHolderID="RightContent">
...
<asp:Content ID="LeftBodyContent" runat="server" ContentPlaceHolderID="LeftContent">
a. In the Default.aspx window, locate the Content control with an ID attribute value of
HeaderContent, and change it to RightBodyContent. Change the ContentPlaceHolderID
attribute value from HeadContent to RightContent.
b. Locate the Content control with an ID attribute value of BodyContent, and change it to
LeftBodyContent. Change the ContentPlaceHolderID attribute value from MainContent to
LeftContent.
3. Add the following markup to the Content control with an ID attribute value of RightBodyContent.
<asp:Content ID="RightBodyContent" runat="server"
ContentPlaceHolderID="RightContent">
<p>
Right Content
</p>
</asp:Content>
In the Default.aspx window, in the Content control with an ID attribute value of
RightBodyContent, type the following markup.
<p>
Right Content
</p>
4. Move the Content control with an ID attribute value of RightBodyContent to after the Content
control with an ID attribute value of LeftBodyContent.
<asp:Content ID="LeftBodyContent" runat="server" ContentPlaceHolderID="LeftContent">
<h2>
Welcome to AdventureWorks!
</h2>
<p>
Product Categories
<br />
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"
DataValueField="ProductCategoryID"
Height="270px" Width="186px"></asp:ListBox>
<br />
<asp:Button ID="btnCategory" runat="server" Text="Submit"></asp:Button>
</p>
</asp:Content>
<asp:Content ID="RightBodyContent" runat="server"
ContentPlaceHolderID="RightContent">
<p>
Right Content
</p>
</asp:Content>
a. In the Default.aspx window, locate and select the Content control with an ID attribute value of
RightBodyContent, and then press CTRL+X.
b. Place the cursor after the closing Content tag for the Content control with an ID attribute value
of LeftBodyContent, and then press CTRL+V.
Lab Answer Key: Applying Master Pages and CSS 7
Task 6: Test the Default.aspx page
1. Test the page by pressing CTRL+F5.
Note: The rendered page should appear as follows. Notice the content displayed in two columns.
2. Close Windows Internet Explorer.
In the Home Page Windows Internet Explorer window, click the Close button.
3. Close Visual Studio 2010.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Exercise 3: Integrate a Master Page
Task 1: Open an existing ASP.NET web application
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.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 03 or D:\Lab
Files\VB\Lab 11\Starter\Exercise 03 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:\Lab Files\CS\Lab
11\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starter\Exercise
03\AdventureWorks.sln, and then click Open.
Task 2: Open the Site.Master master page
Open the Site.Master file.
In Solution Explorer, double-click Site.Master.
8 Lab Answer Key: Applying Master Pages and CSS
Task 3: Create an area on the master page to display status messages
Create a Label control named StatusMessageLabel in the div element with a class attribute value of
main.
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
<asp:Label ID="StatusMessageLabel" runat="server" />
</div>
In the Site.Master window, in the div element with a class attribute value of main, after the
ContentPlaceHolder control, type the following markup.
<asp:Label ID="StatusMessageLabel" runat="server" />
Task 4: Create a property that populates the status area
1. Open the Site.Master master page in Code view.
In the Site.Master window, right-click anywhere, and then click View Code.
2. Create a new property named StatusMessage in the SiteMaster or Site class.
[Visual C#]
public string StatusMessage
{
get { return StatusMessageLabel.Text; }
set { StatusMessageLabel.Text = value; }
}
[Visual Basic]
Public Property StatusMessage() As String
Get
Return StatusMessageLabel.Text
End Get
Set(ByVal value As String)
StatusMessageLabel.Text = value
End Set
End Property
Task 5: Set the status property in child pages
1. To allow for the About.aspx and Products.aspx pages to access properties on the master using a
strongly typed reference, add a MasterType directive.
[Visual C#]
<%@ MasterType TypeName="AdventureWorks.SiteMaster" %>
[Visual Basic]
<%@ MasterType TypeName="AdventureWorks.Site" %>
a. In Solution Explorer, double-click About.aspx.
b. In the About.aspx window, after the Page directive, add the following markup.
[Visual C#]
<%@ MasterType TypeName="AdventureWorks.SiteMaster" %>
Lab Answer Key: Applying Master Pages and CSS 9
[Visual Basic]
<%@ MasterType TypeName="AdventureWorks.Site" %>
c. In Solution Explorer, double-click Products.aspx.
d. In the Products.aspx window, after the Page directive, add the following markup.
[Visual C#]
<%@ MasterType TypeName="AdventureWorks.SiteMaster" %>
[Visual Basic]
<%@ MasterType TypeName="AdventureWorks.Site" %>
2. In the Page_Load event handler for the About.aspx page, set the StatusMessage property.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
Master.StatusMessage = "You are on the About page";
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Master.StatusMessage = "You are on the About page"
End Sub
a. In the AdventureWorks - Microsoft Visual Studio window, click About.aspx.
b. In the About.aspx window, right-click anywhere, and then click View Code.
c. In the Page_Load event handler method, type the following code.
[Visual C#]
Master.StatusMessage = "You are on the About page";
[Visual Basic]
Master.StatusMessage = "You are on the About page"
3. In the Page_Load event handler for the Products.aspx page, set the StatusMessage property.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string categoryName;
string categoryId = "5";
if (Request["id"] != null)
{
categoryId = Request["id"];
}
categoryName =
DataAccessLayer.Products.GetCategoryName(int.Parse(categoryId));
10 Lab Answer Key: Applying Master Pages and CSS
lblCategory.Text = categoryName;
var data =
DataAccessLayer.Products.GetProductsByCategory(int.Parse(categoryId));
gvProducts.DataSource = data;
gvProducts.DataBind();
}
Master.StatusMessage = "You are on the Products page";
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
If Not Page.IsPostBack Then
Dim categoryName As String = Nothing
Dim categoryID As String = "5"
If Not Request("id") Is Nothing Then
categoryID = Request("id")
End If
categoryName =
AdventureWorks.DataAccessLayer.Products.GetCategoryName(Integer.Parse(categoryID))
lblCategory.Text = categoryName
Dim data =
AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(Integer.Parse(categoryI
D))
gvProducts.DataSource = data
gvProducts.DataBind()
End If
Master.StatusMessage = "You are on the Products page"
End Sub
a. ntureWorks - Microsoft Visual Studio window, click Products.aspx.
b. In the Products.aspx window, right-click anywhere, and then click View Code.
In the Page_Load event handler method, append the following code.
In the Adve
c.
[Visual C#]
Master.StatusMessage = "You are on the Products page";
[Visual Basic]
Master.StatusMessage = "You are on the Products page"
4. Run t
5. On the Products page, scroll down to see the status message.
6. Open the About page.
In the http://localhost:xxxx/Products.aspx - Windows Internet Explorer window, click
he application by pressing CTRL+F5.
About.
7. On the About page, notice the status message.
Lab Answer Key: Applying Master Pages and CSS 11
8. Close Windows Internet Explorer.
In the About Us Windows Internet Explorer window, click the Close button.
ks Microsoft Visual Studio window, click the Close button.
Ex
b application
EN-DEV, point to All Programs, click Microsoft Visual Studio
CS\Lab 11\Starter\Exercise 04 or D:\Lab
io window, on the File menu, click Open Project.
r\Exercise
t.
rks, point to Add, point to Add ASP.NET Folder,
fault and then press ENTER.
e
der.
Add, and then click New
entureWorks dialog box, in the middle pane, click Skin File, in the
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.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 12\Starter\Exercise 01 or D:\Lab
Files\VB\Lab 12\Starter\Exercise 01 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:\Lab Files\CS\Lab
12\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 12\Starter\Exercise
01\AdventureWorks.sln, and then click Open.
Task 2: Register a jQuery library in the HTML header
1. Open the Site.Master master page.
In Solution Explorer, double-click Site.Master.
2. Ensure that the jquery-1.4.1.js and jquery.tablesorter.min.js file are located in the Scripts folder.
3. In Solution Explorer, expand Scripts.
4. Locate the jquery-1.4.1.js and jquery.tablesorter.min.js files.
5. In the head element of the Site.Master file, add the following script elements.
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script src='<%= ResolveUrl("~/Scripts/jquery-1.4.1.js") %>'
type="text/javascript"></script>
<script src='<%= ResolveUrl("~/Scripts/jquery.tablesorter.min.js") %>'
type="text/javascript"></script>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
In the Site.Master window, in the head element, after the link element, type the following
markup.
<script src='<%= ResolveUrl("~/Scripts/jquery-1.4.1.js") %>'
type="text/javascript"></script>
<script src='<%= ResolveUrl("~/Scripts/jquery.tablesorter.min.js") %>'
type="text/javascript"></script>
Note: Make sure that you add the closing script tag (</script>) and not the self-closing script tag
(</>). The self-closing tag for the script references is not recognized by the browsers.
Best Practices: For Web Forms applications, you can use the ResolveUrl method, which correctly
resolves the URL relative to the request.
Lab Answer Key: Developing Client-side Scripts and Services 3
Task 3: Use selectors and events
1. Run the application.
In the AdventureWorks Microsoft Visual Studio window, press CTRL+F5.
2. Select the Bike Stands product category and click Submit.
In the Home Page Windows Internet Explorer window, in the Product Categories list, click
Bike Stands, and then click Submit.
3. Select the All-Purpose Bike Stand product.
In the http://localhost:xxxxx/Products.aspx?id=31 Windows Internet Explorer window,
click All-Purpose Bike Stand.
4. Add the product to the shopping cart.
In the http://localhost:xxxxx/ProductDetail.aspx?id=879 Windows Internet Explorer
window, click Order.
5. View the source for the rendered page.
In the http://localhost:xxxxx/ShoppingCart.aspx Windows Internet Explorer window, on
the View menu, click Source.
6. Locate the gvCart GridView control, and note the ID for the rendered server control.
<table cellspacing="0" rules="all" border="1" id="MainContent_gvCart" style="border-
collapse:collapse;">
Scroll down to find the rendered i for the gvCart server control. Look for the first text containing
the server control name gvCart. Notice the rendered id, MainContent_gvCart, and how by
default the GridView control does not render the thead and tbody HTML elements.
7. Close the source window.
In the http://localhost:xxxxx/ShoppingCart.aspx Original Source window, click the Close
button.
8. Close Windows Internet Explorer.
In the Home Page Windows Internet Explorer window, click the Close button.
9. In the Site.Master master page, insert the following JavaScript element, after the closing html tag.
<script type="text/javascript">
$(document).ready(function () {
$("#MainContent_gvCart").tablesorter();
});
</script>
Task 4: Use the tableSorter jQuery library to allow client-side sorting
1. Open the ShoppingCart.aspx Web Form in Code view.
In Solution Explorer, right-click ShoppingCart.aspx, and then click View Code.
2. Update the Page_Load method to reflect the following code. (This ensures that the thead and tbody
HTML elements are rendered with the GridView control.)
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
4 Lab Answer Key: Developing Client-side Scripts and Services
{
if (Session["_cart"] != null)
{
List<clsShoppingCart> cart = (List<clsShoppingCart>) Session["_cart"];
gvCart.DataSource = cart;
gvCart.DataBind();
}
else
{
lblMessage.Text = "Your cart is empty";
btnPlaceOrder.Visible = false;
}
}
if (this.gvCart.Rows.Count > 0)
{
gvCart.UseAccessibleHeader = true;
gvCart.HeaderRow.TableSection = TableRowSection.TableHeader;
gvCart.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
If Not Session("_cart") Is Nothing Then
Dim cart = CType(Session("_cart"), List(Of clsShoppingCart))
gvCart.DataSource = cart
gvCart.DataBind()
Else
lblMessage.Text = "Your cart is empty"
btnPlaceOrder.Visible = False
End If
If gvCart.Rows.Count > 0 Then
gvCart.UseAccessibleHeader = True
gvCart.HeaderRow.TableSection = TableRowSection.TableHeader
gvCart.FooterRow.TableSection = TableRowSection.TableFooter
End If
End Sub
In the ShoppingCart.aspx window, in the ShoppingCart class, in the Page_Load method,
append the following code.
[Visual C#]
if (this.gvCart.Rows.Count > 0)
{
gvCart.UseAccessibleHeader = true;
gvCart.HeaderRow.TableSection = TableRowSection.TableHeader;
gvCart.FooterRow.TableSection = TableRowSection.TableFooter;
}
[Visual Basic]
If gvCart.Rows.Count > 0 Then
gvCart.UseAccessibleHeader = True
gvCart.HeaderRow.TableSection = TableRowSection.TableHeader
gvCart.FooterRow.TableSection = TableRowSection.TableFooter
Lab Answer Key: Developing Client-side Scripts and Services 5
End If
3. Run the application.
In Solution Explorer, click AdventureWorks, and then press CTRL+F5.
4. Select the Bike Stands product category, and then click Submit.
In the Home Page Windows Internet Explorer window, in the Product Categories list, click
5. Select the All-Purpose Bike Stand product.
In the http://localhost:xxxxx/Products.aspx?id=31 Windows Internet Explorer window,
6. Add the product to the shopping cart.
In the http://localhost:xxxxx/ProductDetail.aspx?id=879 Windows Internet Explorer
7. Continue shopping.
In the http://localhost:xxxxx/ShoppingCart.aspx Windows Internet Explorer window, click
8. Select the Bib-Shorts product category, and then click Submit.
In the Home Page Windows Internet Explorer window, in the Product Categories list, click
9. Select the Men's Bib-Shorts, L product.
In the http://localhost:xxxxx/Products.aspx?id=22 Windows Internet Explorer window,
10. Add the product to the shopping cart.
In the http://localhost:xxxxx/ProductDetail.aspx?id=857 Windows Internet Explorer
11. View the source for the rendered page.
In the http://localhost:xxxxx/ShoppingCart.aspx Windows Internet Explorer window, on
12. Locate the gvCart GridView control, and note that the thead and tbody HTML elements are
Continue Shopping.
6. Close Windows Internet Explorer.
In the Home Page Windows Internet Explorer window, click the Close button.
Task 6: Turn off the virtual machine and revert the changes
264A-GEN-DEV, and then click
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
4. In the Revert Virtual Machine dialog box, click Revert.
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10
Turn Off.
Revert.
Lab Answer Key: Implementing Advanced Ajax in a Web Application 1
Module 13
Lab Answer Key: Implementing Advanced Ajax in a Web
Application
Contents:
Exercise 1: Using Microsoft Ajax in an MVC Page 2
Exercise 2: Using jQuery in an MVC View 6
Exercise 3: Handling Events 8
2 Lab Answer Key: Implementing Advanced Ajax in a Web Application
Lab 13: Implementing Advanced Ajax for the
AdventureWorks Web Application
Exercise 1: Using Microsoft Ajax in an MVC Page
Task 1: Open an existing ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. 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.
3. Open the AdventureWorksMvc solution from the D:\Lab Files\CS\Lab 13\Starter\Exercise 01 or
D:\Lab Files\VB\Lab 13\Starter\Exercise 01 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:\Lab Files\CS\Lab
13\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 13\Starter\Exercise
01\AdventureWorksMvc.sln, and then click Open.
Task 2: Add the Ajax libraries to the pages
1. Open the Site.Master file, located in the Views/Shared folder.
In Solution Explorer, expand Views, expand Shared, and then double-click Site.Master.
2. At the top of the Site.Master file, in the head element, add a reference to the Microsoft Ajax
libraries.
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>"
type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
type="text/javascript"></script>
In the Site.Master window, in the head element, append the following markup.
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>"
type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
type="text/javascript"></script>
Task 3: Update the Index action method
1. Locate the Index action method in the Products controller.
In Solution Explorer, expand Controllers, and then double-click ProductsController.cs or
ProductsController.vb.
2. Return the product categories from the Index action method by modifying the existing code.
Lab Answer Key: Implementing Advanced Ajax in a Web Application 3
[Visual C#]
public ActionResult Index(string CategoryID)
{
int id = int.Parse(CategoryID);
var prodCategories = pr.GetCategories();
return View(prodCategories);
}
[Visual Basic]
Public Function Index(ByVal CategoryID As String) As ActionResult
Dim id As Integer = CInt(CategoryID)
Dim prodCategories = pr.GetCategories()
Return View(prodCategories)
End Function
In the ProductsController.cs or ProductsController.vb window, modify the content of the
Index method from the following:
[Visual C#]
int id = int.Parse(CategoryID);
var products = pr.GetProductsByCategory(id);
return View(products);
[Visual Basic]
Dim id As Integer = CInt(CategoryID)
Dim products = pr.GetProductsByCategory(id)
Return View(products)
So that it appears as follows:
[Visual C#]
var prodCategories = pr.GetCategories();
return View(prodCategories);
[Visual Basic]
Dim prodCategories = pr.GetCategories()
Return View(prodCategories)
Task 4: Create an Ajax Product Categories partial view
1. Create a strongly typed, partial view named _AjaxProductCategories, based on the
IEnumerable<AdventureWorksMvc.Models.ProductCategory> or IEnumerable(Of
AdventureWorksMvc.Models.ProductCategory) data class.
a. In Solution Explorer, under Views, right-click Products, point to Add, and then click View.
b. In the Add View dialog box, in the View name box, type _AjaxProductCategories, select the
Create a partial view (.ascx) check box, select the Create a strongly-typed view check box, in
the View data class box, type
4 Lab Answer Key: Implementing Advanced Ajax in a Web Application
IEnumerable<AdventureWorksMvc.Models.ProductCategory> or IEnumerable(Of
AdventureWorksMvc.ProductCategory), and then click Add.
2. Insert the following markup and code in the _AjaxProductCategories.ascx file, after the Control
directive.
[Visual C#]
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "productCategories" }))
{ %>
<select size="4" id="CategoryID" name="CategoryID" style="height: 270px; width:
186px;">
<% foreach (var ProductCategory in Model)
{ %>
<option value="<%= ProductCategory.ProductCategoryID %>">
<%= Html.Encode(ProductCategory.Name)%>
</option>
<% } %>
</select>
<div id="productCategories">
</div>
<% } %>
[Visual Basic]
<% Using (Ajax.BeginForm(New AjaxOptions With {.UpdateTargetId = "productCategories"
}))%>
<select size="4" id="CategoryID" name="CategoryID" style="height: 270px; width:
186px;">
<% For Each ProductCategory In Model%>
<option value="<%= ProductCategory.ProductCategoryID %>">
<%= Html.Encode(ProductCategory.Name)%>
Lab Answer Key: Implementing Advanced Ajax in a Web Application 5
</option>
<% Next%>
</select>
<div id="productCategories">
</div>
<% End Using%>
Task 5: Render the Partial view on the Index view
1. Open the Index.aspx view in the Views/Products folder.
In Solution Explorer, expand Views, expand Products, and then double-click Index.aspx.
2. Delete the existing markup in the Content2 Content control.
In the Index.aspx window, select the markup between the opening and closing Content tags, for
the Content control with an ID attribute value of Content2, and then press DELETE.
3. Add the following markup to the Index view, at the top of the Content2 Content control.
[Visual C#]
<h2>
Product Catalog</h2>
<label>
Choose a Category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model);%>
[Visual Basic]
<h2>
Product Catalog</h2>
<label>
Choose a category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model)%>
4. Delete the existing markup in the Content1 Content control.
In the Index.aspx window, select the markup between the opening and closing Content tags, for
the Content control with an ID attribute value of Content1, and then press DELETE.
5. Add the following markup to the Index view, at the top of the Content1 Content control.
Products
6. Base the Index view on a different data class, by modifying the Inherits attribute value in the Page
directive.
[Visual C#]
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.ProductCategor
y>>"
6 Lab Answer Key: Implementing Advanced Ajax in a Web Application
[Visual Basic]
Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of
AdventureWorksMvc.ProductCategory))"
In the Index.aspx window, modify the Inherits attribute in the Page directive, to contain the
following value.
[Visual C#]
System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.ProductCategory>>
[Visual Basic]
System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.ProductCategory))
7. Build the solution and fix any errors.
In the AdventureWorksMvc Microsoft Visual Studio window, press CTRL+SHIFT+B.
8. Close Visual Studio 2010.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Exercise 2: Using jQuery in an MVC View
Task 1: Open an existing ASP.NET web application
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.
2. Open the AdventureWorksMvc solution from the D:\Lab Files\CS\Lab 13\Starter\Exercise 02 or
D:\Lab Files\VB\Lab 13\Starter\Exercise 02 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:\Lab Files\CS\Lab
13\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 13\Starter\Exercise
02\AdventureWorksMvc.sln, and then click Open.
Task 2: Add the jQuery library to the pages
1. Open the Site.Master file, located in the Views/Shared folder.
In Solution Explorer, expand Views, expand Shared, and then double-click Site.Master.
2. At the top of the Site.Master file, in the head element, add a reference to the Microsoft Ajax
libraries.
<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"
type="text/javascript"></script>
In the Site.Master window, in the head element, append the following markup.
<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"
type="text/javascript"></script>
Task 3: Create the Featured Products action
1. Open the ProductsController.cs or ProductsController.vb file in the Controllers folder.
Lab Answer Key: Implementing Advanced Ajax in a Web Application 7
In Solution Explorer, expand Controllers, and then double-click ProductsController.cs or
ProductsController.vb.
2. Create an action for the Ajax method to call. The following code returns a view populated with
products.
[Visual C#]
public ViewResult FeaturedProducts(string CategoryId)
{
int id = int.Parse(CategoryId);
var products = pr.GetProductsByCategory(id);
return View("_FeaturedProducts", products);
}
[Visual Basic]
Public Function FeaturedProducts(ByVal CategoryId As String) As ViewResult
Dim id As Integer = Integer.Parse(CategoryId)
Dim products = pr.GetProductsByCategory(id)
Return View("_FeaturedProducts", products)
End Function
Task 4: Load the Featured Products when a category is clicked
1. Open the Index.aspx view in the Views/Products folder.
In Solution Explorer, expand Views, expand Products, and then double-click Index.aspx.
2. The Ajax method needs a place to put the results from the called function. Add a div element
at the bottom of the page, before the closing Content tag.
<br />
<div id="featured-products"></div>
In the Index.aspx window, in the Content2 Content element, append the following markup.
<br />
<div id="featured-products"></div>
3. Create the Ajax method call. This function calls the controller action, and then returns the
results into the featured products div created earlier. Add the following markup to handle the
click event for the rendered select element, at the bottom of the page, before the closing Content
tag.
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryID ").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>', {
CategoryId: id });
});
});
</script>
4. Run the application.
In Solution Explorer, click AdventureWorksMvc, and then press CTRL+F5.
8 Lab Answer Key: Implementing Advanced Ajax in a Web Application
5. In Windows
Internet Explorer
, click Submit.
In the Welcome to AdventureWorks Windows Internet Explorer window, click Submit.
6. In Windows Internet Explorer, in the Choose a category list, click Bib-shorts.
In the Products Windows Internet Explorer window, in the Choose a category list, click Bib-
shorts.
Note: The products for the chosen category are displayed below the list.
7. Close Windows Internet Explorer.
In the Products Windows Internet Explorer window, click the Close button.
8. Close Visual Studio 2010.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Exercise 3: Handling Events
Task 1: Open an existing ASP.NET web application
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.
2. Open the AdventureWorksMvc solution from the D:\Lab Files\CS\Lab 13\Starter\Exercise 03 or
D:\Lab Files\VB\Lab 13\Starter\Exercise 03 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:\Lab Files\CS\Lab
13\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 13\Starter\Exercise
03\AdventureWorksMvc.sln, and then click Open.
Task 2: Display a status message
1. Open the Index.aspx page in the Views/Products folder.
In Solution Explorer, expand Views, expand Products, and then double-click Index.aspx.
2. Before the featured-products div element, add a div to display the Ajax status messages.
<div class="log"></div>
3. After the featured-products div element, add a div to display the Ajax error messages.
<div class="error"></div>
4. In the $(document).ready jQuery function, add the following functions to display and hide the status
messages.
$(document).ready(function () {
$("#CategoryID").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>', {
CategoryId: id });
});
$('.log').ajaxStart(function () {
Lab Answer Key: Implementing Advanced Ajax in a Web Application 9
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
});
In the Index.aspx window, add the following code:
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
...after this code.
$(document).ready(function () {
$("#CategoryID ").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>', {
CategoryId: id });
});
1. After the .ajaxComplete function, add the follo
Task 3: Alert the user when an error occurs
wing function to display the alert.
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});
In the Index.aspx window, add the following code:
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});
...after this code.
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
2. Ensure that the Index view page matches the following.
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.ProductCategor
y>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Products
10 Lab Answer Key: Implementing Advanced Ajax in a Web Application
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Product Catalog</h2>
<label>
Choose a category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model);%>
<br />
<div class="log">
</div>
<div id="featured-products">
</div>
<div class="error">
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryID").click(function () {
var id = $(this).val();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>',
{ CategoryId: id });
});
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});
});
</script>
</asp:Content>
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of
AdventureWorksMvc.ProductCategory))" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Products
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Product Catalog</h2>
<label>
Choose a category:</label>
<br />
<% Html.RenderPartial("_AjaxProductCategories", Model)%>
<br />
<div class="log">
</div>
<div id="featured-products">
</div>
<div class="error">
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryID").click(function () {
var id = $(this).val();
Lab Answer Key: Implementing Advanced Ajax in a Web Application 11
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>',
{ CategoryId: id });
});
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');
});
$('.log').ajaxComplete(function () {
$(this).text('');
});
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});
});
</script>
</asp:Content>
1. Run the application.
Task 4: Test the Index view
In Solution Explorer, click AdventureWorksMvc, and then press CTRL+F5.
2. In Windows Internet Explorer, click Submit.
In the Welcome to AdventureWorks Windows Internet Explorer window, click Submit.
3. In Windows Internet Explorer, in the Choose a category list, click Bib-shorts.
In the Products Windows Internet Explorer window, in the Choose a category list, click Bib-
Note: The products for the chosen category are displayed below the list, but first you see the Loading...
shorts.
notice.
4. Close Windows Internet Explorer.
In the Products Windows Internet Explorer window, click the Close button.
5. Close Visual Studio 2010.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Task 5: Turn off the virtual machine and revert the changes
264A-GEN-DEV, and then click
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
4. In the Revert Virtual Machine dialog box, click Revert.
1. In Hyper-V Manager, in the Virtual Machines pane, right-click 10
Turn Off.
Revert.
Lab Answer Key: ASP.NET Deployments 1
Module 14
Lab Answer Key: ASP.NET Deployments
Contents:
Exercise 1: Creating a Profile for Deploying a Web Application Project
Using One-Click Publish 2
Exercise 2: Creating a Web Deployment Package 5
2 Lab Answer Key: ASP.NET Deployments
Lab 14: Deploying AdventureWorks
Exercise 1: Creating a Profile for Deploying a Web Application Project Using
One-Click Publish
Task 1: Create a new ASP.NET web application
1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
2. 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.
3. Create a new ASP.NET Web Application named Deployment in the D:\Lab Files\CS\Lab
14\Starter\Exercise 01 or D:\Lab Files\VB\Lab 14\Starter\Exercise 01 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 Deployment, in the Location
box, type D:\Lab Files\CS\Lab 14\Starter\Exercise 01 or D:\Lab Files\VB\Lab
14\Starter\Exercise 01, and then click OK.
Task 2: Create an ASP.NET Application Services database
1. View the Account\Register.aspx Web Form in Windows
Internet Explorer
.
In Solution Explorer, expand Account, right-click Register.aspx, and then click View in Browser.
2. On the Create New Account page, type the following information, and then click Create User.
User Name: Student
E-mail: student@adventureworks.com
Password: Pa$$w0rd
Confirm Password: Pa$$w0rd
3. In the Register Windows Internet Explorer window, in the User Name box, type Student, in the
E-mail box, type student@adventureworks.com, in the Password box, type Pa$$w0rd, and in the
Confirm Password box, type Pa$$w0rd.
Note: An ASP.NET Application Services SQL Server
Silverlight