Upload
carlos-betancourt
View
63
Download
0
Embed Size (px)
Citation preview
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 1/449
O F F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T
10264A
Lab Instructions and Lab Answer Key:Developing Web Applications withMicrosoft® Visual Studio® 2010
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 2/449
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/orother countries.
All other trademarks are property of their respective owners.
Product Number: 10264A
Part Number: X17-47398
Released: 11/2010
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 3/449
Lab Instructions: Overview of Web Application Architecture and Design 1
Module 1
Lab Instructions: Overview of Web Application Architectureand 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 4/449
2 Lab Instructions: Overvi w of Web Application Architecture and esign
ab 1: E plorin the Adventu
• • • I
InF
a
Fi
bjectives:
Describe th
Explain co
Describe th
troductio
this lab, yourthermore, y
plication dev
nally, you will
e Adventure
e differences
e request life
will review thu will compa
elopment by
explore how t
orks website
between Web
cycle for both
existing Adve how applic
sing the MV
o create cont
re Works We site
.
Forms and MVC.
Web Forms and MVC.
nture Workstion develop
framework.
ebsite and bent by using
ecome familiaWeb Forms d
r with its desiiffers from
n.
ols dynamicallly by adding n advertisement on the pa e.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 5/449
Lab Instructions: Overview of eb Application Architecture and Design 3
A
h
a
e
p
ab Sce
s a web devel
ave limited ex
complish the
d, you want t
rogramming
ario
per at Adven
perience with
goals set by
o examine th
odel.
ture Works, y
ASP.NET 4.0.
anagement f
MVC frame
u have work
ou need to f
or the new Ad
ork and unde
d extensively
rther explore
venture Work
rstand how it
with ASP.NET
the features o
s website. As
compares wit
2.0. However,
f ASP.NET 4.0
first step to
the Web For
you
to
ard this
ms
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 6/449
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.
f 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
f Task 2: Start the web application
• Run the AdventureWorks solution in Debug mode.
f 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.
f Task 4: Add products to the shopping cart
1. Add one pair of Men’s Bib-Shorts, size M, to the shopping cart.
2. Continue shopping.
f Task 5: Place an order
1. Open the shopping cart.
2. Place the order.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 7/449
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.
f 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
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 8/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 9/449
Lab Instructions: Overview of Web Application Architecture and Design 7
Exercise 2: Comparing Web Forms and MVCThe 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.
f Task 1: View the AdventureWorks solution in Visual Studio 2010
Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.
f 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.
f Task 3: View AdventureWorksMvc solution Microsoft Visual Studio 2010
• Switch to the Visual Studio 2010 instance with the AdventureWorksMvc solution open.
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 10/449
8 Lab Instructions: Overview of Web Application Architecture and Design
Exercise 3: Working with the Request Life CycleThe 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.
f Task 1: Explore the life cycle of a Web Forms page1. 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 page’s Load event, the text is added to the lblAdvertisement Label control.
8. Close Windows Internet Explorer.
9. Close Visual Studio 2010.
f 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#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 11/449
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 controller’s Index action method, the text is added to Index view by using the
ViewData.
9. Close Windows Internet Explorer.
10. Close Visual Studio 2010.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 12/449
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 13/449
2 Lab Instructions: Designiing a Web Application
ab 2: Redesig ing th
N
A
• • • I
In
di
t
ote: Tasks in
bjectives:
fter completin
Draw diagr
Identify wh
business re
Add MVC
troductio
this lab, you
iagramming it
anagement, a
VC. You will a
at you can g
his lab will be
g this lab, yo
ams showing
ich pages of t
quirements.
apabilities to
will first captu
s overall archi
nd recomme
lso do the gr
t started as so
Adve ture orks ebsite
the same reg
will be able t
he overall arc
he website wil
the existing w
re your under
tecture and p
d which page
undwork nec
on as Manag
ardless of the
o:
hitecture and
l use Web For
ebsite.
standing of th
ge flow. You
s of the websi
ssary for add
ment approv
programming
page flow of
ms, and whic
e current Adv
will then revie
te will use We
ing MVC capa
al comes thro
language yo r solution is sing.
the Adventur Works websi e.
pages will use MVC, based on
enture Works
w the busines
b Forms, and
bilities to the
gh.
website by
s requirement
which pages
existing websi
s set by
ill use
te so
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 14/449
Lab Instructions: Designin a Web Application 3
N
d
t
r
c
e
ab Sce
ow that you h
VC to develo
etailing reco
e current we
designed we
sts and bene
umerate the
ario
ave a better u
some pages
mendations f
site and reco
site. Keep in
its of your de
rationale und
nderstanding
of the Advent
r redesignin
mend an ap
ind that you
isions before
rlying your r
of Web Form
ure Works we
the website.
ropriate pro
are operating
making reco
commendati
s and MVC, y
bsite. Your ne
Your proposal
ramming mo
on a tight bu
mendations.
ns to help m
u can see the
xt task is to cr
needs to des
del for develo
dget, so you
The proposal
nagement as
benefits of us
eate a propos
ribe the struc
ping the page
eed to consid
should also
ess them.
ing
al
ture of
s of the
er the
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 15/449
4 Lab Instructions: Designing a Web Application
Exercise 1: Reviewing the Adventure Works Website StructureThe 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.
f 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#® D:\Lab Files\CS\Lab 02\Solution\Exercise 01
Visual Basic® D:\Lab Files\VB\Lab 02\Solution\Exercise 01
f Task 2: Examine the code and markup location and purpose
• Analyze the solution and determine its intent and structure.
f Task 3: Draw a diagram showing the overall architecture
• On a sheet of paper, draw a diagram describing the overall Adventure Works website architecture,
based on your analysis.
f Task 4: Draw a diagram showing the page flow
• On a sheet of paper, draw a diagram showing the page flow of the AdventureWorks web application,based on your analysis.
f Task 5: Discuss your findings with the class
• Discuss the diagrams created amongst the class.
Results: After completing this exercise, you should have created two diagrams describing the existing
architecture and page flow of the AdventureWorks web application.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 16/449
Lab Instructions: Designing a Web Application 5
Exercise 2: Redesigning the Adventure Works WebsiteThe main tasks for this exercise are as follows:
• Read the requirements document.
• Determine which pages will use Web Forms and which will use MVC.
• Discuss your recommendations and their rationale with the class.
f Task 1: Read the requirements document
• The redesigned AdventureWorks web application must meet the requirements as set by management
and listed in the following sections.
Business Requirements and Considerations
• Build a responsive, rich, and interactive UI
• Enhance the performance of existing pages and resolve errors
• Use URLs that are search engine friendly and facilitate indexing of products by search engines
• Include a section for blogs
• Include an administration section to enable the Sales team to manage information stored in thedatabase
• Secure the blog management pages and the administration section
Functional Requirements: Shopping Cart
• List product categories
• Click a category to display products
• Display products in a detailed view
• Add products to the shopping cart
• Remove products from the shopping cart
• Submit the shopping cart
Functional Requirements: Blogs
• Log on to the website
• Add a new blog entry
• Edit and delete blog entries
• Add anonymous comments
• Approve comments
Functional Requirements: Administration Section
• Log on to the website
• Manage products
• Manage product categories
• Manage sales order headers
• Manage customers
• User Interface Requirements
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 17/449
6 Lab Instructions: Designing a Web Application
• Display a welcome message on the home page in English or French (Canada)
• Minimize page refreshes
• Provide support for easily changing the overall look of the application
• Reflect the corporate branding and propose two styles based on the corporate colors
• Display a marketing message on the Product Detail page• Display a product advertisement on the blog pages
• Display a ticker showing biking-related news headlines on the blog pages
f Task 2: Determine which pages will use Web Forms and which will use MVC
• Based on the requirements given, determine and document which pages will remain Web Forms
pages and which will be implemented in MVC.
f Task 3: Discuss your recommendations and their rationale with the class
• Discuss the recommendations created with the class.
Results: After completing this exercise, you should have reviewed the requirements document for theAdventure Works website, determined which pages will remain Web Forms pages and which will use
MVC, and discussed your recommendations and their rationale with the class.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 18/449
Lab Instructions: Designing a Web Application 7
Exercise 3: Adding MVC Capabilities to the Adventure Works WebsiteThe main tasks for this exercise are as follows:
• Open the AdventureWorks solution in Visual Studio 2010.
• Add required assemblies to the project.
• Add the MVC Assembly references and namespaces to the Web.config file.
• Map the default MVC request routes.
• Change project to reflect an MVC Project.
f Task 1: Open the AdventureWorks solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 02\Starter\Exercise 03
Visual Basic D:\Lab Files\VB\Lab 02\Starter\Exercise 03
f Task 2: Add required assemblies to the project
1. Add references to the System.Web.Abstractions assembly to the project.
2. Add references to the System.Web.MVC and System.Web.Routing assemblies to the project.
f Task 3: Add the MVC Assembly references and namespaces to the Web.config file
1. Open the Web.config file in the root AdventureWorks folder.
2. Add the following text to your Web.config file in their proper sections as shown, this adds the
appropriate assemblies to your project and configures special MVC handlers:
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>...
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/></assemblies>
</compilation>
...
<pages><namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/><add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
</namespaces></pages>
<httpHandlers>
<add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler"/></httpHandlers>
</system.web>
<system.webServer>...
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 19/449
8 Lab Instructions: Designing a Web Application
<handlers>
<remove name="MvcHttpHandler"/><add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc"
type="System.Web.Mvc.MvcHttpHandler"/>
</handlers></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31BF3856AD364E35"/>
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/></dependentAssembly>
</assemblyBinding>
</runtime>
3. Save the Web.config file.
The final Web.config file should appear as follows
[Visual C#]
<?xml version="1.0"?>
<configuration><appSettings />
<connectionStrings>
<add name="ApplicationServices" connectionString="data
source=.\SQLEXPRESS;IntegratedSecurity=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="AdventureWorksEntities"connectionString="metadata=res://*/mdlAdventureWorks.csdl|res://*/mdlAdventureWorks.ss
dl|res://*/mdlAdventureWorks.msl;provider=System.Data.SqlClient;provider connection
string="Data Source=.\sqlexpress;Initial
Catalog=AdventureWorksLT2008R2;IntegratedSecurity=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
</connectionStrings><system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/><add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</assemblies></compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" /></authentication>
<membership>
<providers>
<clear /><add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="ApplicationServices" enablePasswordRetrieval="false"enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="false" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" applicationName="/" /></providers>
</membership>
<profile>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 20/449
Lab Instructions: Designing a Web Application 9
<providers>
<clear /><add name="AspNetSqlProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ApplicationServices" applicationName="/" /></providers>
</profile>
<roleManager enabled="false"><providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /></providers>
</roleManager>
<pages><namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/><add namespace="System.Web.Routing"/>
</namespaces>
</pages><httpHandlers>
<add verb="*" path="*.mvc" validate="false"
type="System.Web.Mvc.MvcHttpHandler"/>
</httpHandlers></system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" /><handlers>
<remove name="MvcHttpHandler"/>
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc"
type="System.Web.Mvc.MvcHttpHandler"/></handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31BF3856AD364E35"/><bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding></runtime>
</configuration>
[Visual Basic]
<?xml version="1.0" encoding="utf-8"?><!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433 -->
<configuration><connectionStrings><add name="ApplicationServices" connectionString="data
source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"providerName="System.Data.SqlClient" />
<add name="AdventureWorksEntities"
connectionString="metadata=res://*/mdlAdventureWorks.csdl|res://*/mdlAdventureWorks.ssdl|res://*/mdlAdventureWorks.msl;provider=System.Data.SqlClient;provider connection
string="Data Source=.\sqlexpress;Initial
Catalog=AdventureWorksLT2008R2;Integrated
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 21/449
10 Lab Instructions: Designing a Web Application
Security=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" /></connectionStrings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0"><assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" /><add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/></assemblies>
</compilation>
<authentication mode="Forms"><forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers><clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"connectionStringName="ApplicationServices" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="false" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership><profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider"type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile><roleManager enabled="false">
<providers><clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices" applicationName="/" /><add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers></roleManager>
<pages>
<namespaces><add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/></namespaces>
</pages><httpHandlers>
<add verb="*" path=".mvc" validate="false"
type="System.Web.Mvc.MvcHttpHandler"/>
</httpHandlers></system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" /><handlers>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 22/449
Lab Instructions: Designing a Web Application 11
<remove name="MvcHttpHandler"/>
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path=".mvc"type="System.Web.Mvc.MvcHttpHandler"/>
</handlers>
</system.webServer><runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly><assemblyIdentity name="System.Web.Mvc" PublicKeyToken="31BF3856AD364E35"/>
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly></assemblyBinding>
</runtime>
</configuration>
f Task 4: Map the default MVC request routes
1. Import the System.Web.Mvc and System.Web.Routing namespaces in Global.asax to support MVC
request routing.
[Visual C#]using System.Web.Mvc;
using System.Web.Routing;
[Visual Basic]
Imports System.Web.MvcImports System.Web.Routing
2. Create a method named RegisterRoutes to register the MVC routes and exclude routes for existing
Web Form pages, handlers, and WCF services.
[Visual C#]
public static void RegisterRoutes(RouteCollection routes)
{routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.svc/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parametersnew { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
[Visual Basic]Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}")routes.IgnoreRoute("{resource}.svc/{*pathInfo}")
routes.MapRoute(
"Default","{controller}/{action}/{id}",
New With {.controller = "Home", .action = "Index", .id = ""}
)End Sub
3. Call the RegisterRoutes in the Application_Start method.
[Visual C#]
protected void Application_Start(object sender, EventArgs e){
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 23/449
12 Lab Instructions: Designing a Web Application
RegisterRoutes(RouteTable.Routes);
}
[Visual Basic]Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RegisterRoutes(RouteTable.Routes)
End Sub
4. Save the Global.asax file.
f Task 5: Change project to reflect an MVC Project
1. Open the project, AdventureWorks.csproj or AdventureWorks.vbproj file in Notepad for direct
editing.
2. Locate the ProjectTypeGuids element.
[Visual C#]
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-
00c04f79efbc}</ProjectTypeGuids>
[Visual Basic]<ProjectTypeGuids{349c5851-65df-11da-9384-00065b846f21};{F184B08F-C81C-45F6-A57F-
5ABD9991F28F}</ProjectTypeGuids>
3. Add the following markup at the beginning of the ProjectTypeGuids element.
{F85E285D-A4E0-4152-9332-AB1D724D3325};
Note: The top of the project file should look like this.
[Visual C#]<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
...<ProjectGuid>{A8D6241C-680E-42BA-884B-501CC08D3FA9}</ProjectGuid>
<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
...
[Visual Basic]<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><PropertyGroup>
...
<ProjectGuid>{F9BE0786-D923-4DF0-9483-CE13D5D26A1F}</ProjectGuid><ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325{349c5851-65df-11da-9384-
00065b846f21};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
...
4. Save the project file.
5. Reload the AdventureWorks project.
6. Test the new project type by opening the Add New Item dialog box.
7. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 24/449
Lab Instructions: Designing a Web Application 13
f Task 6: 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 reviewed and documented the existing
AdventureWorks Web Forms application architecture and page flow, reviewed requirements
documentation and created a plan for redesigning the AdventureWorks application using MVC where it
made sense, and added MVC functionality to the existing AdventureWorks application.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 25/449
Lab Instructions: Developing MVC Models 1
Module 3
Lab Instructions: Developing MVC Models
Contents:Exercise 1: Exploring the AdventureWorks Database 4
Exercise 2: Adding an ADO.NET Entity Data Model 7
Exercise 3: Model Data Validation 12
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 26/449
2 Lab Instructions: Developing MVC Models
ab 3: Creating
A
• • • I
In
a
bjectives:
fter completin
Work with
Use Entity
Implement
troductio
this lab, you
Entity Fram
MVC odels
g this lab, yo
the Adventur
ramework da
data validatio
will create rel
work data mo
will be able t
Works datab
ta model.
n for the MV
tionships bet
del, add a dat
o:
se.
models.
een databas
a repository,
tables by usi
nd implemen
ng the Databa
t data model
se Designer,
alidation.
reate
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 27/449
Lab Instructions: Developing MVC Models 3
ab Sce ario
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 28/449
4 Lab Instructions: Developing MVC Models
Exercise 1: Exploring the AdventureWorks DatabaseThe main tasks for this exercise are as follows:
1. Open the AdventureWorksMvc solution in Visual Studio 2010.
2. Open AdventureWorks database.
3. Examine the table schemas.
4. Add Relationships between tables using Diagrams.
f 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 at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 03\Starter\Exercise 01
Visual Basic D:\Lab Files\VB\Lab 03\Starter\Exercise 01
f Task 2: Open AdventureWorks database
• Open the AdventureWorksLT2008R2 database by using Server Explorer.
f Task 3: Examine the table schemas
1. Display the list of tables.
2. Open the Customer (SalesLT) table in the Table Designer.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 29/449
Lab Instructions: Developing MVC Models 5
3. Examine the schema of the table.
4.
Close the Table Designer.
f Task 4: Add Relationships between tables using Diagrams
1. Create a new database diagram containing the Customer and CustomerAddress tables.
Note: The relationship between the Customer and CustomerAddress table is one-to-many, which
means a single customer can have multiple addresses.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 30/449
6 Lab Instructions: Developing MVC Models
2. Close the Database Designer and do not save the diagram.
3. Close Visual Studio 2010.
Result: After completing this exercise, you should have learned how to use Server Explorer to examine
the database schema and view relationships between the tables using database diagrams.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 31/449
Lab Instructions: Developing MVC Models 7
Exercise 2: Adding an ADO.NET Entity Data ModelThe main tasks for this exercise are as follows:
1. Open the AdventureWorksMvc solution in Visual Studio 2010.
2. Add Entity Data Model to the web application.
3. Add data repository.
4. Implement list, select, insert, update, and delete operations.
f Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 03\Starter\Exercise 02
Visual Basic D:\Lab Files\VB\Lab 03\Starter\Exercise 02
f Task 2: Add Entity Data Model to the web application
1. Add a new ADO.NET Entity Data Model named AdventureWorks.edmx to the project, and generate
the model from database. The model must be added to the Models folder.
2. Use the existing AdventureWorksLT2008ConnectionString connection string to connect to the
database, and save the connection settings in the Web.config file as AdventureWorksEntities.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 32/449
8 Lab Instructions: Developing MVC Models
3. Select the Blog and Blogger tables from the database and name the model namespace
AdventureWorksModel.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 33/449
Lab Instructions: Developing MVC Models 9
4. Build the solution, and fix any errors.
f Task 3: Add data repository
• Add a new data repository class named BlogRepository to the Models folder.
f Task 4: Implement list, select, insert, update, and delete operations
1. Declare and instantiate a private AdventureWorksEntities object named db in the BlogRepository
class.
[Visual C#]
private AdventureWorksEntities db = new AdventureWorksEntities();
[Visual Basic]
Private db As New AdventureWorksEntities
2. Add the following method to the BlogRepository class to return a list of all of the blogs.
[Visual C#]public IQueryable<Blog> GetAllBlogs()
{
return db.Blogs;}
[Visual Basic]
Public Function GetAllBlogs() As IQueryable(Of Blog)
Return db.BlogsEnd Function
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 34/449
10 Lab Instructions: Developing MVC Models
3. Add the following method to the BlogRepository class to return a list of all of the blogs for a specific
blogger.
[Visual C#]
public IQueryable<Blog> GetAllBlogs(int id){
return from blog in db.Blogs
where blog.BloggerID == idselect blog;
}
[Visual Basic]
Public Function GetAllBlogs(ByVal id As Integer) As IQueryable(Of Blog)Return From blog In db.Blogs
Where blog.BloggerID = id
Select blogEnd Function
4. Add the following method to the BlogRepository class to return a specific blog.
[Visual C#]
public Blog GetBlog(int id){
return (from blog in db.Blogswhere blog.BlogID == idselect blog).SingleOrDefault();
}
[Visual Basic]
Public Function GetBlog(ByVal id As Integer) As BlogReturn (From blog In db.Blogs
Where blog.BlogID = id
Select blog).SingleOrDefault()End Function
5. Add the following method to the BlogRepository class to return the name of the blogger.
[Visual C#]
public string GetBloggerName(int id){
var bloggerName = (from blogger in db.Bloggers
where blogger.BloggerID == idselect blogger.Name).FirstOrDefault();
return bloggerName;}
[Visual Basic]
Public Function GetBloggerName(ByVal id As Integer) As String
Dim bloggerName = (From blogger In db.BloggersWhere blogger.BloggerID = id
Select blogger.Name).FirstOrDefault
Return bloggerNameEnd Function
6. Add the following methods to the BlogRepository class to add, update, delete, and save individual
blogs.
[Visual C#]
public void AddBlog(Blog blog)
{db.Blogs.AddObject(blog);
}
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 35/449
Lab Instructions: Developing MVC Models 11
public void UpdateBlog(Blog blog)
{db.Blogs.ApplyCurrentValues(blog);
}
public void DeleteBlog(Blog blog)
{
db.Blogs.DeleteObject(blog);}
public void Save(){
db.SaveChanges();
}
[Visual Basic]Public Sub AddBlog(ByVal blg As Blog)
db.Blogs.ApplyCurrentValues(blg)
End Sub
Public Sub UpdateBlog(ByVal blg As Blog)
db.Blogs.Attach(blg)End Sub
Public Sub DeleteBlog(ByVal blg As Blog)db.Blogs.DeleteObject(blg)
End Sub
Public Sub Save()db.SaveChanges()
End Sub
7. Save all modified files.
8. Close Visual Studio 2010.
Result: In this exercise, you added an Entity data model to the web application, connecting it to theexisting AdventureWorks database. You also added a repository class and implemented list, select,insert, update, and delete operations in the class.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 36/449
12 Lab Instructions: Developing MVC Models
Exercise 3: Model Data ValidationThe main tasks for this exercise are as follows:
1. Open the AdventureWorksMvc solution in Visual Studio 2010.
2. Add a partial class to the Models folder.
3. Add business rules validation.
f Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 03\Starter\Exercise 03
Visual Basic D:\Lab Files\VB\Lab 03\Starter\Exercise 03
f Task 2: Add a partial class to the Models folder
1. Add a new class named Blog to the Models folder.
2. Make the Blog class partial, by prefixing with the keyword partial / Partial.
[Visual C#]public partial class Blog
[Visual Basic]
Partial Public Class Blog
3. Import the System.ComponentModel and System.ComponentModel.DataAnnotations
namespaces.
[Visual C#]
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
[Visual Basic]
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel
Note: In the next section, you will add business rules validation to the partial class.
f Task 3: Add business rules validation
1. Add another class named BlogMetadata to the Blog.cs or Blog.vb code file.
[Visual C#]
public class Blog_MetaData{
[DisplayName("Blog ID")]
public object BlogID { get; set; }
[DisplayName("Date Posted")]
[DisplayFormat(DataFormatString = "{0:d}")]public object DatePosted { get; set; }
[Required]public object Title { get; set; }
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 37/449
Lab Instructions: Developing MVC Models 13
[Required][DisplayName("Blog Entry")]
public object BlogEntry { get; set; }
}
[Visual Basic]
Public Class Blog_MetaData<DisplayName("Blog ID")> _
Public Property BlogID As Object
<DisplayName("Date Posted")> _
<DisplayFormat(DataFormatString:="{0:d}")> _Public Property DatePosted As Object
<Required()> _Public Property Title As Object
<Required()> <DisplayName("Blog Entry")> _Public Property BlogEntry As Object
End Class
2. Apply the MetadataType attribute to the Blog class, and reference the Blog_Metadata type as the
metadata type.
[Visual C#]
[MetadataType(typeof(Blog_MetaData))]
public partial class Blog
[Visual Basic]
<MetadataType(GetType(Blog_MetaData))>
Partial Public Class Blog
3. Build the solution, and fix any errors.
4. Close Visual Studio 2010.
f 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.
Result: After completing this exercise you should have learned how to add a partial class to the model
and extend the behavior of the existing class using partial classes and add validation logic in the partial
class.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 38/449
Lab Instructions: Developing MVC Controllers 1
Module 4
Lab Instructions: Developing MVC Controllers
Contents:Exercise 1: Creating an MVC Controller 4
Exercise 2: Adding code to list the existing blog entries 6
Exercise 3: Adding code to create a new blog entry 9
Exercise 4: Adding code to edit a blog entry 12
Exercise 5: Adding code to delete a blog entry 16
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 39/449
2 Lab Instructions: Developing MVC Controllers
ab 4: eveloping M
N
B
A
• • • • • I
In
d
ote: You can
asic® as your
bjectives
fter completin
Create an
List the exi
Create a n
Edit a blog
Delete a bl
troductio
this lab, you
elete (CRUD)
perform the t
rogramming
g this lab, yo
VC controlle
ting blog ent
w blog entry.
entry.
og entry.
will create an
perations.
C Controllers
sks in this lab
language.
will be able t
r.
ies.
MVC controll
by using eith
o:
r and add co
er Microsoft V
e to it to per
isual C#® or icrosoft Visu l
orm create, r ad, update, a d
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 40/449
Lab I structions: Developing MVC Controllers 3
B
d
A
o
ab Sce
ased on your
eveloped by u
DO.NET Entit
perations.
ario
ecommendat
sing MVC. Yo
Data Model.
ions for redesi
have alread
Next, you nee
gning the Ad
built your M
d to develop
entureWorks
C model clas
n MVC contr
website, the
ses by leverag
oller to handl
log pages ne
ing an existin
the databas
d to be
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 41/449
4 Lab Instructions: Developing MVC Controllers
Exercise 1: Creating an MVC ControllerThe main tasks for this exercise are as follows:
• Open the AdventureWorksMvc solution in Visual Studio 2010.
• Create a controller named BlogController.
f Task 1: Open the AdventureWorksMvc solution in Visual Studio 20101. 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
f Task 2: Create a controller named BlogController1. 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'
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 42/449
Lab Instructions: Developing MVC Controllers 5
' GET: /Blog
Function Index() As ActionResult
Return View()
End FunctionEnd 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 43/449
6 Lab Instructions: Developing MVC Controllers
Exercise 2: Adding code to list the existing blog entriesThe 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.
f 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
f 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()
f 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();
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 44/449
Lab Instructions: Developing MVC Controllers 7
return View(blogs);
}
[Visual Basic]
Function Index() As ActionResult
Dim blogs = blogRepository.GetAllBlogs()
Return View(blogs)End Function
f 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 ActionResultEnd Function
2. Add code to the Blogger action method to return only the blog entries for the indicated blogger tothe 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
f Task 5: Create a Details action method1. 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 45/449
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 ThenReturn 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 46/449
Lab Instructions: Developing MVC Controllers 9
Exercise 3: Adding code to create a new blog entryThe 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.
f 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
f 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 ActionResultReturn View()
End Function
f 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]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 47/449
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.NowblogRepository.AddBlog(blg)
blogRepository.Save()
TempData("ConfirmationMessage") = blg.Title & " has been added"
Return RedirectToAction("Index")
CatchReturn 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();
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 48/449
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
Tryblg.DatePosted = DateTime.Now
blogRepository.AddBlog(blg)
blogRepository.Save()
TempData("ConfirmationMessage") = blg.Title & " has been added"
Return RedirectToAction("Index")
CatchReturn 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 49/449
12 Lab Instructions: Developing MVC Controllers
Exercise 4: Adding code to edit a blog entryThe 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.
f 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
f 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 ActionResultEnd 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);
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 50/449
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
f 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)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 51/449
14 Lab Instructions: Developing MVC Controllers
If blogEntry Is Nothing Then
Return RedirectToAction("Index")End If
TryUpdateModel(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 TryEnd Function
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 52/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 53/449
16 Lab Instructions: Developing MVC Controllers
Exercise 5: Adding code to delete a blog entryThe 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
f 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
f 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 ActionResultEnd 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 ThenReturn 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);
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 54/449
Lab Instructions: Developing MVC Controllers 17
if (blog == null)
return RedirectToAction("Index");
return View(blog);
}
[Visual Basic]
Function Delete(ByVal id As Integer) As ActionResultDim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing ThenReturn RedirectToAction("Index")
End If
Return View(blogEntry)End Function
f 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 ActionResultEnd 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")
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 55/449
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.
f 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. Oneof the action methods accepts HTTP Gets and the other action method accepts HTTP Posts.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 56/449
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 57/449
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® as your programming language.
Objectives
After completing this lab, you will be able to:
• Create a List MVC view.
• Create a Details MVC view.
• Create a Create MVC view.
• Create an Edit MVC view.
• Create a Delete MVC view.
Introduction
In this lab, you create MVC views for listing, adding, editing, and deleting blog entries. You use strongly-
typed views, ViewData and TempData to retrieve the data from the controller. Also, you use partial views
to reuse markup that is used on multiple pages.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 58/449
Lab Instructions: Developing MVC Views 3
Lab Scenario
Based on your recommendations for redesigning the AdventureWorks website, the blog pages need to be
developed by using MVC. You have already created an ADO.NET Entity Data Model to build your MVC
model classes. You have also developed an MVC controller to handle database operations. With the
database access and application logic in place, you now need to create a set of MVC views to render the
UI based on controller actions.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 59/449
4 Lab Instructions: Developing MVC Views
Exercise 1: Develop a List MVC ViewThe main tasks for this exercise are as follows:
1. Add a Blog menu item to the Site.Master page.
2. Add a view to display the complete list of blogs.
3. Test the new view.
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 05\Starter\Exercise 01
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 01
Task 2: Add a Blog menu item to the Site.Master page
1. Open the Site.Master page.
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">
<li><%: Html.ActionLink("Home", "Index", "Home")%></li><li><%: Html.ActionLink("Blog", "", "Blog")%></li><li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>
Task 3: Add a view to display the complete list of blogs
1. Add a Blog subfolder to the Views folder.
2. Add an empty view named Index.aspx, based on the Site.Master page, to the Blog folder.
3. Update the new view to a strongly-typed view of type
System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.Blog>> or
System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog)).
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 60/449
Lab Instructions: Developing MVC Views 5
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%>
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 %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 61/449
6 Lab Instructions: Developing MVC Views
-<%: item.Title %>
</div><% Next%>
</asp:Content>
6. Build the solution, and fix any errors.
Task 4: Test the new view
1. Run the application.
2. Display the Blog view.
3. Close Internet Explorer.
4. Close Visual Studio 2010.
Results: After this exercise, you should have created a Blog menu item that opens a list MVC view
named Index, which lists all of the blog entries.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 62/449
Lab Instructions: Developing MVC Views 7
Exercise 2: Develop a Details MVC viewThe main tasks for this exercise are as follows:
• Add a strongly-typed details view named Details.
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 02
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 02
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.
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>
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)" %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 63/449
8 Lab Instructions: Developing MVC Views
<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.
5. Close Internet Explorer.
6. Close Visual Studio 2010.
Results: After this exercise, you should have created a new MVC view that shows the details about an
individual blog entry.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 64/449
Lab Instructions: Developing MVC Views 9
Exercise 3: Develop a Create MVC viewThe main tasks for this exercise are as follows:
1. Add a strongly-typed view named Blogger to list all of the blogs for a particular blogger.
2. Add a strongly-typed view named Create.
3. Use TempData to add a confirmation message to the Index view.
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: 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.
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))
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)
{ %><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 %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 65/449
10 Lab Instructions: Developing MVC Views
</div><% Next%>
<p><%: Html.ActionLink("Create New", "Create") %>
</p>
• 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))" %>
<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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 66/449
Lab Instructions: Developing MVC Views 11
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" /><% } %>
<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">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 67/449
12 Lab Instructions: Developing MVC Views
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></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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 68/449
Lab Instructions: Developing MVC Views 13
<%: Html.ActionLink("Back to List", "Blogger") %></div>
</asp:Content>
4. Run the application.
5. Navigate directly to the Blogger view by using the following route.
blog/blogger/1
6. Add a blog entry.
7. Close Internet Explorer.
Task 4: Use TempData to add a confirmation message to the Index view
1. Open the Index view.
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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 69/449
14 Lab Instructions: Developing MVC Views
<%@ 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><% 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.
5. Navigate directly to the Blogger view by using the following route.
/blog/blogger/1
6. Add another blog entry.
7. Close Internet Explorer.
8. Close Visual Studio 2010.
Results: After this exercise, you should have created two new MVC views. The first new view lists all of
the blog entries for a particular blogger and the second new view allows you to create new blog
entries.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 70/449
Lab Instructions: Developing MVC Views 15
Exercise 4: Develop an Edit MVC viewThe main tasks for this exercise are as follows:
1. Create a partial view named Blog.
2. Create an edit view named Edit, which uses the Blog partial view.
3. Edit a blog entry.
4. Update the Create view to use the Blog partial view.
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 04
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 04
Task 2: Create a partial view named Blog
1. Add an empty, strongly-typed partial view of type Blog, named Blog, to the Blog folder.
2. Copy all of the markup and code from the Content2 Content element in the Create view to the
partial Blog view.
[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" />
<% } %><div>
<%: Html.ActionLink("Back to List", "Blogger") %>
<div>
[Visual Basic]
<% Using (Html.BeginForm())%><%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend><div class="editor-label">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 71/449
16 Lab Instructions: Developing MVC Views
<%: 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 partial Blog view matches the following.
[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><input type="submit" value="Submit" />
<% } %>
<div><%: Html.ActionLink("Back to List", "Blogger") %>
</div>
[Visual Basic]
<%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(OfAdventureWorksMvc.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)%>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 72/449
Lab Instructions: Developing MVC Views 17
</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>
Task 3: Create an edit view, named Edit, that uses the Blog partial view
1. Add an empty, strongly-typed view of type Blog, named Edit, based on the Site.Master master page,
to the Blog folder.
2. Add the following markup and code to the Edit view in the Content2 Content control, immediately
after the h2 element.
[Visual C#]
<% Html.RenderPartial("Blog"); %>
[Visual Basic]
<% 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>
Task 4: Edit a blog entry
1. Run the application.
2. Navigate directly to the Blogger view by using the following route.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 73/449
18 Lab Instructions: Developing MVC Views
blog/blogger/1
3. Edit a blog entry.
4. Close Internet Explorer.
Task 5: Update the Create view to use the Blog partial view.
1. Replace the markup and code after the h2 element in the Content2 Content element in the Create view with the following.
[Visual C#]
<% Html.RenderPartial("Blog"); %>
[Visual Basic]
<% Html.RenderPartial("Blog") %>
2. 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>
<% 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">
Create
</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Create</h2><% Html.RenderPartial("Blog")%>
</asp:Content>
3. Run the application.
4. Navigate directly to the Blogger view by using the following route.
blog/blogger/1
5.
Add another blog entry.6. Close Internet Explorer.
7. Close Visual Studio 2010.
Results: After this exercise, you should have created a partial view that is used by both the Edit view
and the Create view.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 74/449
Lab Instructions: Developing MVC Views 19
Exercise 5: Develop a Delete MVC viewThe main tasks for this exercise are as follows:
1. Add a strongly-typed view named Delete that uses the default markup provided by the Add View
dialog box.
2. Delete a blog entry.
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 05
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 05
Task 2: Add a strongly-typed view named Delete that uses the default markup provided
by the Add View dialog box1. Build the solution.
2. Add a delete, strongly-typed view of type Blog, named Delete, based on the Site.Master master
page, to the Blog folder. The view should use the default content supplied for a Delete operation.
3. Update the markup and code that renders the Back to List link to match the following.
<%: Html.ActionLink("Back to List", "Blogger") %>
4. Verify that the markup and code in the Delete 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">
Delete</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Delete</h2>
<h3>
Are you sure you want to delete this?</h3><fieldset>
<legend>Fields</legend>
<div class="display-label">
BlogID</div><div class="display-field">
<%: Model.BlogID %></div>
<div class="display-label">BloggerID</div>
<div class="display-field">
<%: Model.BloggerID %></div><div class="display-label">
DatePosted</div>
<div class="display-field"><%: String.Format("{0:g}", Model.DatePosted) %></div>
<div class="display-label">
Title</div><div class="display-field">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 75/449
20 Lab Instructions: Developing MVC Views
<%: Model.Title %></div><div class="display-label">
BlogEntry</div><div class="display-field">
<%: Model.BlogEntry %></div>
</fieldset><% using (Html.BeginForm())
{ %>
<p><input type="submit" value="Delete" />
|
<%: Html.ActionLink("Back to List", "Blogger") %></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">
Delete
</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Delete</h2>
<h3>
Are you sure you want to delete this?</h3><fieldset>
<legend>Fields</legend>
<div class="display-label">BlogID</div>
<div class="display-field">
<%: Model.BlogID %></div><div class="display-label">
BloggerID</div>
<div class="display-field"><%: Model.BloggerID %></div>
<div class="display-label">
DatePosted</div><div class="display-field">
<%: String.Format("{0:g}", Model.DatePosted) %></div>
<div class="display-label">
Title</div><div class="display-field">
<%: Model.Title %></div>
<div class="display-label">BlogEntry</div>
<div class="display-field">
<%: Model.BlogEntry %></div></fieldset>
<% Using Html.BeginForm()%>
<p>
<input type="submit" value="Delete" />|
<%: Html.ActionLink("Back to List", "Blogger") %></p>
<% End Using%></asp:Content>
Task 3: Delete a blog entry
1. Run the application.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 76/449
Lab Instructions: Developing MVC Views 21
2. Navigate directly to the Blogger view by using the following route.
blog/blogger/1
3. Select a blog entry.
4. Close Internet Explorer.
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 an MVC view to delete blog entries.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 77/449
Lab Instructions: Designing for Discoverabili ty 1
Module 6
Lab Instructions: Designing for Discoverability
Contents:Exercise 1: Mapping URLs of Web Forms Pages 4
Exercise 2: Creating a Sitemap File 8
Exercise 3: Building the Application Infrastructure 9
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 78/449
2 Lab Instructions: Designing for Discoverability
Lab 6: Designing for Discoverability
Objectives
After completing this lab, you will be able to:
• Map URLs of Web Forms pages.
• Create a sitemap file.
• Build an application infrastructure.
IntroductionIn this lab, you map URLs of Web Forms pages to use ASP.NET URL mapping for listing products by
category, and details for a specific product ID. You also create a sitemap, as well as a robots.txt file with
an inclusion to the newly created sitemap file for the Default Web Site in IIS, and add navigation controls
to the application.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 79/449
Lab Instructions: Designing for Discoverabili ty 3
Lab Scenario
You are developing an application that will be used for external customers, and you want to ensure that
Search engines can find your site easily. As well, you want to use URLs that are easy for your salespeople
to send in emails.
Using the routing features of ASP.NET 4.0, you will map the URLs of a Web Forms page. You will create a
sitemap page, and complete building the application infrastructure.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 80/449
4 Lab Instructions: Designing for Discoverability
Exercise 1: Mapping URLs of Web Forms PagesThe main tasks for this exercise are as follows:
1. Add and verify reference to System.Web.Routing.
2. Edit the Global.asax file to use ASP.NET URL mapping for the page listing products by category.
3. Test the pages.
4. Add a second route to map a URL to the following product ID: http://localhost/product/1.
5. Test the 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.
3. Open the AdventureWorks solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 06\Starter\Exercise 01
Visual Basic D:\Lab Files\VB\Lab 06\Starter\Exercise 01
Task 2: Add and verify a reference to the System.Web.Routing assembly
1. Add a reference to the System.Web.Routing assembly.
2. Verify a reference to the System.Web.Routing assembly.
Task 3: Map the page listing products by category
1. Open the Global.asax file.
2. Import the System.Web.Routing namespace in the Global.asax code file.
3. Add a 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
);
}
[Visual Basic]
Private Sub RegisterRoutes(ByVal routes As RouteCollection)' Route name
' URL with parameters' Web forms page to handle itroutes.MapPageRoute("products-browse", "products/{category}", "~/Products.aspx")
End Sub
4. Modify the Application_Start method as shown.
[Visual C#]
void Application_Start(){
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 81/449
Lab Instructions: Designing for Discoverabili ty 5
RegisterRoutes(RouteTable.Routes);}
[Visual Basic]
Private Sub Application_Start()RegisterRoutes(RouteTable.Routes)
End Sub
5. Open the Products.aspx.cs or Products.aspx.vb code file.
6. Modify the Page_Load method in the Products class as shown.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
string categoryName = null;
string categoryId;
// Retrieve category param from "/Products/{Category}" URL
categoryId = Page.RouteData.Values["category"].ToString();
categoryName =
DataAccessLayer.Products.GetCategoryName(int.Parse(categoryId));lblCategory.Text = categoryName;
var data =DataAccessLayer.Products.GetProductsByCategory(int.Parse(categoryId));
gvProducts.DataSource = data;gvProducts.DataBind();
}}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack ThenDim categoryName As String = Nothing
Dim categoryId As String
' Retrieve category param from "/Products/{Category}" URL
categoryId = Page.RouteData.Values("category").ToString()
categoryName =
AdventureWorks.DataAccessLayer.Products.GetCategoryName(Integer.Parse(categoryId))
lblCategory.Text = categoryName
Dim data =AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(Integer.Parse(categoryId))
gvProducts.DataSource = data
gvProducts.DataBind()End If
End Sub
Task 4: Test the pages
1. Run the application.
2. Navigate directly to the Products page by using the following route.
products/1
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 82/449
6 Lab Instructions: Designing for Discoverability
Note: A grid should render with a single row containing products for the product category with an
ID value of 1.
3. Close Internet Explorer.
Task 5: Add a second route to map a URL to a product ID1. Open the Global.asax file.
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 itroutes.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
3. Open the ProductDetail.aspx.cs or ProductDetail.aspx.vb code file.
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} URLproductId = 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();
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 83/449
Lab Instructions: Designing for Discoverabili ty 7
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) HandlesMe.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.ColorlblSize.Text = data.Size
lblWeight.Text = data.Weight.ToString()
lblListPrice.Text = data.ListPrice.ToString()hdnProductId.Value = data.ProductID.ToString()
hdnProductName.Value = data.NamehdnListPrice.Value = data.ListPrice.ToString()
End If
End Sub
Task 6: Test the pages
1. Run the application.
2. Navigate directly to the ProductDetail page by using the following route.
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.
4. Close Visual Studio 2010.
Results: After completing this exercise, you should have added a reference to theSystem.Web.Routing assembly, and modified the Global.asax file to use ASP.NET URL mapping to listproducts by category and details for a specific product ID.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 84/449
8 Lab Instructions: Designing for Discoverability
Exercise 2: Creating a Sitemap FileThe main tasks for this exercise are as follows:
1. Create a sitemap file to list products.
2. Modify the robots.txt file to include the sitemap.
Task 1: Create a sitemap file to list products1. Open Internet Information Services (IIS) Manager as an administrator.
2. In Control Panel, click System and Security, and then click Administrative Tools.
3. Right-click Internet Information Services (IIS) Manager, and then click Run as administrator.
4. In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then press
ENTER.
5. Open the Search Engine Optimization feature.
6. 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.
Task 2: Modify the robots.txt file to include the sitemap
1. Select theDefault Web site
.
2. Open the Search Engine Optimization feature.
3. Add a new allow rule for the default website and Sitemap.xml file.
4. Close Internet Information Services (IIS) Manager.
5. Close Administrative Tools.
6. Close System and Security.
Results: After completing this exercise, you should have created a sitemap as well as a robots.txt filewith an inclusion to the newly created sitemap file for the default website in IIS.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 85/449
Lab Instructions: Designing for Discoverabili ty 9
Exercise 3: Building the Application InfrastructureThe main tasks for this exercise are as follows:
1. Add Navigation Controls to the web application.
2. Use the FindControl function to locate a control.
Task 1: Open the AdventureWorks solution in Visual Studio 20101. Open 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
Task 2: Add Navigation Controls to the web application
1. Create a Web.sitemap file in the root directory of the website.
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>
<siteMapNode url="~/About.aspx" title="About" description="About"></siteMapNode>
</siteMapNode></siteMap>
3. Save and close the Web.sitemap file.
4. Open the Site.Master master page.
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.
8. Run the application.
9. Close Internet Explorer.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 86/449
10 Lab Instructions : Designing for Discoverability
Task 3: Use the FindControl function to locate a control
1. Open the Site.Master code-behind file.
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.
4. Debug the application.
5. Single-step over the selected line of code.
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.
8. 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.G
4. In the Revert Virtual Machine dialog box, click Revert.
Results: After this exercise, you should have added navigation controls to the web application.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 87/449
Lab Instructions: Writing Server-Side Code for Web Forms 1
Module 7
Lab Instructions: Writing Server-Side Code for Web Forms
Contents:Exercise 1: Modifying a Web Forms Page to Display Localized Content 4
Exercise 2: Persisting Data on Web Forms Pages 8
Exercise 3: Utilizing View State Effectively 12
Exercise 4: Adding Validation to Web Forms Pages 15
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 88/449
2 Lab Instructions: Writing Server-Side Code for Web Forms
ab 7: riting erver-
A
• • • • I
In
di
le
c
Note: You ca
programmin
bjectives:
fter completin
Modify a
Persist use
Utilize vie
Add valida
troductio
this lab, you
ifferent resour
arn how to ut
ntrols.
n perform the
language.
g this lab, stu
eb Forms pa
data by usin
state effectiv
ion to Web F
modify a Web
ce files. You p
ilize view stat
Side C de for Web F rms
tasks in this l
ents will be a
e to display l
a variety of
ely.
rms pages.
Forms page
ersist user dat
effectively. Y
ab by using ei
ble to:
calized conte
ethods.
nd the maste
a by using co
ou also add v
ther Visual C# or Visual Basic as your
nt.
r page to disp
kies, applicat
lidation to W
lay localized c
ion state, and
eb Forms pag
ontent, locate
session state,
es, using valid
d in
and you
ation
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 89/449
Lab Instructions: r it ing Server-Side Code for Web Forms 3
T
b
la
s
T
ab Sce
improve the
e updated to
rge percenta
ould be displ
erefore, you
ario
customer exp
isplay localiz
e of online sa
ayed in either
need to edit t
erience, existi
d informatio
les, managem
English or oth
e home pag
ng Web Form
. Because pur
ent has decid
er languages
to detect the
s pages of the
chases by int
d that the m
based on a cu
default brow
AdventureW
rnational cust
ssages, units,
stomer’s lang
ser language.
rks website n
omers make
dates, and so
age preferen
eed to
p a
on,
ce.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 90/449
4 Lab Instructions: Writing Server-Side Code for Web Forms
Exercise 1: Modifying a Web Forms Page to Display Localized ContentThe main tasks for this exercise are as follows:
• Create resource files so that Default.aspx can display the page in English and• language of your choice.• Localize the Site.Master master.
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 07\Starter\Exercise 01
Visual Basic D:\Lab Files\VB\Lab 07\Starter\Exercise 01
f Task 2: Create resource files for Default.aspx
1. Analyze the markup in Default.aspx.
2. Generate local resources for Default.aspx, by using the Generate Local Resource functionalityavailable in Design view.
Note: This automatically creates the App_LocalResources folder in the root of your webapplication, if one does not already exist. The process also creates a resource file calledDefault.aspx.resx, in the App_LocalResources folder.
3. Switch back to Source view of Default.aspx.
4. Notice that both the lbCategories and btnCategory server controls have had an extra attributecalled meta:resourcekey added to the existing markup.
<asp:Button ... meta:resourcekey="btnCategoryResource1"></asp:Button><asp:ListBox ... meta:resourcekey="lbCategoriesResource1"></asp:ListBox>
Note: The values of these attributes are used to find the localized values for the properties of thelocalizable controls in the Default.aspx.resx file.
5. Notice that the Page directive at the top of the page now contains the following information.
<%@ Page ... culture="auto" meta:resourcekey="PageResource1" uiculture="auto" %>
6. Open Default.aspx.resx.
Note: In the Resource Editor, you will see a list with all the localizable properties of the localizablecontrols from the Default.aspx page.
7. Switch back to Default.aspx.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 91/449
Lab Instructions: Writing Server-Side Code for Web Forms 5
8. Notice that the text strings Welcome to AdventureWorks! and Product Categories were notmodified, and they were not added to the .resx file either. This is because they were hard-coded inthe Web Forms page.
9. Localize the hard-coded Welcome to AdventureWorks! text implicitly, by adding a Localize servercontrol within the h2 element, with the following attributes.
Attribute Value
ID lclWelcome
Text Welcome to AdventureWorks!
meta:resourcekey LocalizeResource1
10. Delete the text Welcome to AdventureWorks! from the h2 element.
Note: Make sure that you do not delete the text Welcome to AdventureWorks! from theLocalize server control.
11. Add a resource string named lclWelcomeResource1.Text to the Default.aspx.resx resource file. Thestring must have the value of Welcome to AdventureWorks!.
12. Localize the hard-coded Product Categories text explicitly, by adding a Literal server control withinthe p element, with the following attributes.
Attribute Value
ID ProductCategoriesLiteral
Text <%$ Resources: ProductCategoriesLiteral.Text %>
13. Delete the text Product Categories from the p element.
Note: Make sure that you do not delete the text Product Categories from the Literal server
control.
14. Add a resource string named ProductCategoriesLiteral.Text to the Default.aspx.resx resource file.The string must have the value of Product Categories.
15. Run the application.
16. Verify that Default.aspx Web Form looks the same as it did before you modified it.
17. Close Windows Internet Explorer.
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\Lab07\Starter\Exercise 01 or D:\Lab Files\VB\Lab 07\Starter\Exercise 01 folder.
f Task 3: Localize the Site.Master master page
1. Open the Site.Master master page.
2. Localize the hard-coded Log In text, by adding a Literal server control within the a element, with thefollowing attributes.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 92/449
6 Lab Instructions: Writing Server-Side Code for Web Forms
Attribute Value
ID LoginLiteral
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 theLoggedInTemplate element, with the following attributes.
Attribute Value
ID WelcomeLiteral
Text Welcome
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.
7. Generate local resources for Site.Master, by using the Generate Local Resource functionality.
Note: This generates a new file called Site.Master.resx in the App_LocalResources folder.
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\Lab07\Starter\Exercise 01 or D:\Lab Files\VB\Lab 07\Starter\Exercise 01 folder.
f Task 4: Test the web application
1. Run the application.
2. Show the AdventureWorks home page in German, by changing the language preference in theInternet Options dialog box.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 93/449
Lab Instructions: Writing Server-Side Code for Web Forms 7
Note: The page should now be shown in German.
3. Close Internet Explorer.
4. Close Visual Studio 2010.
Results: After this exercise, you should have a web application that supports different languages, andshows the site in the user’s preferred language.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 94/449
8 Lab Instructions: Writing Server-Side Code for Web Forms
Exercise 2: Persisting Data on Web Forms PagesThe main tasks for this exercise are as follows:
1. Use a cookie collection to persist user information, setting scope and lifetime to save the last chosencategory.
2. Store system-wide information in the Application object, to hold the number of simultaneous visitors
on the site.
3. Use the session object to store the shopping cart.
4. Configure session state to run in SQL Server.
f Task 1: Open the AdventureWorks solution in Visual Studio 2010
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the following location.
ProgrammingLanguage Location
Visual C# D:\Lab Files\CS\Lab 07\Starter\Exercise 02
Visual Basic D:\Lab Files\VB\Lab 07\Starter\Exercise 02
f 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.
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. Thecookie must be appended to the response.
[Visual C#]
else{
if (lbCategories.SelectedIndex != -1)
{
string category = lbCategories.SelectedValue;
HttpCookie cookie = new HttpCookie("Preferences");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") = categorycookie.Expires = DateTime.Now.AddMinutes(1)Response.AppendCookie(cookie)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 95/449
Lab Instructions: Writing Server-Side Code for Web Forms 9
Response.Redirect("/Products.aspx?id=" & category, True)
End IfEnd If
3. If the page is rendered for the first time, add code to check that a cookie named Preferences exists inthe request cookie collection, and if there is, read the LastCategory value from the cookie, and assignit to the SelectedValue property of the ListBox control.
[Visual C#]
if (!Page.IsPostBack){
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.GetCategorieslbCategories.DataSource = data
lbCategories.DataBind()
Dim cookie As HttpCookie = Request.Cookies("Preferences")
If Not cookie Is Nothing ThenlbCategories.SelectedValue = cookie("LastCategory")
End If
4. Build the solution, and fix any errors.
f Task 3: Store system-wide information in the Application object
1. Open Global.asax in Code view.
2. In the Application_Start method, overwrite the existing code, by adding a new application variablenamed 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") = 0End 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 theApplication object before writing, and unlocking once you have finished writing to it.
[Visual C#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 96/449
10 Lab Instructions: Writing Server-Side Code for Web Forms
void Session_Start(object sender, EventArgs e)
{Application.Lock();int visitors = (int)Application["OnlineVisitors"];visitors++;Application["OnlineVisitors"] = visitors;Application.UnLock();
}
[Visual Basic]
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)Application.Lock()Dim visitors As Integer = Integer.Parse(Application("OnlineVisitors"))visitors += 1Application("OnlineVisitors") = visitorsApplication.UnLock()
End Sub
4. In the Session_End decrement the value of the OnlineVisitors application variable by 1, if thecurrent value is not 0. Make sure you prevent multiple threads from writing to the applicationvariable, by locking the Application object before writing, and unlocking once you have finishedwriting 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 Thenvisitors -= 1Application("OnlineVisitors") = visitors
End If
Application.UnLock()End Sub
5. Build the solution, and fix any errors.
f Task 4: Use the session object to store the shopping cart
1. Open the ProductDetails Web Form in Code view.
2. Upon postback, the Order button has been pressed, so the information entered in the Web Form ispersisted. In the Page_Load method, notice how the product ID, product name, and list price, whichare not displayed to the user, are saved to hidden fields. In the btnOrder_Click event handler, noticethat a new List object of type clsShoppingCart is created and saved to Session state. Finally, the useris redirected to the ShoppingCart Web Form.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 97/449
Lab Instructions: Writing Server-Side Code for Web Forms 11
3. Open the ShoppingCart Web Form in Code view.
4. Analyze the code in the Page_Load method.
f Task 5: Configure session state to run in SQL Server
1. Open the Web.config file.
2. Configure your application to use the local SQL Server® instance named SQLExpress, for persistingsession information instead of the default InProc mode.
<system.web>...
<sessionState mode="SQLServer" sqlConnectionString="Integrated Security=SSPI;DataSource=.\SQLExpress;" /></system.web>
3. Configure the local SQL Server instance SQLExpress to host the state database, by running thefollowing command from the Visual Studio Command Prompt (2010). The Visual Studio CommandPrompt (2010) must be run as an administrator.
aspnet_regsql -E -S .\SQLExpress -ssadd
4. Open the SQL Server Command Line Tool, by running the following command from the Visual
Studio Command Prompt (2010).
sqlcmd –E –S .\SQLExpress
5. Add permissions for the user Student to access the tempdb and ASPState database to use the newSQL Server Session state, by running commands from the SQL Server Command Line Tool withinthe Visual Studio Command Prompt (2010). The commands are saved in the D:\Lab Files\CS\Lab07\Starter\Exercise 02\ASPState.txt or D:\Lab Files\VB\Lab 07\Starter\Exercise 02\ASPState.txt file, from where you can copy them and paste them into the SQL Server Command Line Tool.
6. Close the SQL Server Command Line Tool, by running the following command from the VisualStudio Command Prompt (2010).
quit
7. Close the Visual Studio Command Prompt (2010).8. Close Visual Studio 2010.
Results: After this exercise, you should have implemented state using different techniques, includingApplication and Session state.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 98/449
12 Lab Instructions: Writing Server-Side Code for Web Forms
Exercise 3: Utilizing View State EffectivelyThe main tasks for this exercise are as follows:
1. Configure the view state to persist page data.
2. Disable the view state and its effects.
f Task 1: Open the AdventureWorks solution in Visual Studio 20101. Open 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 03
Visual Basic D:\Lab Files\VB\Lab 07\Starter\Exercise 03
f Task 2: Configure view state to persist page data
1. Run the application.
2. View the source of the Default.aspx page in Internet Explorer, by using the View Source functionality.
3. Analyze the HTML code, and pay special attention to the __VIEWSTATE field.
4. Close the View Source window.
5. Close Internet Explorer.
6. Open the Default.aspx Web Form.
7. Disable view state for the lbCategories server control.
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"DataValueField="ProductCategoryID"
Height="270px" Width="186px" EnableViewState="False"
></asp:ListBox>
8. Run the application.
9. View the source of the Default.aspx page in Internet Explorer, by using the View Source functionality.
10. Analyze the HTML code, and pay special attention to the __VIEWSTATE field, which is now muchsmaller, almost half the size.
11. Close the View Source window.
12. Notice the effects of disabling view state for the lbCategories server control, by clicking Submit.
Note: The lbCategories server control is now empty because it is not being populated by theserver code on a postback.
13. Close Internet Explorer.
f Task 3: Disable view state and its effects
1. Disable view state for the Default Web Form by setting the EnableViewState property to False.
<%@ Page Title="Home Page" ... EnableViewState="False" %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 99/449
Lab Instructions: Writing Server-Side Code for Web Forms 13
2. Run the application.
3. Click Submit.
Note: The lbCategories server control is now empty because it is not being populated by theserver code on a postback.
4. Close Internet Explorer.
5. Enable view state for the lbCategories server control.
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"DataValueField="ProductCategoryID"
Height="270px" Width="186px" EnableViewState="True"
></asp:ListBox>
6. Run the application.
7. Click Submit.
Note: The lbCategories server control is now empty, even if you enabled view state for the control.This is because disabling view state for a control or page will disable the view state for all childcontrols.
8. Close Internet Explorer.
9. Remove the EnableViewState attribute and value from the Page directive.
10. Remove the EnableViewState attribute and value from the lbCategories server control.
11. Disable view state for the Default Web Form by setting the ViewStateMode property to Disabled.
<%@ Page Title="Home Page" ... ViewStateMode="Disabled" %>
12. Enable view state for the lbCategories server control by setting the ViewStateMode property to
Enabled.
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"DataValueField="ProductCategoryID"
Height="270px" Width="186px" ViewStateMode="Enabled"></asp:ListBox>
13. Run the application.
Note: The rendered page looks okay.
14. Click Submit.
Note: The lbCategories server control is still populated because view state has been enabled forthe server control.
15. Close Internet Explorer.
16. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 100/449
14 Lab Instructions: Writing Server-Side Code for Web Forms
Results: After this exercise, you should have examined and implemented the view state in different
ways.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 101/449
Lab Instructions: Writing Server-Side Code for Web Forms 15
Exercise 4: Adding Validation to Web Forms PagesThe main tasks for this exercise are as follows:
1. Add credit card fields to the check-out page.
2. Add and configure a RequiredFieldValidator control for the txtCreditCard control.
3. Add and configure a RegularExpressionValidator control for the credit card field.
f Task 1: Open the AdventureWorks solution in Visual Studio 2010
1. Open 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 04
Visual Basic D:\Lab Files\VB\Lab 07\Starter\Exercise 04
f Task 2: Add credit card fields to the check-out page
1. Open the ShoppingCart.aspx Web Form.
2. Add a TextBox server control for the credit card field and name it txtCreditCard. Place the servercontrol below the gvCart GridView server control. Add describing text, Credit card number:, infront of the server control.
<br />
Credit card number: <asp:TextBox runat="server" ID="txtCreditCard"/>
f Task 3: Add and configure a RequiredFieldValidator control for the txtCreditCard control
1. Add a RequiredFieldValidator control named CreditCardRequiredFieldValidator to theShoppingCart Web Form, and place it immediately after the txtCreditCard control.
<asp:TextBox runat="server" ID="txtCreditCard" />
<asp:RequiredFieldValidator ID="CreditCardRequiredFieldValidator" runat="server"></asp:RequiredFieldValidator>
2. Set the following properties as indicated.
a. ControlToValidate = txtCreditCard
b. ErrorMessage = Credit card number is required.
c. Text = *
<asp:RequiredFieldValidator ID="CreditCardRequiredFieldValidator" runat="server" ControlToValidate="txtCreditCard" ErrorMessage="Credit card number is required."
Text="*"></asp:RequiredFieldValidator>
f Task 4: Add and configure a RegularExpressionValidator control for the credit card field1. Add a RegularExpressionValidator control named CreditCardRegularExpressionValidator to the
ShoppingCart Web Form, and place it immediately after the CreditCardRequiredFieldValidator
control. Add a self-closing HTML br element after the RegularExpressionValidator control.
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="CreditCardRegularExpressionValidator"runat="server"></asp:RegularExpressionValidator><br />
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 102/449
16 Lab Instructions: Writing Server-Side Code for Web Forms
2. Set the following properties as indicated.
a. ControlToValidate = txtCreditCard
b. ErrorMessage = Please enter a valid credit card number.
c. Text = *
d. ValidationExpression= ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$ <asp:RegularExpressionValidator ID="CreditCardRegularExpressionValidator"runat="server"
ControlToValidate="txtCreditCard" Text="*" ErrorMessage="Please enter a validcredit card number."
ValidationExpression="^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$"></asp:RegularExpressionValidator>
3. Open the ShoppingCart Web Form in Code view.
4. Make sure that an order can be placed only if Page.IsValid is true. Add the check to the
btnPlaceOrder_Click event handler method.
[Visual C#]
protected void btnPlaceOrder_Click(object sender, EventArgs e){
if (Page.IsValid){
Session["_cart"] = null;Response.Redirect("~/ThankYou.aspx", true);
}}
[Visual Basic]
Protected Sub btnPlaceOrder_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnPlaceOrder.ClickIf Page.IsValid Then
Session("_cart") = Nothing
Response.Redirect("~/ThankYou.aspx", True)End If
End Sub
5. Run the application.
6. Select Bib-Shorts on the Product Categories list, and click Submit.
7. On the Products page, click Men's Bib-Shorts, L.
8. On the Men's Bib-Shorts, L page, click Order.
9. On the Shopping Cart page, click Place Order.
Note: Observe that an asterisk (*) is placed next to txtCreditCard server control because you have
not filled in this field.
10. On the Shopping Cart page, in the Credit card number box, type 1234123412341234 , and then
click Place Order.
Note: Observe that an asterisk (*) is placed next to txtCreditCard server control because you have
not entered a valid credit card number.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 103/449
Lab Instructions: Writing Server-Side Code for Web Forms 17
11. On the Shopping Cart page, in the Credit card number box, type 4058340022020047 , and then
click Place Order.
Note: Observe that you are redirected to the ThankYou Web Form because you have filled in a
valid credit card number.
12. Close Internet Explorer.
13. Close Visual Studio 2010.
Results: After this exercise, you should have implemented validation for the check-out page, by addingvalidation controls to the Web Form.
f Task 5: 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 104/449
Lab Instructions: Optimizing Data Management for Web Forms 1
Module 8
Lab Instructions: Optimizing Data Management for WebForms
Contents:Lab 8A: Optimizing Data Management for Web Forms
Section 1: Visual Basic
Exercise 1: Managing Data by Using LINQ to Entities 4
Exercise 2: Customizing the GridView 5
Exercise 3: Using ListView, DetailsView and Charts 10
Section 2: Visual C#
Exercise 1: Managing Data by Using LINQ to Entities 14
Exercise 2: Customizing the GridView 15
Exercise 3: Using ListView, DetailsView and Charts 21
Lab 8B: Optimizing Data Management for Web Forms
Section 1: Visual Basic
Exercise 4:
Managing Data by Using ASP.NET Dynamic Data 27Section 2: Visual C#
Exercise 4: Managing Data by Using ASP.NET Dynamic Data 29
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 105/449
2 Lab Instructions: Optimi ing Data Managem nt for Web Forms
ab 8A: Optimizing D
A
• • • • I
In
s
Note: You ca
language. If
the Section
to the steps
bjectives
fter completin
Manage da
Display dat
Display par
Display das
troductio
this lab, you
urce controls
n perform tas
ou are using
of the lab do
rovided in Se
g this lab, yo
ta by using th
a using the gr
ent and child
hboard infor
will develop t
.
ta Ma agem nt for eb F
ks in this lab e
isual Basic as
cument. If yo
tion 2 of the
will be able t
e LinqDataS
id control.
data in the lis
ation using t
e administrat
ither by using
your progra
are using Vi
lab documen
o:
urce control.
and detail co
e chart contr
ion section of
Visual Basic
ming langua
ual C# as you
t.
ntrols.
ol.
the website b
r Visual C# pr
e, refer to th
r programmin
y using variou
rms
ogramming
steps provid
g language, r
d in
fer
s ASP.NET data
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 106/449
La Ins tructions: Opt imizing Data Manage ent for Web Forms 3
T
t
t
f
• • • • In
s
ab Sce
e Adventure
at they can
ward this end
llowing:
View, add,
View sales
View and e
Display sal
this lab, you
urce controls
ario
orks Sales te
anage inform
, you need to
am has reque
ation, as well
create a set o
sted the addit
s provide a d
web form pa
ion of an adm
ashboard to s
ges that will
inistration sec
enior manage
nable the Sal
tion to the we
ment. As a firs
s team to do
bsite so
t step
the
edit, and dele e products
orders
dit customer etails
s information in a graphical format (dashboard)
will develop t
.
e administration section of the website by using various ASP.NET data
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 107/449
4 Lab Instructions: Optimizing Data Management for Web Forms
Section 1: Visual Basic
Exercise 1: Managing Data by Using LINQ to EntitiesThe main tasks in this exercise are as follows:
• Create a new Entity Framework data model.
f 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\VB\Lab 08\Starter\Exercise 01 folder.
f Task 2: Create a new Entity Framework data model
1. Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx. The data model
should be generated from a database, by using the AdventureWorksLT2008 connection string from
the Web.config file. All tables from the database, with the exception of the BuildVersion table,
should be added to the data model.
2. Save and close the ADO.NET Entity Data Model item.
3. Build the project and fix any errors.
4. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 108/449
Lab Instructions: Optimizing Data Management for Web Forms 5
Exercise 2: Customizing the GridViewThe main tasks in this exercise are as follows:
1. Create a Shopping Cart Quantity user control.
2. Modify the ShoppingCart entity class.
3. Convert a BoundField column to TemplateField.
4. Add Computed column to the GridView control.
5. Make GridView updatable.
6. Add user control to TemplateField
7. Implement GridView paging.
8. Test the GridView control.
f Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the the D:\Lab Files\VB\Lab 08\Starter\Exercise 02
folder.
f Task 2: Create a Shopping Cart Quantity user control
1. Create a new user control named Quantity.ascx.
2. Add a TextBox control named QuantityTextBox to the user control.
<asp:TextBox ID="QuantityTextBox" runat="server"></asp:TextBox>
3. Add a RequiredFieldValidator control named QuantityRequiredFieldValidator to the user control.
The RequiredFieldValidator control must validate the QuantityTextBox control, and display thetext “You must fill in the Quantity.” as the error message, if the user leaves the text box empty. The
display mode must be dynamic.
<asp:RequiredFieldValidator ID="QuantityRequiredFieldValidator" runat="server"ErrorMessage="You must fill in the Quantity." ControlToValidate="QuantityTextBox"
Display="Dynamic"></asp:RequiredFieldValidator>
4. Add a public property named Text to the user control. The property must be of type String, and get
and set the Text property of the QuantityTextBox control.
Public Property Text As String
GetReturn QuantityTextBox.Text
End Get
Set(ByVal value As String)QuantityTextBox.Text = value
End Set
End Property
5. Save and close the user control.
6. Build the project and fix any errors.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 109/449
6 Lab Instructions: Optimizing Data Management for Web Forms
Note: Observe the “Build succeeded” message in the Build pane of the Output window.
f Task 3: Modify the ShoppingCart entity class
1. Open the ShoppingCart.vb class file.
2. Add a private member variable named productQuantity of type Integer to the ShoppingCart class.
Private productQuantity As Integer
3. Modify the auto-implemented Quantity property, to get and set the productQuantity member
variable.
Public Property Quantity As IntegerGet
Return productQuantity
End Get
SetproductQuantity = value
End Set
End Property
4. Add an auto-implemented TotalPrice property, of type Decimal.
Public Property TotalPrice As Decimal
5. Update the TotalPrice property, when the Quantity property is set.
TotalPrice = productQuantity * ListPrice
6. Save and close the ShoppingCart entity class.
7. Build the project and fix any errors.
f Task 4: Convert a BoundField column to TemplateField
1. Open the ShoppingCart.aspx content page in Design view.
2. Select the gvCart GridView control.
3. Open the Fields dialog box for the GridView control, by using the Smart Tag.
4. Convert the Quantity field to a template field.
f Task 5: Add Computed column to GridView control
1. Append a new template field with a HeaderText property value of Total Price and close the Fields
dialog box.
2. Open the ShoppingCart.aspx content page in Source view.
Note: Observe how the Quantity field/column has been converted into a TemplateField, and the
newly added Total Price TemplateField.
f Task 6: Make GridView updatable
• Open the ShoppingCart.aspx content page in Design view.
a. Select the gvCart GridView control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 110/449
Lab Instructions: Optimizing Data Management for Web Forms 7
b. Set the AutoGenerateEditButton property to a value of True.
c. Add an event handler for the RowCancelingEdit event.
d. Add an event handler for the RowEditing event.
e. Add an event handler for the RowUpdating event.
f. Make the existing code in the Page_Load event handler execute only on first request bywrapping the existing code in the Page_Load event handler in an If statement.
If Not IsPostBack ThenEnd If
g. Add a new Sub/void method named BindData to the ShoppingCart1 class.
Private Sub BindData()Dim cart As List(Of ShoppingCart) = CType(Session("_cart"), List(Of
ShoppingCart))
gvCart.DataSource = cart
gvCart.DataBind()End Sub
h. Add code to the gvCart_RowEditing method, for setting the edit index and bind the data by
using the BindData method.Protected Sub gvCart_RowEditing(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvCart.RowEditing
' Set edit indexgvCart.EditIndex = e.NewEditIndex
' Bind data
BindData()End Sub
i. Add code to the gvCart_RowCancelingEdit method, for resetting the edit index and bind the
data by using the BindData method.
Protected Sub gvCart_RowCancelingEdit(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles
gvCart.RowCancelingEdit
' Reset edit indexgvCart.EditIndex = -1
' Bind data
BindData()End Sub
j. Add code to the gvCart_RowUpdating method, for retrieving the existing cart from Session.
' Retrieve existing cart from sessionDim cart As List(Of ShoppingCart) = CType(Session("_cart"), List(Of ShoppingCart))
k. Append code to the gvCart_RowUpdating method, for retrieving the current row from the
GridView control.
' Get current rowDim row As GridViewRow = gvCart.Rows(e.RowIndex)
l. Append code to the gvCart_RowUpdating method, for finding the matching row in the storedcart, stored in a new variable named cartToEdit of type ShoppingCart. Use the generic List Find
method with an anonymous Lambda expression.
' Find matching row in stored cartDim cartToEdit As ShoppingCart = cart.Find(Function(cartToFind) cartToFind.ProductId
= Integer.Parse(row.Cells(1).Text))
m. Append code to the gvCart_RowUpdating method, for updating the quantity value of the
cartToEdit shopping cart with the value of the Text property of the Quantity user control, located
in the current row of the GridView control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 111/449
8 Lab Instructions: Optimizing Data Management for Web Forms
Dim qty As Quantity = CType(gvCart.Rows(e.RowIndex).FindControl("Quantity1"),
Quantity)cartToEdit.Quantity = Integer.Parse(qty.Text)
n. Append code to the gvCart_RowUpdating method, to save the updated cart to Session state.
' Save updated cart to session
Session("_cart") = cart
o. Append code to the gvCart_RowUpdating method, for resetting the edit index and bind the
data by using the BindData method.
' Reset edit index
gvCart.EditIndex = -1
' Bind dataBindData()
p. Save and close the ShoppingCart code-behind file.
q. Build the project and fix any errors.
f Task 7: Add user control to TemplateField
• Add the user control to the Shopping Cart Web Form.
Note: Observe how the Quantity user control has been registered using the Register directive, and the
user control has been added to the Web Form.
a. Move the markup for the Quantity user control to the top of the EditItemTemplate element.
<EditItemTemplate><uc1:Quantity ID="Quantity1" runat="server" />
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Quantity")
%>'></asp:TextBox>
</EditItemTemplate>
b. Copy the Text attribute and value from the TextBox1 control to the Quantity1 control.
<uc1:Quantity ID="Quantity1" runat="server" Text='<%# Bind("Quantity") %>' />
c. Delete the TextBox1 control.
d. Make the ProductId BoundField control read-only.
e. Format the display of the ListPrice BoundField control using the DataFormatString attribute
and a value of {0:c}.
f. Modify the format of the TemplateField control with a HeaderText attribute value of TotalPrice, to appear as follows.
<asp:TemplateField HeaderText="Total Price"><ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("TotalPrice") %>'
DataFormatString="{0:c}"></asp:Label>
</ItemTemplate></asp:TemplateField>
f Task 8: Implement GridView paging
• Set the AllowPaging property to true for GridView control.
a. Set the PageSize property to 1 for GridView control.
b. Add an event handler for the PageIndexChanging event.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 112/449
Lab Instructions: Optimizing Data Management for Web Forms 9
c. Add code to prevent page index to change, when in edit mode, and display an appropriate error
message in the lblMessage Label control, by using the following code.
' Cancel paging operation if user attempts to navigate
' to another page while in edit modeIf CType(sender, GridView).EditIndex <> -1 Then
' Cancel paging operation
e.Cancel = True
' Display error message
Dim newPageIndex As Integer = e.NewPageIndex + 1lblMessage.Text = "Update the item before moving to page " &
newPageIndex.ToString()
Else' Clear message text
lblMessage.Text = ""
' Set page indexCType(sender, GridView).PageIndex = e.NewPageIndex
BindData()
End If
d. Save and close the ShoppingCart files.
e.
Build the project and fix any errors.
f Task 9: Test the GridView control
• Run the application.
a. On the Home page, in the Product Categories list, click Bike Stands, and then click Submit.
b. On the Products page, in the Bike Stands list, click All-Purpose Bike Stand.
c. On the Product Detail page, click Order.
d. On the Shopping Cart page, click Edit.
e. In the Quantity box, type 5, and then click Update.
Note: Observe how the Quantity and Total Price columns are updated.
f. On the Shopping Cart page, click Continue Shopping.
g. On the Home page, in the Product Categories list, click Cranksets, and then click Submit.
h. On the Products page, in the Cranksets list, click HL Crankset.
i. On the Product Detail page, click Order.
Note: Observe that the customized pager has been added to the GridView, now that more items than
the specified page size have been added to the GridView.
j. On the Shopping Cart page, in the GridView pager, click 2.
k. Close Windows® Internet Explorer®.
l. Close Visual Studio 2010.
Note: The page index is changed and the content updated appropriately.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 113/449
10 Lab Instructions: Optimizing Data Management for Web Forms
Exercise 3: Using ListView, DetailsView and ChartsThe main tasks in this exercise are as follows:
1. Create the Sales Orders Master Details view.
2. Test the Master Details view.
3. Create the Sales Order Items History dashboard.
4. Test the Master Details view.
f Task 1: Open an existing ASP.NET web application
• Open Microsoft Visual Studio 2010.
a. Open the AdventureWorks solution from the D:\Lab Files\VB\Lab 08\Starter\Exercise 03
folder.
f Task 2: Create the Sales Orders Master Details view
• Build the project.
a. Open the SalesOrders.aspx content page in Design view.
b. Place the cursor in the HTML p element at the bottom of the MainContent Content control.
c. Add a ListView control named SalesOrdersListView to the p element.
d. Add a new LinqDataSource control, by using the SalesOrdersListView Smart Tag.
e. Use LINQ as the data source, and name the LinqDataSource control
SalesOrdersLinqDataSource, by using the Data Source Configuration Wizard.
f. Select the AdventureWorks.AdventureWorks2008LTEntities object context using the existing
Entity Data Model as the object context for the LinqDataSource control.
g. Select the SalesOrderHeaders table and include the SalesOrderID, OrderDate, DueDate,
ShipDate and CustomerID fields for the LinqDataSource control.
h. Select only sales orders that have already shipped, by specifying a where clause, and compare
ShipDate with the DateTime.Now method.
i. Order the sales orders by CustomerID and ShipDate, by specifying an Order By clause.
j. Finish the Data Source Configuration Wizard.
k. Set the SalesOrderID field as the DataKeyNames property value.
l. Open the SalesOrders.aspx web form in Source view.
m. Remove the WhereParameters element from the LinqDataSource control.
<WhereParameters><asp:Parameter DefaultValue="DateTime.Now" Name="ShipDate" Type="DateTime" />
</WhereParameters>
n. Modify the Where property to appear as follows.
Where="ShipDate <= DateTime.Now"
o. Open the SalesOrders.aspx web form in Design view.
p. Configure the SalesOrdersListView control, by using the SalesOrdersListView Smart Tag.
Refresh the schema before configuring the control.
q. Select the Grid layout and the Professional style for the SalesOrdersListView control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 114/449
Lab Instructions: Optimizing Data Management for Web Forms 11
r. Enable paging for the SalesOrdersListView control.
s. Disable editing and inserting a SalesOrderHeader item in the SalesOrdersListView control, by
deleting the corresponding templates in Source view.
t. Add a Select button to the AlternatingItemTemplate and ItemTemplate elements. Use the
Button server control and place it at the top of the HTML tr element.
<td><asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select"
/>
</td>
u. Add an empty HTML th element to the LayoutTemplate element. Make the th element a server
control and place it at the top of the HTML tr element.
<th runat="server"></th>
v. Add an empty HTML td element to the SelectedItemTemplate element. Place it at the top of
the HTML tr element.
<td>
</td>
w. Add an empty HTML p element below the existing p element.
<p>
</p>
x. Add a new LinqDataSource control with the following markup, within the empty HTML p
element.
<asp:LinqDataSource ID="SalesOrderDetailsLinqDataSource" runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"
EntityTypeName="" TableName="SalesOrderDetails" Where="SalesOrderID ==
@SalesOrderID"><WhereParameters>
<asp:ControlParameter ControlID="SalesOrdersListView" Name="SalesOrderID"
PropertyName="SelectedValue"
Type="Int32" DefaultValue="0" /></WhereParameters>
</asp:LinqDataSource>
y. Add a DetailsView control with the following markup, at the top of the new HTML p element.
<asp:DetailsView ID="SalesOrderDetailDetailsView" runat="server"
DataSourceID="SalesOrderDetailsLinqDataSource"
Height="50px" Width="125px" AutoGenerateRows="False"><Fields>
<asp:BoundField DataField="SalesOrderDetailID"
HeaderText="SalesOrderDetailID" SortExpression="SalesOrderDetailID" /><asp:BoundField DataField="OrderQty" HeaderText="OrderQty"
SortExpression="OrderQty" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID"SortExpression="ProductID" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitPriceDiscount" HeaderText="UnitPriceDiscount"
SortExpression="UnitPriceDiscount" />
<asp:BoundField DataField="LineTotal" HeaderText="LineTotal"SortExpression="LineTotal" />
<asp:BoundField DataField="rowguid" HeaderText="rowguid"
SortExpression="rowguid" /><asp:BoundField DataField="ModifiedDate" HeaderText="ModifiedDate"
SortExpression="ModifiedDate" />
</Fields>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 115/449
12 Lab Instructions: Optimizing Data Management for Web Forms
</asp:DetailsView>
f Task 3: Test the Master Details view
• Run the application.
a. On the Sales Orders page, click Select for any item in the ListView control.
b. The DetailsView containing the Sales Order Details is displayed below the ListView control.
c. Close Windows® Internet Explorer®.
f Task 4: Create the Sales Order Items History dashboard
• Open the SalesOrderItemsHistory.aspx content page in Source view.
a. Add an EntityDataSource control named SalesOrderItemsEntityDataSource to the
MainContent Content control.
<asp:EntityDataSource ID="SalesOrderItemsEntityDataSource" runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"
CommandText="SELECT Headers.SalesOrderNumber, Headers.OrderDate,SUM(Details.OrderQty) AS SalesOrderItems FROM SalesOrderHeaders AS Headers INNER JOIN
SalesOrderDetails AS Details ON Headers.SalesOrderID = Details.SalesOrderID
GROUP BY Headers.SalesOrderID, Headers.SalesOrderNumber, Headers.OrderDate"ConnectionString="name=AdventureWorksLT2008Entities"
DefaultContainerName="AdventureWorksLT2008Entities"
EnableFlattening="False">
</asp:EntityDataSource>
b. Open the SalesOrderItemsHistory.aspx content page in Design view.
c. Add a Chart control named SalesOrderItemsHistoryChart.
d. Set the Chart type to Bar by using the Smart Tag.
e. Use the SalesOrderItemsEntityDataSource control as the data source, by using the
DataSourceID property, the X values should come from the SalesOrderItems field, the Y values
should come from the OrderDate field. Refresh the schema, after selecting the data source
control.f. Modify the default chart area, by setting the X and Y axis titles to # Sales Order Items and Order
Date. Use the ChartArea Collection Editor, accessible from the Properties window.
f Task 5: Test the Master Details view
• Run the application.
Note: Observe how the Chart shows how the number of items per order are shown by order date.
a. Close Internet Explorer.
b.
Close Visual Studio 2010.
f Task 6: Turn off the virtual machine and revert the changes
• In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off .
a. In the Turn Off Machine dialog box, click Turn Off .
b. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then
click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 116/449
Lab Instructions: Optimizing Data Management for Web Forms 13
c. In the Revert Virtual Machine dialog box, click Revert.
Note: The answers to the exercises are on the Course Companion CD.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 117/449
14 Lab Instructions: Optimizing Data Management for Web Forms
Section 2: Visual C#
Exercise 1: Managing Data by Using LINQ to EntitiesThe main tasks in this exercise are as follows:
• Create a new Entity Framework Data Model.
f Task 1: Open an existing ASP.NET web application
• Open Microsoft Visual Studio 2010.
• Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 08\Starter\Exercise 01
folder.
f Task 2: Create a new Entity Framework Data model
• Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx. The data model
should be generated from a database, by using the AdventureWorksLT2008 connection string from
the Web.config file. All tables from the database, with the exception of the BuildVersion table,
should be added to the data model.
a. Close the ADO.NET Entity Data Model item.
b. Build the project and fix any errors.
c. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 118/449
Lab Instructions: Optimizing Data Management for Web Forms 15
Exercise 2: Customizing the GridViewThe main tasks in this exercise are as follows:
1. Create a Shopping Cart Quantity user control.
2. Modify the ShoppingCart entity class.
3. Convert a BoundField column to TemplateField.
4. Add Computed Column to the GridView control.
5. Make GridView updatable.
6. Add user control to TemplateField.
7. Implement GridView paging.
8. Test the GridView control.
f Task 1: Open an existing ASP.NET web application
• Open Microsoft Visual Studio 2010.• Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 08\Starter\Exercise 02
folder.
f Task 2: Create a Shopping Cart Quantity user control
• Create a new user control named Quantity.ascx.
a. Add a TextBox control named QuantityTextBox to the user control.
<asp:TextBox ID="QuantityTextBox" runat="server"></asp:TextBox>
b. Add a RequiredFieldValidator control named QuantityRequiredFieldValidator to the user
control. The RequiredFieldValidator control must validate the QuantityTextBox control, and
display the text “You must fill in the Quantity.” as the error message, if the user leaves the text
box empty. The display mode must be dynamic.
<asp:RequiredFieldValidator ID="QuantityRequiredFieldValidator" runat="server"
ErrorMessage="You must fill in the Quantity." ControlToValidate="QuantityTextBox"Display="Dynamic"></asp:RequiredFieldValidator>
c. Add a public property named Text to the user control. The property must be of type string, and
get and set the Text property of the QuantityTextBox control.
public string Text{
get
{return QuantityTextBox.Text;
}
set
{QuantityTextBox.Text = value;
}
}
d. Save and close the user control.
e. Build the project and fix any errors.
Note: Observe the Build succeeded message in the Build pane of the Output window.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 119/449
16 Lab Instructions: Optimizing Data Management for Web Forms
f Task 3: Modify ShoppingCart Entity class
• Open the ShoppingCart.cs class file.
a. Add a private member variable named productQuantity of type int to the ShoppingCart class.
private int productQuantity;
b.
Modify the auto-implemented Quantity property, to get and set the productQuantity membervariable.
public int Quantity
{
get{
return productQuantity;
}set
{
productQuantity = value;}
}
c. Add an auto-implemented TotalPrice property, of type decimal.
public decimal TotalPrice { get; set; }
d. Update the TotalPrice property, when the Quantity property is set.
TotalPrice = productQuantity * ListPrice;
e. Save and close the ShoppingCart entity class.
f. Build the project and fix any errors.
f Task 4: Convert a BoundField column to TemplateField
• Open the ShoppingCart.aspx content page in Design view.
a. Select the gvCart GridView control.
b. Open the Fields dialog box for the GridView control, by using the Smart Tag.
c. Convert the Quantity field to a template field.
f Task 5: Add Computed column to GridView control
1 Append a new template field with a HeaderText property value of Total Price and close the Fields
dialog box.
2 Open the ShoppingCart.aspx content page in Source view.
Note: Observe how the Quantity field/column has been converted into a TemplateField, and the
newly added Total Price TemplateField.
f Task 6: Make GridView updatable
• Open the ShoppingCart.aspx content page in Design view.
a. Select the gvCart GridView control.
b. Set the AutoGenerateEditButton property to a value of True.
c. Add an event handler for the RowCancelingEdit event.
d. Add an event handler for the RowEditing event.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 120/449
Lab Instructions: Optimizing Data Management for Web Forms 17
e. Add an event handler for the RowUpdating event.
f. Make the existing code in the Page_Load event handler execute only on first request by
wrapping the existing code in the Page_Load event handler in an if statement.
if (!IsPostBack){
}
g. Add a new void method named BindData to the ShoppingCart class.
private void BindData(){
List<ShoppingCart> cart = (List<ShoppingCart>) Session["_cart"];
gvCart.DataSource = cart;gvCart.DataBind();
}
h. Add code to the gvCart_RowEditing method, for setting the edit index and bind the data by
using the BindData method.
protected void gvCart_RowEditing(object sender, GridViewEditEventArgs e)
{// Set edit index
gvCart.EditIndex = e.NewEditIndex;// Bind dataBindData();
}
i. Add code to the gvCart_RowCancelingEdit method, for resetting the edit index and bind the
data by using the BindData method.
protected void gvCart_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{// Reset edit index
gvCart.EditIndex = -1;
// Bind data
BindData();}
j. Add code to the gvCart_RowUpdating method, for retrieving the existing cart from Session.
// Retrieve existing cart from session
List<ShoppingCart> cart = (List<ShoppingCart>) Session["_cart"];
k. Append code to the gvCart_RowUpdating method, for retrieving the current row from the
GridView control.
// Get current rowGridViewRow row = gvCart.Rows[e.RowIndex];
l. Append code to the gvCart_RowUpdating method, for finding the matching row in the stored
cart, stored in a new variable named cartToEdit of type ShoppingCart. Use the generic List Find
method with an anonymous Lambda expression.
// Find matching row in stored cart
ShoppingCart cartToEdit = cart.Find((cartToFind) => cartToFind.ProductId ==int.Parse(row.Cells[1].Text));
m. Append code to the gvCart_RowUpdating method, for updating the quantity value of the
cartToEdit shopping cart with the value of the Text property of the Quantity user control,
located in the current row of the GridView control.
// Update values
Quantity qty = gvCart.Rows[e.RowIndex].FindControl("Quantity1") as Quantity;
cartToEdit.Quantity = int.Parse(qty.Text);
n. Append code to the gvCart_RowUpdating method, for saving the updated cart to Session state.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 121/449
18 Lab Instructions: Optimizing Data Management for Web Forms
// Save updated cart to session
Session["_cart"] = cart;
o. Append code to the gvCart_RowUpdating method, for resetting the edit index and bind the
data by using the BindData method.
// Reset edit index
gvCart.EditIndex = -1;
// Bind dataBindData();
p. Save and close the ShoppingCart code-behind file.
q. Build the project and fix any errors.
f Task 7: Add User control to TemplateField
• Add the user control to the Shopping Cart web form.
a. Open the ShoppingCart.aspx content page in Source view.
Note: Observe how the Quantity user control has been registered using the Register directive, and
the user control has been added to the web form.
b. Move the markup for the Quantity user control to the top of the EditItemTemplate element.
<EditItemTemplate>
<uc1:Quantity ID="Quantity1" runat="server" /> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Quantity")
%>'></asp:TextBox>
</EditItemTemplate>
c. Copy the Text attribute and value from the TextBox1 control to the Quantity1 control.
<uc1:Quantity ID="Quantity1" runat="server" Text='<%# Bind("Quantity") %>' />
d. Delete the TextBox1 control.
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Quantity")%>'></asp:TextBox>
e. Make the ProductId BoundField control read-only.
ReadOnly="true"
f. Format the display of the ListPrice BoundField control using the DataFormatString attribute
and a value of {0:c}.
DataFormatString="{0:c}"
g. Modify the format of the TemplateField control with a HeaderText attribute value of TotalPrice, to appear as follows.
<asp:TemplateField HeaderText="Total Price">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("TotalPrice") %>'DataFormatString="{0:c}"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
f Task 8: Implement GridView paging
• Set the AllowPaging property to true for GridView control.
a. Set the PageSize property to 1 for GridView control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 122/449
Lab Instructions: Optimizing Data Management for Web Forms 19
b. Add an event handler for the PageIndexChanging event.
c. Add code to prevent page index to change, when in edit mode, and display an appropriate error
message in the lblMessage Label control, by using the following code.
// Cancel paging operation if user attempts to navigate// to another page while in edit mode
if (((GridView) sender).EditIndex != -1)
{// Cancel paging operation
e.Cancel = true;
// Display error messageint newPageIndex = e.NewPageIndex + 1;
lblMessage.Text = "Update the item before moving to page " +
newPageIndex.ToString();}
else
{// Clear message text
lblMessage.Text = "";
// Set page index((GridView) sender).PageIndex = e.NewPageIndex;
BindData();}
d. Save and close the ShoppingCart files.
e. Build the project and fix any errors.
f Task 9: Test GridView control
• Run the application.
a. On the Home page, in the Product Categories list, click Bike Stands, and then click Submit.
b. On the Products page, in the Bike Stands list, click All-Purpose Bike Stand.
c. On the Product Detail page, click Order.
d. On the Shopping Cart page, click Edit.
e. In the Quantity box, type 5, and then click Update.
Note: Observe how the Quantity and Total Price columns are updated.
f. On the Shopping Cart page, click Continue Shopping.
g. On the Home page, in the Product Categories list, click Cranksets, and then click Submit.
h. On the Products page, in the Cranksets list, click HL Crankset.
i. On the Product Detail page, click Order.
Note: Observe that the customized pager has been added to the GridView, now that more items
than the specified page size has been added to the GridView.
j. On the Shopping Cart page, in the GridView pager, click 2.
Note: Observe that the page index is changed and the content updated appropriately.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 123/449
20 Lab Instructions: Optimizing Data Management for Web Forms
k. Close Windows® Internet Explorer®.
l. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 124/449
Lab Instructions: Optimizing Data Management for Web Forms 21
Exercise 3: Using ListView, DetailsView and ChartsThe main tasks in this exercise are as follows:
1. Create the Sales Orders Master Details view.
2. Test the Master Details view.
3. Create the Sales Order Items History dashboard.
4. Test the Master Details view.
f Task 1: Open an existing ASP.NET web application
• Open Microsoft Visual Studio 2010.
• Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 08\Starter\Exercise 03
folder.
f Task 2: Create the Sales Orders Master Details view
• Build the project.
a. Open the SalesOrders.aspx content page in Design view.
b. Select the HTML p element at the bottom of the MainContent Content control.
c. Add a ListView control named SalesOrdersListView to the p element.
d. Add a new LinqDataSource control, by using the SalesOrdersListView Smart Tag.
e. Use LINQ as the data source, and name the LinqDataSource control
SalesOrdersLinqDataSource, by using the Data Source Configuration Wizard.
f. Select the AdventureWorks.AdventureWorksLT2008Entities object context from the existing
Entity Data Model as the object context for the LinqDataSource control.
g. Select the SalesOrderHeaders table and include the SalesOrderID, OrderDate, DueDate,
ShipDate and CustomerID fields for the LinqDataSource control.
h. Select only sales orders that have already shipped, by specifying a where clause, and compare
ShipDate with the DateTime.Now method.
i. Order the sales orders by CustomerID and ShipDate, by specifying an Order By clause.
j. Finish the Data Source Configuration Wizard.
k. Set the SalesOrderID field as the DataKeyNames property value.
l. Open the SalesOrders.aspx web form in Source view.
m. Remove the WhereParameters element from the LinqDataSource control.
<WhereParameters><asp:Parameter DefaultValue="DateTime.Now" Name="ShipDate" Type="DateTime" />
</WhereParameters>
n. Modify the Where property to appear as follows.
Where="ShipDate <= DateTime.Now"
o. Open the SalesOrders.aspx web form in Design view.
p. Configure the SalesOrdersListView control, by using the SalesOrdersListView Smart Tag.
Refresh the schema before configuring the control.
q. Select the Grid layout and the Professional style for the SalesOrdersListView control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 125/449
22 Lab Instructions: Optimizing Data Management for Web Forms
r. Enable paging for the SalesOrdersListView control.
s. Disable editing and inserting a SalesOrderHeader item in the SalesOrdersListView control, by
deleting the corresponding templates.
t. Add a Select button to the AlternatingItemTemplate and ItemTemplate elements. Use the
Button server control and place it at the top of the HTML tr element.
<td><asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select"
/>
</td>
u. Add an empty HTML th element to the LayoutTemplate element. Make the th element a server
control and place it at the top of the HTML tr element.
<th runat="server"></th>
v. Add an empty HTML td element to the SelectedItemTemplate element. Place it at the top of
the HTML tr element.
<td>
</td>
w. Add an empty HTML p element below the existing p element.
<p>
</p>
x. Add a new LinqDataSource control with the following markup, within the empty HTML p
element.
<asp:LinqDataSource ID="SalesOrderDetailsLinqDataSource" runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"
EntityTypeName="" TableName="SalesOrderDetails" Where="SalesOrderID ==
@SalesOrderID"><WhereParameters>
<asp:ControlParameter ControlID="SalesOrdersListView" Name="SalesOrderID"
PropertyName="SelectedValue"
Type="Int32" DefaultValue="0" /></WhereParameters>
</asp:LinqDataSource>
y. Add a DetailsView control with the following markup, at the top of the new HTML p element.
<asp:DetailsView ID="SalesOrderDetailDetailsView" runat="server"
DataSourceID="SalesOrderDetailsLinqDataSource"
Height="50px" Width="125px" AutoGenerateRows="False"><Fields>
<asp:BoundField DataField="SalesOrderDetailID"
HeaderText="SalesOrderDetailID" SortExpression="SalesOrderDetailID" /><asp:BoundField DataField="OrderQty" HeaderText="OrderQty"
SortExpression="OrderQty" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID"SortExpression="ProductID" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitPriceDiscount" HeaderText="UnitPriceDiscount"
SortExpression="UnitPriceDiscount" />
<asp:BoundField DataField="LineTotal" HeaderText="LineTotal"SortExpression="LineTotal" />
<asp:BoundField DataField="rowguid" HeaderText="rowguid"
SortExpression="rowguid" /><asp:BoundField DataField="ModifiedDate" HeaderText="ModifiedDate"
SortExpression="ModifiedDate" />
</Fields>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 126/449
Lab Instructions: Optimizing Data Management for Web Forms 23
</asp:DetailsView>
f Task 3: Test the Master Details view
• Run the application.
a. On the Shopping Cart page, click Select, for any item in the ListView control.
b. The DetailsView containing the Sales Order Details is displayed below the ListView control.
c. Close Windows® Internet Explorer®.
f Task 4: Create the Sales Order Items History dashboard
• Open the SalesOrderItemsHistory.aspx content page in Source view.
a. Add an EntityDataSource control named SalesOrderItemsEntityDataSource to the
MainContent Content control.
<asp:EntityDataSource ID="SalesOrderItemsEntityDataSource" runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"
CommandText="SELECT Headers.SalesOrderNumber, Headers.OrderDate,SUM(Details.OrderQty) AS SalesOrderItems FROM SalesOrderHeaders AS Headers INNER JOIN
SalesOrderDetails AS Details ON Headers.SalesOrderID = Details.SalesOrderID
GROUP BY Headers.SalesOrderID, Headers.SalesOrderNumber, Headers.OrderDate"ConnectionString="name=AdventureWorksLT2008Entities"
DefaultContainerName="AdventureWorksLT2008Entities"
EnableFlattening="False">
</asp:EntityDataSource>
b. Open the SalesOrderItemsHistory.aspx content page in Design view.
c. Add a Chart control named SalesOrderItemsHistoryChart.
d. Set the Chart type to Bar by using the Smart Tag.
e. Use the SalesOrderItemsEntityDataSource control as the data source, by using the
DataSourceID property, the X values should come from the SalesOrderItems field, the Y values
should come from the OrderDate field. Refresh the schema, after selecting the data source
control.f. Modify the default chart area, by setting the X and Y axis titles to # Sales Order Items and Order
Date. Use the ChartArea Collection Editor, accessible from the Properties window.
f Task 5: Test the Master Details view
• Run the application.
Note: Observe how the Chart shows how the number of items per order are shown by order date.
a. Close Internet Explorer.
b.
Close Visual Studio 2010.
f Task 6: Turn off the virtual machine and revert the changes
• In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off .
a. In the Turn Off Machine dialog box, click Turn Off .
b. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then
click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 127/449
24 Lab Instructions: Optimizing Data Management for Web Forms
c. In the Revert Virtual Machine dialog box, click Revert.
Note: The answers to the exercises are on the Course Companion CD.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 128/449
La Ins tructions: Opt imizing Data Manage ent for Web Forms 25
A
• I
In
s
ab 8B:
Note: You ca
language. If
the Section
to the steps
bjectivesfter completin
Manage da
troductio
this lab, you
urce controls
Optimi ing D ta Ma agem nt for eb Forms
n perform tas
ou are using
of the lab do
rovided in Se
ks in this lab e
isual Basic as
cument. If yo
tion 2 of the
ither by using
your progra
are using Vi
lab documen
Visual Basic
ming langua
ual C# as you
t.
r Visual C# pr
e, refer to th
r programmin
ogramming
steps provid
g language, r
d in
fer
g this lab, yo
ta by using A
will develop t
and by using
will be able t
P.NET Dyna
e administrat
the ASP.NET
o:
ic Data.
ion section of
ynamic Data
the website b
framework.
y using various ASP.NET data
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 129/449
26 La Instructions: Optimizing Data Manage ent for Web Forms
ab Sce ario
T
t
t
f
e Adventure
at they can
ward this end
llowing:
orks Sales te
anage inform
, you need to
am has reque
ation, as well
create a set o
sted the addit
s provide a d
web form pa
ion of an adm
ashboard to s
ges that will
inistration sec
enior manage
nable the Sal
tion to the we
ment. As a firs
s team to do
bsite so
t step
the
• View, add, edit, and dele e products
• View sales orders
• View and edit customer etails
In
fr
this lab, you
amework.
will develop t e administration section of the website by using the A P.NET Dynamic Data
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 130/449
Lab Instructions: Optimizing Data Management for Web Forms 27
Section 1: Visual Basic
Exercise 4: Managing Data by Using ASP.NET Dynamic DataThe main tasks in this exercise are as follows:
1. Create a new ASP.NET Dynamic Data web application.
2. Add a new ADO.NET Entity Data Model.
3. Register the object context.
4. Run the application.
f Task 1: Create a new ASP.NET Dynamic Data web application
• Open Microsoft Visual Studio 2010.
• Create an ASP.NET Dynamic Data web application named AWDynamicData by using the NewProject dialog box, and the ASP.NET Dynamic Data Entities Web Application project
template. Place the project in the D:\Lab Files\VB\Lab 08\Starter\Exercise 04 folder.
f Task 2: Add a new ADO.NET Entity Data Model
• Add an ADO.NET Entity Data Model project item named AWEDM.edmx.
a. Generate the model from the AdventureWorksLT2008R2 database, on the .\SQLEXPRESS
server, and select only the Customer (SalesLT), SalesOrderDetail (SalesLT), and
SalesOrderHeader (SalesLT) tables.
b. Save and close the AWEDM.edmx file.
f Task 3: Register the object context
• In the Global.asax.vb file, add context registration to the RegisterRoutes procedure, registering all
tables for the AWDynamicData.AdventureWorksLT2008R2Entities object context.
DefaultModel.RegisterContext(GetType(AWDynamicData.AdventureWorksLT2008R2Entities),New ContextConfiguration() With {.ScaffoldAllTables = True})
• Save and close the Global.asax.vb file.
f Task 4: Run the application
• Build and run the web application.
a. The page displayed in the browser displays a list of the tables you added to the data model.
b. View the Customers page, showing all customers.
c. The page displays the List view that contains the data from the Customers table.
d. View the Details view, for a customer.
e. The page displays the Details view that contains the data for the selected row from theCustomers table.
f. View the Customers page, showing all customers, by clicking Show all items.
g. Sort the customers by the LastName column.
h. The page displays the List view that contains the data of customers, sorted by last name.
i. View the sales order headers associated with the second customer displayed from the top.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 131/449
28 Lab Instructions: Optimizing Data Management for Web Forms
j. The page displays the List view that contains the data of customer sales order headers.
k. Filter the sales order headers by entries that have the OnlineOrderFlag column set to True.
l. The page now displays no sales order headers, because none of the sales order headers have the
OnlineOrderFlag set to true.
m. View the customers page.
n. Create a new customer, by clicking Insert new item.
o. Save the new customer, with empty fields, and then cancel the new customer.
p. The page displays the List view that contains the data from the Customers table. This is the
default view and the one you are returned to, after cancelling.
q. Edit the last customer displayed.
r. The page displays the Edit view that contains the data for the selected row from the Customers
table.
s. Cancel the edit and close Windows Internet Explorer.
t. Close Microsoft Visual Studio 2010.
f Task 5: Turn off the virtual machine and revert the changes
• In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off .
a. In the Turn Off Machine dialog box, click Turn Off .
b. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then
click Revert.
c. In the Revert Virtual Machine dialog box, click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 132/449
Lab Instructions: Optimizing Data Management for Web Forms 29
Section 2: Visual C#
Exercise 4: Managing Data by Using ASP.NET Dynamic DataThe main tasks in this exercise are as follows:
1.
Create a new ASP.NET Dynamic Data web application.
2. Add a new ADO.NET Entity Data Model.
3. Register the object context.
4. Run the application.
f Task 1: Create a new ASP.NET Dynamic Data web application
• Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.
a. Open Microsoft Visual Studio 2010.
b. Create an ASP.NET Dynamic Data web application named AWDynamicData by using the NewProject dialog box, and the ASP.NET Dynamic Data Entities Web Application project
template. Place the project in the D:\Lab Files\CS\Lab 08\Starter\Exercise 04 folder.
f Task 2: Add a new ADO.NET Entity Data Model
• Add an ADO.NET Entity Data Model project item named AWEDM.edmx.
a. Generate the model from the AdventureWorksLT2008R2 database, on the .\SQLEXPRESS
server, and select only the Customer (SalesLT), SalesOrderDetail (SalesLT), and
SalesOrderHeader (SalesLT) tables.
b. Save and close the AWEDM.edmx file.
f Task 3: Register the object context
• In the Global.asax.cs file, add context registration to the RegisterRoutes procedure, registering all
tables for the AWDynamicData.AdventureWorksLT2008R2Entities object context.
DefaultModel.RegisterContext(typeof(AWDynamicData.AdventureWorksLT2008R2Entities),
new ContextConfiguration()
{ScaffoldAllTables = true
});
• Save and close the Global.asax.cs file.
f Task 4: Run the application
• Build and run the web application.
a. The page displayed in the browser displays a list of the tables you added to the data model.
b. View the Customers page, showing all customers.
c. The page displays the List view that contains the data from the Customers table.
d. View the Details view, for a customer.
e. The page displays the Details view that contains the data for the selected row from the
Customers table.
f. View the Customers page, showing all customers, by clicking Show all items.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 133/449
30 Lab Instructions: Optimizing Data Management for Web Forms
g. Sort the customers by the LastName column.
h. The page displays the List view that contains the data of customers, sorted by last name.
i. View the sales order headers associated with the second customer displayed from the top.
j. The page displays the List view that contains the data of customer sales order headers.
k. Filter the sales order headers by entries that have the OnlineOrderFlag column set to True.l. The page now displays no sales order headers, because none of the sales order headers have the
OnlineOrderFlag set to true.
m. View the customers page.
n. Create a new customer, by clicking Insert new item.
o. Save the new customer, with empty fields, and then cancel the new customer.
p. The page displays the List view that contains the data from the Customers table. This is the
default view and the one you are returned to, after cancelling.
q. Edit the last customer displayed.
r.
The page displays the Edit view that contains the data for the selected row from the Customerstable.
s. Cancel the edit and close Windows Internet Explorer.
t. Close Microsoft Visual Studio 2010.
f Task 5: Turn off the virtual machine and revert the changes
• In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
Turn Off .
a. In the Turn Off Machine dialog box, click Turn Off .
b. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then
click Revert.
c. In the Revert Virtual Machine dialog box, click Revert.
Note: The answers to the exercises are on the Course Companion CD.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 134/449
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 1
Module 9
Lab Instructions: Ensuring Quality by Debugging, UnitTesting, and RefactoringContents:
Exercise 1: Configuring Error Handling 4
Exercise 2: Debugging Code 5
Exercise 3: Logging 8
Exercise 4: Creating Unit Tests 12
Exercise 5: Implementing the Test-First/Test-Driven DevelopmentMethodology 15
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 135/449
2 Lab Instructions: Ensuring Quality by Debug ing, Unit Testing, a d Refactoring
ab 9: ebugging, Unit Testi
A
• • • • • I
In
t
bjectives
fter completin
Configure
Debug cod
Configure l
Create unit
Implement
troductio
this lab you
the event lo
g this lab, yo
rror handling
e.
ogging.
tests.
the test-first/
ill configure
, and create a
will be able t
.
est-driven de
rror handling
nd run unit t
g, and Refact ring
o:
velopment m thodology.
lication, debuin a web app
sts.
g code to ide tify errors, lo errors
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 136/449
Lab Instructions: E suring Quality by Debugging, Unit Testing, and Refactoring 3
A
fi
f
• • • • •
ab Sce
dventure Wor
st step towar
atures of Visu
Configure
Debug cod
Log errors
Implement
Implement
ario
ks has request
this end, yo
al Studio 201
ed that you l
r team has d
and the .NE
ok into how
termined you
Framework:
ou can impro
should look i
ve the quality
nto the follow
of the coding
ing functional
. As a
ity and
rror handling
e
a code-first development ethodology
a test-first/te t-driven development met odology
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 137/449
4 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Exercise 1: Configuring Error HandlingThe main tasks for this exercise are as follows:
• Create a generic error page for unhandled errors.
• Modify Global.asax and Web.config to redirect to the generic error page when an unhandled error
occurs.
f 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 01 or D:\Lab
Files\VB\Lab 09\Starter\Exercise 01 folder.
f Task 2: Create a generic error page for unhandled errors
1. Add a new Web Form named CustomErrorPage.
2. Add the text CUSTOM ERROR PAGE to the CustomErrorPage Web Form.
3. Save the AdventureWorks project.
4. Close the CustomErrorPage Web Form.
f Task 3: Modify Web.config to redirect to the generic error page when an unhandled
error occurs
1. Open the Web.config file.
2. Add the following markup to the system.web element.
<customErrors mode="On" defaultRedirect="~/CustomErrorPage.aspx"/>
3. Save and close the Web.config file.
4. Run the application.
5. Click the Submit button.
Note: The custom error page is displayed.
6. Close Windows® Internet Explorer®.
7. Close Visual Studio 2010.
Results: After this exercise, you should have created a custom error page for unhandled exceptions.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 138/449
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 5
Exercise 2: Debugging CodeThe 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.
f 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.
f Task 2: Run the application
1. Set Default.aspx as the project start page.
2. Run the application in Debug mode.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 139/449
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.
f Task 4: Debug a java script error using breakpoints and single stepping
• Run the application in Debug mode.
Note: The Home page is displayed.
f Task 5: Debug Default.aspx.js1. 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 140/449
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 javascript code.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 141/449
8 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Exercise 3: LoggingThe 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.
f 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.
f 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]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 142/449
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.LoadIf 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 IfEnd 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 143/449
10 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
6. Close the Event Viewer.
7. Close Windows Internet Explorer.
f 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.
f 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();
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 144/449
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 loggingthat can be called by a single method and all modules.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 145/449
12 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Exercise 4: Creating Unit TestsThe 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.
f 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.
f Task 2: Create a method to add two numbers1. 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.
f Task 3: Add a test project
• Add a test project named CalculatorTestProject for the Add method.
f 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 146/449
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 valueint 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 valueint 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 appropriatevalue
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 valueDim actual As Integer
actual = target.Add(p1, p2)
Assert.AreEqual(expected, actual)End Sub
f Task 5: Run the test
• Start the test.
Note: In the Test Result window, you can see that the AddTest test passed.
f 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#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 147/449
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 valueint 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 appropriatevalue
Dim p1 As Integer = 2 ' TODO: Initialize to an appropriate value
Dim p2 As Integer = 3 ' TODO: Initialize to an appropriate valueDim 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
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 148/449
Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring 15
Exercise 5: Implementing the Test-First/Test-Driven DevelopmentMethodologyThe main tasks for this exercise are as follows:
• Create tests.
• Create method stub.
• Run the tests.
• Add logic to stub methods.
• Run the tests.
f 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.
f 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)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 149/449
16 Lab Instructions: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Dim expected As Integer = 6
Dim unexpected As Integer = 5Dim 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.
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 150/449
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.
f 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 * p2End 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.
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 151/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 152/449
Lab Instructions: Securing a Web Application 1
Module 10
Lab Instructions: Securing a Web ApplicationContents:
Exercise 1: Configuring ASP.NET Membership and Roles 4
Exercise 2: Authentication 6
Exercise 3: Authorization 10
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 153/449
2 Lab Instructions: Securing a Web Application
ab 10: Securing a We
A
• • • I
In
u
le
bjectives
fter completin
Create and
Implement
Create acc
troductio
this lab you
sing the Logi
arn to create
g this lab, yo
manage user
the Login co
ss rules
ill learn how
control. You
an email pass
b Application
will be able to:
using the ASPand roles by .NET Web Sit Administrati n Tool
trol
to use the AS
will also impl
ord recovery
.NET Web Sit
ment custom
page. Finally,
e Administrati
logic to expir
you will learn
on Tool, auth
e the passwor
how to creat
nticate users
in 90 days, a
access rules.
by
nd
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 154/449
Lab Instructions: Securin a Web Application 3
T
a
T
a
ab Sce
e Adventure
thenticated
is means you
thentication
ario
Works Sales t
sers are able
am has requ
o access the s
sted that area
ecure areas o
s of the websi
the site.
ite be protect d so that onl
must configu
and authoriza
re ASP.NET M
ion, impleme
embership, cr
nt Login cont
eate users, cre
ols, and test t
ate and assig
he web applic
roles, imple
ation.
ent
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 155/449
4 Lab Instructions: Securing a Web Application
Exercise 1: Configuring ASP.NET Membership and RolesThe 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.
f 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:\LabFiles\VB\Lab 10\Starter\Exercise 01 folder.
f 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.
f Task 3: Add users
1. Click Create user.
2. Fill out the information to create a new user, using the following information.
UserName Password E-mail
SecurityQuestion Security Answer
Mary Pa$$w0rd [email protected] Favorite pet Cat
3. Click Create User.
4. Click Continue.
5. Fill out the information to create a new user, using the following information.
UserName Password E-mail
SecurityQuestion Security Answer
John Pa$$w0rd [email protected] High School Central
6. Click Create User.
7. Click Continue.
f Task 4: Add roles
1. In the ASP.NET Web Site Administration Tool, click Security.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 156/449
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.
f Task 5: Assign roles to users1. 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 byusing the ASP.NET Web Site Administration Tool. You should also have learned how to create usersand role for an ASP.NET web application.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 157/449
6 Lab Instructions: Securing a Web Application
Exercise 2: AuthenticationThe 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.
f 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:\LabFiles\VB\Lab 10\Starter\Exercise 02 folder.
f 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 toFrom 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>
f 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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 158/449
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 isrequired." 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 isrequired." 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 followingmarkup 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.
f 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 userMembershipUser user = Membership.GetUser(LoginUser.UserName.Trim());
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 159/449
8 Lab Instructions: Securing a Web Application
// Did we find the user?if (user != null)
{
// Check if the user password has expired after 90 daysif (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 userDim 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 IfEnd If
End Sub
4. Build the solution.
5. Close the Login.aspx code-behind file.
6. Close the Login.aspx Web Form.
f Task 5: Configure password recovery
1. Add a new Web Form named EmailPassword to the Account folder. The Web Form must be basedon the Site.Master master page.
2. Drag a PasswordRecovery server control from the Login section of the Toolbox to theEmailPassword.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="[email protected]">
<network host="yourhost" userName="hostusername" password="hostpassword" /></smtp>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 160/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 161/449
10 Lab Instructions: Securing a Web Application
Exercise 3: AuthorizationThe 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.
f 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:\LabFiles\VB\Lab 10\Starter\Exercise 03 folder.
f 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.
f 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.
f Task 4: Test the web application
1. Build the solution and fix any errors.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 162/449
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 InternetExplorer 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.
f 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 clickTurn 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 clickRevert.
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 163/449
Lab Instructions: Applying Master Pages and CSS 1
Module 11
Lab Instructions: Applying Master Pages and CSSContents:
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 164/449
2 Lab Instructions: Applyi g Master Pages and CSS
A
• • • • I
In
C
c
w
e
t
ab 11:
ote: Tasks in
bjectives:
fter completin
Modify a
Create nest
Apply mast
Apply The
troductio
this lab, you
ontentPlace
eate an area i
ill then create
isting CSS sty
eme in the
Applyi
this lab will b
g this lab, yo
aster page.
ed master pa
er pages.
es, Skins, and
will first modi
older for the
n the existing
two control s
les, create tw
eb.config file
g Mas
e the same, re
will be able t
es.
Styles.
y the existing
footer conten
master page
ins and appl
themes for t
.
er Pag s and SS
gardless of th
o:
master page
t, and imple
or status mes
them to cont
e website ba
e programmi
or the Adven
ent it in the
ages and im
rols in the exi
ed on the exi
g language y ur solution is using.
ureWorks we
bout.aspx pa
lement it for
sting website.
sting styles, an
site, add a n
ge. You will t
ll child pages
You will also
d implement
w
en
. You
odify
one
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 165/449
Lab Instruc tions: Applying Master Pages and CSS 3
A
o
f
Y
n
ab Sce
dventure Wor
ptions using t
ture changes
u will also ad
eed to imple
ario
ks is redesigni
e new color
to the look-a
ng their Webs
alette, taking
d-feel easy t
ite in a corpo
advantage of
perform.
rate branding
the theme an
initiative. You
d skin feature
will present t
s of ASP.NET t
o
o make
d an applicati
ent this mess
on-wide locat
ging location
ion for reporti
consistently
ng errors and
cross the app
sending mess
lication.
Youages to users.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 166/449
4 Lab Instructions: Applying Master Pages and CSS
Exercise 1: Modify a Master Page1. 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.
f 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:\LabFiles\VB\Lab 11\Starter\Exercise 01 folder.
f Task 2: Open the Site.Master master page
• Open the Site.Master file in the root of the AdventureWorks project.
f 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>
f Task 4: Open the About.aspx page
• Open the About.aspx file in the root of the AdventureWorks project.
f 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>
f 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>
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 167/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 168/449
6 Lab Instructions: Applying Master Pages and CSS
Exercise 2: Create a Nested Master PageThe 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.
f 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:\LabFiles\VB\Lab 11\Starter\Exercise 02 folder.
f 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>
f 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>
f Task 4: Add footer content
• To add the footer content to the Nested.master file, add the following markup in the Footer Content control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 169/449
Lab Instructions: Applying Master Pages and CSS 7
<asp:Content ID="Footer" ContentPlaceHolderID="FooterContent" runat="server">
Copyright AdventureWorks</asp:Content>
f 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>
f Task 5: Test the Default.aspx page
• Test the page by pressing CTRL+F5.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 170/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 171/449
Lab Instructions: Applying Master Pages and CSS 9
Exercise 3: Integrate a Master PageThe 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.
f 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:\LabFiles\VB\Lab 11\Starter\Exercise 03 folder.
f Task 2: Open the Site.Master master page
• Open the Site.Master file.
f 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>
f 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 StringGet
Return StatusMessageLabel.Text
End GetSet(ByVal value As String)
StatusMessageLabel.Text = value
End SetEnd Property
f 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" %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 172/449
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) HandlesMe.Load
If Not Page.IsPostBack Then
Dim categoryName As String = NothingDim categoryID As String = "5"
If Not Request("id") Is Nothing ThencategoryID = 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 173/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 174/449
12 Lab Instructions: Applying Master Pages and CSS
Exercise 4: Implement Control SkinsThe 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.
f 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:\LabFiles\VB\Lab 11\Starter\Exercise 04 folder.
f Task 2: Create a new theme named Default
• Add new theme folder named Default to project.
f Task 3: Create a Controls.skin file in the Default theme
• Add a new skin file named Controls.skin to the Default theme folder.
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 175/449
Lab Instructions: Applying Master Pages and CSS 13
Exercise 5: Apply Styles and ThemesThe 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.
f 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:\LabFiles\VB\Lab 11\Starter\Exercise 05 folder.
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 176/449
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.
f 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.
f 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.
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 177/449
Lab Instructions: Developing Client-side Scripts and Services 1
Module 12
Lab Instructions: Developing Client-side Scripts and ServicesContents:
Exercise 1: Using jQuery 4
Exercise 2: Using Advanced jQuery 7
Exercise 3: Creating a WCF Service 9
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 178/449
2 Lab Instructions: Developing Client-side Scri ts and Services
ab 12: Creating Clien
A
• • • • I
In
j
in
bjectives
fter completin
Enable clie
Use jQuery
Embed jQu
Create a W
troductio
this lab, you
uery. You will
voke it using
g this lab, yo
t-side sorting
selectors.
ery visual effe
CF Service an
will enhance t
l also embed j
he client-side
t-side cripts nd Ser ices
will be able to:
.
cts.
invoke it usi g the client-side code.
he shopping c
Query visual e
code.
art interface t
ffects in your
o support clie
application, c
nt-side sortin
eate a WCF s
, and use sele
rvice, and the
ctors in
n
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 179/449
Lab Instructions: De eloping Client-s ide Scr ipts and Services 3
A
o
it
Y
h
p
ab Sce
dventure Wor
r her shoppin
ems in the car
u have also
over the mou
roducts, and t
ario
ks has design
cart. After th
t.
d a shopping
e products ar
cart applicati
added, the u
n that allows
ser can click o
the user to a
n the Cart lin
d products in
k to view the
to his
urrent
een requeste
e over the pr
he service mu
to display a
duct name. I
t be callable
vertisement i
addition, yo
rom client-sid
formation ab
must create
e code.
out the produ
a WCF service
cts when the
for retrieving
users
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 180/449
4 Lab Instructions: Developing Client-side Scripts and Services
Exercise 1: Using jQueryThe 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.
f 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:\LabFiles\VB\Lab 12\Starter\Exercise 01 folder.
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 181/449
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>
f 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()
ElselblMessage.Text = "Your cart is empty"
btnPlaceOrder.Visible = False
End If
If gvCart.Rows.Count > 0 ThengvCart.UseAccessibleHeader = TruegvCart.HeaderRow.TableSection = TableRowSection.TableHeadergvCart.FooterRow.TableSection = TableRowSection.TableFooter
End IfEnd Sub
3. Run the application.
4. Select the Bike Stands product category, and then click Submit.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 182/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 183/449
Lab Instructions: Developing Client-side Scripts and Services 7
Exercise 2: Using Advanced jQueryThe main tasks for this exercise are as follows:
1. Implement jQuery events and effects.
2. Create a custom plug-in.
f Task 1: Open an existing ASP.NET web application1. Open Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 12\Starter\Exercise 02 or D:\LabFiles\VB\Lab 12\Starter\Exercise 02 folder.
f 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.
f 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">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 184/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 185/449
Lab Instructions: Developing Client-side Scripts and Services 9
Exercise 3: Creating a WCF ServiceThe 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.
f 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:\LabFiles\VB\Lab 12\Starter\Exercise 03 folder.
f Task 2: Create an Ajax-enabled WCF service
• Add a new Ajax-enabled WCF service named ProductsService to the project.
f 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 isWebMessageFormat.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 herereturn;
}
// 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 hereEnd 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();
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 186/449
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 == randomNumberselect 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.ProductsWhere p.ProductID = randomNumberSelect New With {p.Name, p.ListPrice,
p.ProductNumber}).FirstOrDefault()
Return NewSystem.Web.Script.Serialization.JavaScriptSerializer().Serialize(randomProduct)
End UsingEnd 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.
f 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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 187/449
Lab Instructions: Developing Client-side Scripts and Services 11
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 188/449
12 Lab Instructions: Developing Client-side Scripts and Services
6. Close Windows Internet Explorer.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 189/449
Lab Instructions: Implementing Advanced Ajax in a Web Application 1
Module 13
Lab Instructions: Implementing Advanced Ajax in a WebApplication
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 190/449
2 Lab Instructions: Implementing Advanced Aj x in a Web Application
ab 13:dvent
ImplereWor
entingks We
AdvanApplic
ced Ajation x for t e
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 191/449
Lab Instructions: Implementing Advanced Ajax i a Web Appl icat ion 3
A
a
e
In
t
T
w
In
t
A
• • • I
In
Y
ab Sce
dding the pro
ked to enhan
anagement
courage pur
addition, the
e user selects
do this, whe
hen the user
this lab, you
e different cli
bjectives
fter completin
Dynamicall
Dynamicall
Add Ajax e
troductio
this lab, you
u will also us
ario
duct catalog t
ce the usabilit
o the Advent
y of the catal
reWorks web
g.
site has been success. No , you have b en
ould like to d
hases.
isplay two Featured Products when a user clicks a prod ct category, to
y would like t
a category.
show all of the products a d product categories on the same page hen
andn a user clicks
licks the Sub
a category, y
it button, yo
u will need t
u will need to
load the pro
load all prod
ducts featured
cts.
dynamically,
Query and Ajwill explore th
ent events.
e features of j x in an MVC pplication. Y u will also ex mine
g this lab, stu ents will be able to:
y load conten into a view using Microsof t Ajax Library.
y load conten into a view using jQuery A ax.
ent handlers using jQuery jax.
will add Ajax l
e jQuery in an
ibraries to the
MVC view, a
pages and m
d handle eve
aster page, an
ts using jQu
d create a par
ry.
tial Ajax MVC view.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 192/449
4 Lab Instructions: Implementing Advanced Ajax in a Web Application
Exercise 1: Using Microsoft Ajax in an MVC PageThe 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.
f 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.
f 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>
f 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 ActionResultDim id As Integer = CInt(CategoryID)
Dim prodCategories = pr.GetCategories()
Return View(prodCategories)End Function
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 193/449
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%>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 194/449
6 Lab Instructions: Implementing Advanced Ajax in a Web Application
f 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.Models.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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 195/449
Lab Instructions: Implementing Advanced Ajax in a Web Application 7
Exercise 2: Using jQuery in an MVC ViewThe 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.
f 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.
f 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>
f 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
f 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>
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">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 196/449
8 Lab Instructions: Implementing Advanced Ajax in a Web Application
$(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 ProductCategories list.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 197/449
Lab Instructions: Implementing Advanced Ajax in a Web Application 9
Exercise 3: Handling EventsThe 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.
f 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.
f 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('');});
});
f 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
>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Products</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 198/449
10 Lab Instructions: Implementing Advanced Ajax in a Web Application
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 (OfAdventureWorksMvc.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();
$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>',{ CategoryId: id });
});
$('.log').ajaxStart(function () {$(this).text('Loading...');
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 199/449
Lab Instructions: Implementing Advanced Ajax in a Web Application 11
$('.error').text('');
});$('.log').ajaxComplete(function () {
$(this).text('');
});$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');
});});
</script>
</asp:Content>
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 200/449
Lab Instructions: ASP.NET Deployments 1
Module 14
Lab Instructions: ASP.NET Deployments
Contents:Exercise 1: Creating a Profile for Deploying a Web Application ProjectUsing One-Click Publish 4
Exercise 2: Creating a Web Deployment Package 7
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 201/449
2 Lab Instructions: ASP.NET Deployments
ab 14: Deploy
N
p
A
I
In
w
ote: You can
rogramming l
bjectives
fter completin
• Create
• Create
troductio
this lab, you
ill also create
ing Ad entur Works
perform the t
anguage.
g this lab, yo
a One-Click
and deploy a
will create a a web deploy
sks in this lab
will be able t
ublish profil
web deploym
rofile for depl
ent package
by using eith
o:
.
ent package.
oying a web
and use it to
er Visual C#® or Visual Basic® as your
pplication pr
deploy a web
ject using on
application to
-click publish
IIS.
. You
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 202/449
Lab Instructions: ASP.NET Deployments 3
A
d
di
ab Sce
dventureWor
eployment. Y
isadvantages
ario
s is preparing
u will investig
f each.
to deploy th
ate the differ
application t
nt methods o
o the differen
f deployment
servers for te
and the adva
sting, staging,
tages and
and
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 203/449
4 Lab Instructions: ASP.NET Deployments
Exercise 1: Creating a Profile for Deploying a Web Application ProjectUsing One-Click PublishThe 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.
f 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\Lab14\Starter\Exercise 01 or D:\Lab Files\VB\Lab 14\Starter\Exercise 01 folder.
f 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: [email protected]
• 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.
f Task 3: Set the active build configuration
1. In Solution Explorer, click Deployment.
2. On the Solutions Configuration list, click Release.
f Task 4: Specify which files and IIS settings to deploy1. 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 204/449
Lab Instructions: ASP.NET Deployments 5
6. Save the changes.
f 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 DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;IntegratedSecurity=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.
f 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="DataSource=.\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.
f 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 untrustedcertificate 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 205/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 206/449
Lab Instructions: ASP.NET Deployments 7
Exercise 2: Creating a Web Deployment PackageThe 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.
f 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:\LabFiles\VB\Lab 14\Starter\Exercise 02 folder.
f 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;IntegratedSecurity=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" /><add name="AW"
connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AdventureWorksLT2008R2_Data.mdf;Integrated 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 207/449
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
f Task 4: Specify deployment packaging settings1. 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 (appliesto 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.
f 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;IntegratedSecurity=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, DataSource=10264A-GEN-DEV\SQLEXPRESS;Initial Catalog=DeploymentTest;IntegratedSecurity=True;Pooling=False.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 208/449
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.mdf;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\Lab14\Starter\DeploymentGrant.sql script, by clicking Add Script.
17. Save the changes.
f 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.
f 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.
f Task 8: Create a package and import it into IIS
1. Build a deployment package by using the Project menu.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 209/449
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 scripts—one 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\Exercise02\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.
f 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.
f 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 .
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 210/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 211/449
Lab Instructions: Developing a Web Application by Using Silverlight 1
Module 15
Lab Instructions: Developing a Web Application by UsingSilverlight
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 212/449
2 Lab Instructions: Developing a Web Application by Using Silverlight
ab 15: Adding Silverlight to
A
• • • I
In
Si
Si
bjectives
fter completin
Create a Sil
Create a Sil
Display dat
troductio
this lab, you
lverlight appli
lverlight cont
g this lab, yo
verlight proje
verlight WCF
a by using Sil
will learn how
cation will be
ol.
will be able t
t.
service.
erlight contr
to add Silverl
used to consu
a Web Applic tion
o:
ls.
ight to an exis
me a WCF Se
ting Adventu
vice and displ
eWorks web
lay the data b
pplication. Th
using the D
e
taGrid
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 213/449
Lab Instructions: Developing a Web Application by Using Silverl ight 3
S
d
si
ab Sce
me of Adven
anagement
eveloping the
mple prototy
ario
tureWorks’ co
ants to explo
AdventureW
e. The resulti
mpetitors are
e the feasibili
rks web site i
g prototype
experiencing
y of using RI
future. For t
hould look si
higher web tr
technology t
is purpose, y
ilar to the fo
ffic than Adv
o increase use
u have been
llowing scree
ntureWorks.
r stickiness w
asked with cr
shot.
en
eating a
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 214/449
4 Lab Instructions: Developing a Web Application by Using Silverlight
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 215/449
Lab Instructions: Developing a Web Application by Using Silverlight 5
Exercise 1: Creating a Silverlight ProjectThe main tasks for this exercise are as follows:
• Add a new Silverlight project.
f 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:\LabFiles\VB\Lab 15\Starter\Exercise 01 folder.
f Task 2: Add a new Silverlight project
1. Add a new Microsoft® Silverlight® application project named AdventureWorksSL to the solution. The
Silverlight project should be hosted in the AdventureWorks project.
2. Build the solution.
3. Save the solution changes.
4. Close Visual Studio 2010.
Results: After this exercise, you should have created a Silverlight project and also have become familiar
with how to host a Silverlight project.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 216/449
6 Lab Instructions: Developing a Web Application by Using Silverlight
Exercise 2: Creating a Silverlight WCF ServiceThe main tasks for this exercise are as follows:
1. Create a Silverlight WCF Service.
2. Create methods that return a list of product categories, and a list of products by category.
f Task 1: Open an existing solution1. Open Microsoft® Visual Studio® 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 15\Starter\Exercise 02 or D:\LabFiles\VB\Lab 15\Starter\Exercise 02 folder.
f Task 2: Create a Silverlight WCF service
• Add a new Silverlight WCF service named ProductServiceSL to the AdventureWorks project.
f Task 3: Create methods that return a list of product categories, and a list of products by
category
1. Delete the stub method DoWork from the code file.
2. Import the System.Collections.Generic namespace.
3. Add the following method, which returns a list of product categories, to the ProductServiceSL class.
[Visual C#]
[OperationContract] public IEnumerable<ProductCategory> GetProductCategories() {
return DataAccessLayer.Products.GetCategories(); } [Visual Basic]
<OperationContract> Public Function GetProductCategories() As IEnumerable(Of
ProductCategory) Return AdventureWorks.DataAccessLayer.Products.GetCategories() End Function
4. Add the following method that returns a list of products by category, to the ProductServiceSL class.
[Visual C#]
[OperationContract] public IEnumerable<Product> GetProductsByCategory(int
ProductCategoryID) {
return DataAccessLayer.Products.GetProductsByCategory(ProductCategoryID); } [Visual Basic]
<OperationContract> Public Function GetProductsByCategory(ProductCategoryID As Integer) AsIEnumerable(Of Product)
Return AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(Prod
uctCategoryID) End Function
5. Build the solution and fix any errors.
6. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 217/449
Lab Instructions: Developing a Web Application by Using Silverlight 7
Results: After this exercise, you should have created a Silverlight WCF service and added some code to
return product categories and products from the database.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 218/449
8 Lab Instructions: Developing a Web Application by Using Silverlight
Exercise 3: Displaying Data by Using Silverlight ControlsThe main tasks for this exercise are as follows:
1. Add a WCF service reference.
2. Create Silverlight controls to display the data.
3. Call the service asynchronously.
4. Bind the data returned from the services to the grids.
5. Test the application.
f Task 1: Open an existing solution
1. Open Microsoft® Visual Studio® 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 15\Starter\Exercise 03 or D:\LabFiles\VB\Lab 15\Starter\Exercise 03 folder.
f Task 2: Add a WCF Service reference
1. Build the solution.
2. In the AdventureWorksSL project, add a service reference to the ProductServiceSL.svc WCF service,
with a namespace of AdventureWorks.
f Task 3: Create Silverlight controls to display the data
1. Open MainPage.xaml in the Designer.
2. From the Toolbox, drag a Silverlight DataGrid control to the left side of the page.
3. Change the height and width of the UserControl and the Grid control to the following values.
• Height: 400
• Width: 600
4. Make the following property changes to the DataGrid control.
• Name: CategoriesDataGrid
• Height: 156
• Width: 100
• AutoGenerateColumns: False
5. From the Toolbox, drag a Silverlight DataGrid control to the right of the CategoriesDataGrid control
on the page.
6. Make the following property changes to the DataGrid control.
• Name: ProductsDataGrid
• Height: 300
• Width: 370
• AutoGenerateColumns: False
7. Drag two Silverlight Label controls onto the page. Position them directly above the two DataGrid
controls.
8. Make the following changes to the left-most Labels control.
• Name: CategoryLabel
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 219/449
Lab Instructions: Developing a Web Application by Using Silverlight 9
• Height: 14
• Width: 100
• Content: Categories
9. Make the following changes to the right-most Labels control.
• Name: ProductLabel• Height: 14
• Width: 100
• Content: Products
10. The final result will look something like this:
11. Examine the markup in XAML view.
<UserControl x:Class="AdventureWorksSL.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentati
on/sdk" Height="400" Width="600">
<Grid x:Name="LayoutRoot" Background="White" Width="600"
Height="400">
<sdk:DataGrid AutoGenerateColumns="False" Height="156"HorizontalAlignment="Left" Name="CategoriesDataGrid"
VerticalAlignment="Top" Width="100" Margin="5,30,0,0" />
<sdk:DataGrid AutoGenerateColumns="False" Height="300"HorizontalAlignment="Left" Margin="106,30,0,0"
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 220/449
10 Lab Instructions: Developing a Web Application by Using Silverlight
Name="ProductsDataGrid" VerticalAlignment="Top" Width="370" />
<sdk:Label Height="14" HorizontalAlignment="Left"Name="CategoryLabel" VerticalAlignment="Top" Width="100"
Margin="6,1,0,0" Content="Categories" />
<sdk:Label Height="14" HorizontalAlignment="Left"Margin="106,1,0,0" Name="ProductLabel" VerticalAlignment="Top"
Width="100" Content="Products" />
</Grid></UserControl>
12. Configure the CategoriesDataGrid control to display the necessary columns returned from the
GetProductCategories service method, by adding a DataGrid.Columns element to the
CategoriesDataGrid control.
<sdk:DataGrid AutoGenerateColumns="False" Height="156"
HorizontalAlignment="Left" Name="CategoriesDataGrid"VerticalAlignment="Top" Width="100" Margin="5,30,0,0">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{BindingProductCategoryID}" Header="ID" Visibility="Collapsed" />
<sdk:DataGridTextColumn Binding="{Binding Name}"
Header="Name" /></sdk:DataGrid.Columns>
</sdk:DataGrid>
13. Configure the ProductsDataGrid control to display the necessary columns returned from the
GetProductByCategory service method, by adding a DataGrid.Columns element to the
ProductsDataGrid control.
<sdk:DataGrid AutoGenerateColumns="False" Height="300"HorizontalAlignment="Left" Margin="106,30,0,0"
Name="ProductsDataGrid" VerticalAlignment="Top" Width="370" />
<sdk:DataGrid.Columns><sdk:DataGridTextColumn Binding="{Binding Name}"
Header="Name" />
<sdk:DataGridTextColumn Binding="{Binding ProductNumber}"Header="Product Number" />
<sdk:DataGridTextColumn Binding="{Binding Color}"
Header="Color" /><sdk:DataGridTextColumn Binding="{Binding Size}"
Header="Size" />
</sdk:DataGrid.Columns></sdk:DataGrid>
f Task 4: Call the services asynchronously
1. In the Designer, double-click the CategoriesDataGrid control.
Note: This creates an event handler named
CategoriesDataGrid_SelectionChanged in the MainPage.xaml.cs or
MainPage.xaml.vb code-behind file.
[Visual C#]
private void CategoriesDataGrid_SelectionChanged(object sender,
SelectionChangedEventArgs e) { } [Visual Basic] Private Sub CategoriesDataGrid_SelectionChanged(ByVal sender As
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 221/449
Lab Instructions: Developing a Web Application by Using Silverlight 11
System.Object, ByVal e As
System.Windows.Controls.SelectionChangedEventArgs) HandlesCategoriesDataGrid.SelectionChanged
End Sub 2. In the MainPage class, create a protected variable for the ProductServiceSLClient object.
[Visual C#]
public partial class MainPage : UserControl {
protected AdventureWorks.ProductServiceSLClient productService
= new AdventureWorks.ProductServiceSLClient();
... [Visual Basic]
Public Partial Class MainPage Inherits UserControl
Protected productService As NewAdventureWorks.ProductServiceSLClient()
... 3. In the MainPage class constructor, wire up event handlers for the two Web service methods.
[Visual C#]
public MainPage() {
InitializeComponent(); productService.GetProductCategoriesCompleted += new
EventHandler<AdventureWorks.GetProductCategoriesCompletedEventArgs
>(productService_GetProductCategoriesCompleted);productService.GetProductsByCategoryCompleted += new
EventHandler<AdventureWorks.GetProductsByCategoryCompletedEventArg
s>(productService_GetProductsByCategoryCompleted);
} [Visual Basic]
Public Sub New() InitializeComponent()
AddHandler productService.GetProductCategoriesCompleted,
AddressOf productService_GetProductCategoriesCompleted
AddHandler productService.GetProductsByCategoryCompleted,AddressOf productService_GetProductsByCategoryCompleted
End Sub 4. Each event handler needs a method to execute once the asynchronous call completes.
[Visual C#]
void productService_GetProductsByCategoryCompleted(object sender,
AdventureWorks.GetProductsByCategoryCompletedEventArgs e) { } void productService_GetProductCategoriesCompleted(object sender,
AdventureWorks.GetProductCategoriesCompletedEventArgs e) {
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 222/449
12 Lab Instructions: Developing a Web Application by Using Silverlight
} [Visual Basic]
Private Sub productService_GetProductCategoriesCompleted(ByValsender As Object, ByVal e As
AdventureWorks.GetProductCategoriesCompletedEventArgs) End Sub Private Sub productService_GetProductsByCategoryCompleted(ByVal
sender As Object, ByVal e AsAdventureWorks.GetProductsByCategoryCompletedEventArgs) End Sub
5. When the page loads, the CategoriesDataGrid control must be populated. In the class constructor,
add a call to the service method GetProductCategoriesAsync.
[Visual C#]
public MainPage() {
InitializeComponent(); productService.GetProductCategoriesCompleted += new
EventHandler<AdventureWorks.GetProductCategoriesCompletedEventArgs
>(productService_GetProductCategoriesCompleted); productService.GetProductsByCategoryCompleted += new
EventHandler<AdventureWorks.GetProductsByCategoryCompletedEventArgs
>(productService_GetProductsByCategoryCompleted); productService.GetProductCategoriesAsync();
} [Visual Basic]
Public Sub New() InitializeComponent() AddHandler productService.GetProductCategoriesCompleted,
AddressOf productService_GetProductCategoriesCompleted AddHandler productService.GetProductsByCategoryCompleted,
AddressOf productService_GetProductsByCategoryCompleted productService.GetProductCategoriesAsync()
End Sub f Task 5: Bind the data returned from the services to the grids
1. The initial call to GetProductCategoriesAsync returns to
productService_GetProductCategoriesCompleted. In the
productService_GetProductCategoriesCompleted method, bind the results using the ItemsSource
property returned by the service to the grid.
[Visual C#]
void productService_GetProductCategoriesCompleted(object sender,
AdventureWorks.GetProductCategoriesCompletedEventArgs e){
CategoriesDataGrid.ItemsSource = e.Result;
}
[Visual Basic]
Sub productService_GetProductCategoriesCompleted(sender As Object,
e As AdventureWorks.GetProductCategoriesCompletedEventArgs)
CategoriesDataGrid.ItemsSource = e.ResultEnd Sub
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 223/449
Lab Instructions: Developing a Web Application by Using Silverlight 13
2. In the CategoriesDataGrid_SelectionChanged event handler, get the selected category, and retrieve
the products by category.
[Visual C#]
private void CategoriesDataGrid_SelectionChanged(object sender,SelectionChangedEventArgs e)
{ AdventureWorks.ProductCategory category =
CategoriesDataGrid.SelectedItem as AdventureWorks.ProductCategory;
productService.GetProductsByCategoryAsync(category.ProductCategory
ID);}
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 224/449
14 Lab Instructions: Developing a Web Application by Using Silverlight
[Visual Basic]
Private Sub CategoriesDataGrid_SelectionChanged(sender As Object,e As SelectionChangedEventArgs)
Dim category As AdventureWorks.ProductCategory =
TryCast(CategoriesDataGrid.SelectedItem,AdventureWorks.ProductCategory)
productService.GetProductsByCategoryAsync(category.ProductCategoryID)End Sub • The call to GetProductsByCategoryAsync returns to the
productService_GetProductsByCategoryCompleted method, where the results returned by the
service should be bound to the ItemsSource property of the grid.
[Visual C#]
void productService_GetProductsByCategoryCompleted(object sender,
AdventureWorks.GetProductsByCategoryCompletedEventArgs e){
ProductsDataGrid.ItemsSource = e.Result;
} [Visual Basic]
Sub productService_GetProductsByCategoryCompleted(sender As
Object, e As
AdventureWorks.GetProductsByCategoryCompletedEventArgs) ProductsDataGrid.ItemsSource = e.Result
End Sub • The final code should like this.
[Visual C#]
public partial class MainPage : UserControl {
protected AdventureWorks.ProductServiceSLClient
productService = new AdventureWorks.ProductServiceSLClient(); public MainPage() {
InitializeComponent(); productService.GetProductCategoriesCompleted += new
EventHandler<AdventureWorks.GetProductCategoriesCompletedEventArgs
>(productService_GetProductCategoriesCompleted); productService.GetProductsByCategoryCompleted += new
EventHandler<AdventureWorks.GetProductsByCategoryCompletedEventArg
s>(productService_GetProductsByCategoryCompleted); productService.GetProductCategoriesAsync();
} private void CategoriesDataGrid_SelectionChanged(object
sender, SelectionChangedEventArgs e) { AdventureWorks.ProductCategory category =
CategoriesDataGrid.SelectedItem as AdventureWorks.ProductCategory; productService.GetProductsByCategoryAsync(category.ProductCategory
ID); } void productService_GetProductsByCategoryCompleted(object
sender, AdventureWorks.GetProductsByCategoryCompletedEventArgs e) {
ProductsDataGrid.ItemsSource = e.Result;
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 225/449
Lab Instructions: Developing a Web Application by Using Silverlight 15
} void productService_GetProductCategoriesCompleted(object
sender, AdventureWorks.GetProductCategoriesCompletedEventArgs e) {
CategoriesDataGrid.ItemsSource = e.Result; }
} [Visual Basic]
Partial Public Class MainPage Inherits UserControl Protected productService As New
AdventureWorks.ProductServiceSLClient() Public Sub New()
InitializeComponent() AddHandler productService.GetProductCategoriesCompleted
, AddressOf productService_GetProductCategoriesCompleted AddHandler productService.GetProductsByCategoryCompleted
, AddressOf productService_GetProductsByCategoryCompleted productService.GetProductCategoriesAsync()
End Sub
Private Sub CategoriesDataGrid_SelectionChanged(ByVal sender
As System.Object, ByVal e As
System.Windows.Controls.SelectionChangedEventArgs) Dim category As AdventureWorks.ProductCategory =
TryCast(CategoriesDataGrid.SelectedItem,
AdventureWorks.ProductCategory) productService.GetProductsByCategoryAsync(category.ParentProductCa
tegoryID) End Sub Private Sub productService_GetProductCategoriesCompleted(ByVal
sender As Object, ByVal e As
AdventureWorks.GetProductCategoriesCompletedEventArgs) CategoriesDataGrid.ItemsSource = e.Result
End Sub Private Sub productService_GetProductsByCategoryCompleted(ByVal sender As
Object, ByVal e AsAdventureWorks.GetProductsByCategoryCompletedEventArgs)
ProductsDataGrid.ItemsSource = e.Result End Sub
End Class f Task 6: Bind the data returned from the services to the grids
1. Set AdventureWorksSLTestPage.aspx as the start page.
2. Run the application.
Note: It might take a while to load the data from the WCF service.
3. Select the Bib-Shorts category.
Note: Notice how the Products list is populated with all the products for the selected category.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 226/449
16 Lab Instructions: Developing a Web Application by Using Silverlight
4. Close Windows Internet Explorer.
5. Close Visual Studio 2010.
f 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 this exercise, you should be able to consume a Silverlight WCF service from a Silverlight
application.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 227/449
Lab Answer Key: Overview of Web Application Architecture and Design 1
Module 1
Lab Answer Key: Overview of Web Application Architectureand Design
Contents:Exercise 1: Exploring the Adventure Works Website 2
Exercise 2: Comparing Web Forms and MVC 5
Exercise 3: Working with the Request Life Cycle 6
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 228/449
2 Lab Answer Key: Overview of Web Application Architecture and Design
Lab 1: Exploring the Adventure Works WebsiteExercise 1: Exploring the Adventure Works Website
f 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 Studio2010, and then click 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
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\Lab01\Starter\WebForms\AdventureWorks.sln or D:\Lab Files\VB\Lab01\Starter\WebForms\AdventureWorks.sln, and then click Open.
f Task 2: Start the web application
• Run the AdventureWorks solution in Debug mode.
• In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartDebugging, or press F5.
f Task 3: Browse the products list• In the Product Categories list, select Bib-Shorts, and then click the Submit button.
• In the Home Page – Windows Internet Explorer window, in the Product Categories list, click
Bib-Shorts, and then click Submit.
Note: Observe the products available in the Bib-Shorts product category.
f Task 4: Add products to the shopping cart
1. Add one pair of Men’s Bib-Shorts, size M, to the shopping cart.
a.
In the http://localhost:xxxx/Products.aspx?id=22 – Windows Internet Explorer window, inthe Products list, click Men’s Bib-Shorts, M.
b. In the http://localhost:xxxx/ProductDetail.aspx?id=856 – Windows Internet Explorer
window, click Order.
2. Continue shopping.
• In the http://localhost:xxxx/ShoppingCart.aspx – Windows Internet Explorer window, click
Continue Shopping.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 229/449
Lab Answer Key: Overview of Web Application Architecture and Design 3
f Task 5: Place an order
1. Open the shopping cart.
• In the Home Page – Windows Internet Explorer window, on the menu, click Cart.
2. Place the order.
• In the http://localhost:xxxx/ShoppingCart.aspx – Windows Internet Explorer window, clickPlace Order.
f Task 6: Explore the life cycle of a Web Forms page
1. Switch to Visual Studio 2010, with the AdventureWorks solution open.
• On the Windows taskbar, click AdventureWorks (Running) - Microsoft Visual Studio.
2. Open the Default.aspx Web Form in Code view.
• In Solution Explorer, right-click Default.aspx, and then click View Code.
3. Place a breakpoint at the beginning of the Page_Load method.
• In the Default.aspx.cs or Default.aspx.vb window, locate the Page_Load method, click the first
line of code, and then press F9.
4. Switch to Windows® Internet Explorer®.
• On the Windows taskbar, click http://localhost:xxxx/ThankYou.aspx – Windows InternetExplorer.
5. Open the Home page.
• In the http://localhost:xxxx/ThankYou.aspx – Windows Internet Explorer window, on the
menu, click Home.
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.
a. On the Debug menu, click Step Over, or press F10.
b. [Visual C#] Repeat step a six times.
[Visual Basic] Repeat step a four times.
7. Continue the web application.
• On the Debug menu, click Continue, or press F5.
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.
• In the Home Page – Windows Internet Explorer window, on the menu, click the Close button.
f Task 7: Open the AdventureWorksMvc solution in Visual Studio 2010
1. Open a second instance of Microsoft Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 230/449
4 Lab Answer Key: Overview of Web Application Architecture and Design
• On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Microsoft Visual C#® D:\Lab Files\CS\Lab 01\Starter\MVC
Microsoft Visual Basic® D:\Lab Files\VB\Lab 01\Starter\MVC
a. In the 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\Lab01\Starter\MVC\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab01\Starter\MVC\AdventureWorksMvc.sln, and then click Open.
f Task 8: Explore the life cycle of an MVC request
1. In the Controllers folder, open the HomeController.cs or HomeController.vb file.
• In Solution Explorer, expand Controllers, and then double-click HomeController.cs or
HomeController.vb.
2. Notice the methods that are available, and the way they relate to the actions that are available to the
user.
• In the HomeController.cs or HomeController.vb window, notice the Index and About action
methods.
3. Close the HomeController.cs or HomeController.vb file.
• In the HomeController.cs or HomeController.vb window, click the Close button.
4. Open the Global.asax file.
• In Solution Explorer, double-click Global.asax.
5. Place a breakpoint at the beginning of the Application_Start method.
• In the Global.asax.cs or Global.asax.vb window, locate the Application_Start method, click the
first line of code, and then press F9.
6. Run the AdventureWorksMvc solution in Debug mode.
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Debug menu, click
Start Debugging, or press F5.
Note: The debugger reaches the breakpoint in the Application_Start method.
Examine the static/Shared RegisterRoutes method.
a. In the Global.asax.cs or Global.asax.vb window, locate the RegisterRoutes method above the
Application_Start method.
b. Notice how the MapRoute method is used to register the Default route to map to the Home
controller and the Index action method.
7. Step through the web application startup until you reach the last line of code in the Index action
method of the Home controller.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 231/449
Lab Answer Key: Overview of Web Application Architecture and Design 5
a. On the Debug menu, click Step Over, or press F10.
b. [Visual C#] Repeat step a five times.
[Visual Basic] Repeat step a six times.
8. Continue the web application.
• On the Debug menu, click Continue, or press F5.
Note: The URL displayed in the address bar of Internet Explorer does not include the name of the
page (Index.aspx) displayed.
9. Close Windows Internet Explorer.
• In the Welcome to AdventureWorks – Windows Internet Explorer window, on the menu, click
the Close button.
Exercise 2: Comparing Web Forms and MVC
f Task 1: View the AdventureWorks solution in Visual Studio 2010• Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.
• On the Windows taskbar, click AdventureWorks - Microsoft Visual Studio.
f 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.
• In the Default.aspx.cs or Default.aspx.vb window, notice the code in the Page_Load event
handler, including the Page.IsPostBack property and the Response.Redirect method.
2. Examine the markup in the Default.aspx Web Form.
a. In Solution Explorer, double-click Default.aspx.
b. In the Default.aspx window, notice the markup, including the use of a master page, Content controls, and ListBox and Button server controls.
f Task 3: View AdventureWorksMvc solution in Visual Studio 2010
• Switch to the Visual Studio 2010 instance with the AdventureWorksMvc solution open.
• On the Windows taskbar, click AdventureWorksMvc - Microsoft Visual Studio.
f 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
Microsoft C#® D:\Lab Files\CS\Lab 01\Starter\MVC
Microsoft Visual Basic® D:\Lab Files\VB\Lab 01\Starter\MVC
2. Examine the code in the HomeController.cs or HomeController.vb code file.
• In the HomeController.cs or HomeController.vb window, notice the code in the Index and
About action methods, including how a view is returned.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 232/449
6 Lab Answer Key: Overview of Web Application Architecture and Design
3. Examine the markup in the Index.aspx page.
a. In Solution Explorer, expand Views, expand Home, and then double-click Index.aspx.
b. In the Index.aspx window, notice the markup, including the use of a master page, the Content controls, the pure select and input HTML controls, and the Html.BeginForm and Html.Encode
MVC helper methods.
f 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.
Exercise 3: Working with the Request Life Cycle
f Task 1: Explore the life cycle of a Web Forms page
1. Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.
• On the Windows taskbar, click AdventureWorks - Microsoft Visual Studio.
2. View the Default.aspx Web Form.
• If not already open and displayed, in Solution Explorer, double-click Default.aspx.
3. Locate the control with the label ASP:Content, which has 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.
• If not already open and displayed, in Solution Explorer, right-click Default.aspx, and then click
View Code.
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.
• On the Debug menu, click Start Without Debugging or click CTRL+F5.
Note: During the page’s Load event, the text is added to the lblAdvertisement Label control.
8. Close Windows Internet Explorer.
• In the Home Page – Windows Internet Explorer window, on the menu, click the Close button.
9. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 233/449
Lab Answer Key: Overview of Web Application Architecture and Design 7
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
f Task 2: Explore the life cycle of a MVC request
1. Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.
• On the Windows taskbar, click AdventureWorksMvc - Microsoft Visual Studio.
2. Open the Views\Home\Index.aspx view.
• In Solution Explorer, expand Views, expand Home, and then double-click Index.aspx.
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#]
ViewData["Advertisement"] = "My advertisement here";
[Visual Basic]
ViewData("Advertisement") = "My advertisement here"
8. Run the web application and view the rendered Index.aspx view.
• On the Debug menu, click Start Without Debugging or click CTRL+F5.
Note: During the controller’s Index action method, the text is added to Index view by using the
ViewData.
9. Close Windows Internet Explorer.
• In the Welcome to AdventureWorks – Windows Internet Explorer window, on the menu, click
the Close button.
10. Close Visual Studio 2010.
• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.
f 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 .
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 234/449
8 Lab Answer Key: Overview of Web Application Architecture and Design
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 235/449
Lab Answer Key: Designing a Web Application 1
Module 2
Lab Answer Key: Designing a Web Application
Contents:Exercise 1: Reviewing the Adventure Works Website Structure 2
Exercise 2: Redesign the AdventureWorks Website 2
Exercise 3: Add MVC Capabilities to the AdventureWorks Website 4
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 236/449
2 Lab Answer Key: Designing a Web Application
Lab 2: Redesigning the Adventure WorksWebsiteExercise 1: Review the Adventure Works Website Structure
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution at the following location.
Programming Language Location
Microsoft Visual C#® D:\Lab Files\CS\Lab 02\Solution\Exercise 01
Microsoft Visual Basic® D:\Lab Files\VB\Lab 02\Solution\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\Lab02\Solution\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 02\Solution\Exercise01\AdventureWorks.sln and then click Open.
f Task 2: Examine the code and markup location and purpose
f Analyze the solution and determine its intent and structure.
a. Expand and look at the content of various folders, Account, DataAccessLayer, and Styles.
b. Look at the various files in the root folder, including the Web Forms, master page, GlobalApplication class, Entity Data Model, and Web.config file(s).
f Task 3: Draw a diagram showing the overall architecture
• On a sheet of paper, draw a diagram describing the overall AdventureWorks website architecture,
based on your analysis.
f Task 4: Draw a diagram showing the page flow
• On a sheet of paper, draw a diagram showing the page flow of the AdventureWorks web application,
based on your analysis.
f Task 5: Discuss your findings with the class
• Discuss together with the class the diagrams created.
Exercise 2: Redesign the AdventureWorks Website
f Task 1: Read the requirements document
• The redesigned AdventureWorks web application must meet the requirements as set by
management, and as listed in the following sections.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 237/449
Lab Answer Key: Designing a Web Application 3
Business Requirements and Considerations
• Build a responsive, rich, and interactive UI
• Enhance the performance of existing pages and resolve errors
• Use URLs that are search engine friendly and facilitate indexing of products by search engines
• Include a section for blogs
• Include an administration section to enable the Sales team to manage information stored in the
database
• Secure the blog management pages and the administration section
Functional Requirements: Shopping Cart
• List product categories
• Click on a category to display products
• Display products in a detailed view
• Add products to the shopping cart
• Remove products from the shopping cart
• Submit the shopping cart
Functional Requirements: Blogs
• Log on to the website
• Add a new blog entry
• Edit and delete blog entries
• Add anonymous comments
• Approve comments
Functional Requirements: Administration Section• Log on to the website
• Manage products
• Manage product categories
• Manage sales order headers
• Manage customers
• User Interface Requirements
• Display a welcome message on the home page in English or French (Canada)
• Minimize page refreshes
• Provide support for easily changing the overall look of the application
• Reflect the corporate branding and propose two styles based on the corporate colors
• Display a marketing message on the Product Detail page
• Display a product advertisement on the blog pages
• Display a ticker showing biking-related news headlines on the blog pages
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 238/449
4 Lab Answer Key: Designing a Web Application
f Task 2: Determine which pages will use Web Forms and which will use MVC
• Based on the requirements given, determine and document which pages will remain as Web Forms
pages and which will be implemented in MVC.
f Task 3: Discuss your recommendations and their rationale with the class
• Discuss the recommendations created with the class.
Exercise 3: Add MVC Capabilities to the AdventureWorks Website
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution at the following location.
Programming Language Location
Microsoft Visual C#®
D:\Lab Files\CS\Lab 02\Starter\Exercise 03
Microsoft Visual Basic® D:\Lab Files\VB\Lab 02\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\Lab02\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 02\Starter\Exercise03\AdventureWorks.sln and then click Open.
f Task 2: Add required assemblies to the project
1. Add references to the System.Web.Abstractions assembly to the project.
a. In Solution Explorer, right-click AdventureWorks, and then click Add Reference.
b. Click.NET.
c. In the list, click System.Web.Abstractions, and then click OK .
2. Add references to the System.Web.MVC and System.Web.Routing assemblies to the project.
a. In Solution Explorer, right-click AdventureWorks, and then click Add Reference.
b. Click .NET.
c. In the list, click System.Web.MVC, press and hold down CTRL, click System.Web.Routing, and
then click OK .
f Task 3: Add the MVC Assembly references and namespaces to the Web.config file1. Open the Web.config file in the root AdventureWorks folder.
• In Solution Explorer, double-click Web.config.
2. Add the following text to your Web.config file in their proper sections as shown, this adds the
appropriate assemblies to your project and configures special MVC handlers:
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 239/449
Lab Answer Key: Designing a Web Application 5
...
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/><add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</assemblies></compilation>
...
<pages><namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/><add namespace="System.Web.Routing"/>
</namespaces>
</pages><httpHandlers>
<add verb="*" path="*.mvc" validate="false"
type="System.Web.Mvc.MvcHttpHandler"/>
</httpHandlers>
</system.web><system.webServer>
...<handlers>
<remove name="MvcHttpHandler"/>
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc"
type="System.Web.Mvc.MvcHttpHandler"/></handlers>
</system.webServer>
<runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31BF3856AD364E35"/><bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
a. In the Web.config file, locate the assemblies element in the compilation element.
<compilation ... targetFramework="4.0">
<assemblies>...
</assemblies>
</compilation>
b. Append the following markup to the assemblies element.
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
c. In the Web.config file, locate the closing system.web tag.
</system.web>
d. Add opening and closing pages tags, just before the closing system.web tag.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 240/449
6 Lab Answer Key: Designing a Web Application
<pages>
</pages>
</system.web>
e. Ad losing namespaces tags to the pages element.d opening and c
<pages>
<namespaces>
</namespaces></pages>
f. App following markup to the namespaces element.end the
<add namespace="System.Web.Mvc"/><add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
g. Ad ust before the closing system.web tag.d opening and closing httpHandlers tags, j
<httpHandlers>
</httpHandlers></system.web>
h. App ng markup to the httpHandlers element.end the followi
<add verb="*" path="*.mvc" validate="false"type="System.Web.Mvc.MvcHttpHandler"/>
i. In the ebServer tag.Web.config file, locate the closing system.w
</system.webServer>
j. App p to the system.webServer element.end the following marku
<system.webServer><handlers>
<remove name="MvcHttpHandler"/><add name="MvcHttpHandler" preCondition="integratedMode" verb="*"
path="*.mvc" type="System.Web.Mvc.MvcHttpHandler"/>
</handlers>
</system.webServer>
k. Ad runtime tags, just before the closing configuration tag.d opening and closing
<runtime>
</runtime>
</configuration>
l. App markup to the runtime element.end the following
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly><assemblyIdentity name="System.Web.Mvc" publicKeyToken="31BF3856AD364E35"/>
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 241/449
Lab Answer Key: Designing a Web Application 7
3. Save ig file.
• In the Web.config window, on the File menu, click Save Web.config, or press CTRL+S.
4. The final Web.config file should appear as follows:
the Web.conf
[Visual C#]
<?xml version="1.0"?>
<configuration><appSettings />
<connectionStrings><add name="ApplicationServices" connectionString="data
source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"providerName="System.Data.SqlClient" />
<add name="AdventureWorksEntities"
connectionString="metadata=res://*/mdlAdventureWorks.csdl|res://*/mdlAdventureWorks.ssdl|res://*/mdlAdventureWorks.msl;provider=System.Data.SqlClient;provider connection
string="Data Source=.\sqlexpress;Initial
Catalog=AdventureWorksLT2008R2;IntegratedSecurity=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web><compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/></assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication><membership>
<providers><clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"connectionStringName="ApplicationServices" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="false" maxInvalidPasswordAttempts="5"minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" applicationName="/" />
</providers></membership>
<profile>
<providers><clear />
<add name="AspNetSqlProfileProvider"
type="System.Web.Profile.SqlProfileProvider"connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false"><providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices" applicationName="/" />
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 242/449
8 Lab Answer Key: Designing a Web Application
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /></providers>
</roleManager>
<pages><namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/><add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
</namespaces></pages>
<httpHandlers>
<add verb="*" path="*.mvc" validate="false"
type="System.Web.Mvc.MvcHttpHandler"/></httpHandlers>
</system.web>
<system.webServer><modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="MvcHttpHandler"/>
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc"
type="System.Web.Mvc.MvcHttpHandler"/></handlers>
</system.webServer><runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31BF3856AD364E35"/><bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding></runtime>
</configuration>
[Visual Basic]
<?xml version="1.0" encoding="utf-8"?>
<!--For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
--><configuration>
<connectionStrings>
<add name="ApplicationServices" connectionString="datasource=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" /><add name="AdventureWorksEntities"
connectionString="metadata=res://*/mdlAdventureWorks.csdl|res://*/mdlAdventureWorks.s
sdl|res://*/mdlAdventureWorks.msl;provider=System.Data.SqlClient;provider connectionstring="Data Source=.\sqlexpress;Initial
Catalog=AdventureWorksLT2008R2;IntegratedSecurity=True;MultipleActiveResultSets=True""providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web><compilation debug="true" strict="false" explicit="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 243/449
Lab Answer Key: Designing a Web Application 9
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/><add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</assemblies></compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" /></authentication>
<membership>
<providers><clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="ApplicationServices" enablePasswordRetrieval="false"enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="false" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers><clear />
<add name="AspNetSqlProfileProvider"type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile><roleManager enabled="false">
<providers>
<clear /><add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider"type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages><namespaces>
<add namespace="System.Web.Mvc"/><add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/></namespaces>
</pages>
<httpHandlers><add verb="*" path=".mvc" validate="false"
type="System.Web.Mvc.MvcHttpHandler"/>
</httpHandlers></system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers><remove name="MvcHttpHandler"/>
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path=".mvc"
type="System.Web.Mvc.MvcHttpHandler"/></handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" PublicKeyToken="31BF3856AD364E35"/>
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 244/449
10 Lab Answer Key: Designing a Web Application
</dependentAssembly>
</assemblyBinding></runtime>
</configuration>
f Task 4: Map the default MVC request routes
outing namespaces in Global.asax to support1. Import the System.Web.Mvc and System.Web.RMVC request routing.
[Visual C#]
using System.Web.Mvc;
using System.Web.Routing;
[Visual Basic]Imports System.Web.Mvc
Imports System.Web.Routing
a. lick Global.asax.
, at the very top, type the following code.
In Solution Explorer, double-c
b. In the Global.asax.cs or Global.asax.vb window
[Visual C#]
using System.Web.Mvc;
using System.Web.Routing;
[Visual Basic] Imports System.Web.Mvc Imports System.Web.Routing
2. Creat tes to register the MVC routes and exclude routes for existinge a method named RegisterRouWeb Form pages, handlers, and WCF services.
[Visual C#] public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");routes.IgnoreRoute("{resource}.svc/{*pathInfo}");
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults);
}
[Visual Basic] Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")routes.IgnoreRoute("{resource}.aspx/{*pathInfo}")
routes.IgnoreRoute("{resource}.svc/{*pathInfo}")
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 245/449
Lab Answer Key: Designing a Web Application 11
New With {.controller = "Home", .action = "Index", .id = ""}
)
End Sub
• asax.cs or Global.asax.vb window, in the Global_asax class, type the followingIn the Global.code.
[Visual C#]
public static void RegisterRoutes(RouteCollection routes)
{routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.svc/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parametersnew { controller = "Home", action = "Index", id = "" } // Parameter
defaults
);
}
[Visual Basic]
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}")routes.IgnoreRoute("{resource}.svc/{*pathInfo}")
routes.MapRoute("Default",
"{controller}/{action}/{id}",
New With {.controller = "Home", .action = "Index", .id = ""}
)
End Sub
3. Call t Routes in the Application_Start method.he Register
[Visual C#] protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
[Visual Basic] Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RegisterRoutes(RouteTable.Routes)
End Sub
• asax.cs or Global.asax.vb window, in the Application_Start method, type theIn the Global.following code.
[Visual C#]
RegisterRoutes(RouteTable.Routes);
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 246/449
12 Lab Answer Key: Designing a Web Application
RegisterRoutes(RouteTable.Routes)
4. Save the Global.asax file.
In the Global.asax.cs or Global.asax.vb window, on the File menu, click Save Global.asax.cs or
Task 5: Change project to reflect an MVC Project
Works.vbproj file in Notepad for direct
a. In Solution Explorer, right-click AdventureWorks, and then click Open Folder in Windows
b. In Windows Explorer, right-click AdventureWorks.csproj or AdventureWorks.vbproj , point to
c. In the Open with dialog box, expand Other programs, select Notepad, clear the Always use
2. Locate the ProjectTypeGuids element.
•
Save Global.asax.vb, or press CTRL+S.
f 1. Open the project, AdventureWorks.csproj or Adventure
editing.
Explorer.
Open with, and then click Choose default program.
the selected program to open this kind of file check box, and then click OK .
[Visual C#]
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-
00c04f79efbc}</ProjectTypeGuids>
[Visual Basic]<ProjectTypeGuids{349c5851-65df-11da-9384-00065b846f21};{F184B08F-C81C-45F6-A57F-
5ABD9991F28F}</ProjectTypeGuids>
• In the AdventureWorks.csproj - Notepad or AdventureWorks.vbproj - Notepad window,
locate the ProjectTypeGuids element at the top of the project file.
[Visual C#]
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-
bf4b-00c04f79efbc}</ProjectTypeGuids>
[Visual Basic]<ProjectTypeGuids{349c5851-65df-11da-9384-00065b846f21};{F184B08F-C81C-45F6-A57F-
5ABD9991F28F}</ProjectTypeGuids>
3. Add the following markup at the beginning of the ProjectTypeGuids element.
{F85E285D-A4E0-4152-9332-AB1D724D3325};
Note: The top of the project file should look like this.
[Visual C#]<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><PropertyGroup>
...
<ProjectGuid>{A8D6241C-680E-42BA-884B-501CC08D3FA9}</ProjectGuid>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 247/449
Lab Answer Key: Designing a Web Application 13
<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-
9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>...
[Visual Basic]
<?xml version="1.0" encoding="utf-8"?><Project ToolsVersion="4.0" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>...
<ProjectGuid>{F9BE0786-D923-4DF0-9483-CE13D5D26A1F}</ProjectGuid>
<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325{349c5851-65df-11da-9384-00065b846f21};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
...
4. Save the project file.
In the AdventureWorks.csproj - Notepad or AdventureWorks.vbproj - Notepad window, on
5. Reload the AdventureWorks project.
In the File Modification Detected dialog box, click the Reload button.
6. Test the new project type by opening the Add New Item dialog box.
In Solution Explorer, right-click AdventureWorks, point to Add, and then click New Item, or
In the Add New Item - AdventureWorks dialog box, notice the addition of the MVC2 project
In the Add New Item - AdventureWorks dialog box, click Cancel.
7. Close Visual Studio 2010.
In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Task 6: Turn off the virtual machine and revert the changes
ht-click 10264A-GEN-DEV, and
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.
•
the File menu, click Save, or press CTRL+S.
•
•
press CTRL+SHIFT+A.
•
item templates.
•
•
f 1. In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, rig
then click Turn Off .
Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 248/449
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 249/449
2 Lab Answer Key: Developing MVC Models
Lab 3: Creating MVC ModelsExercise 1: Exploring the AdventureWorks Database
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
3. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Visual C#® D:\Lab Files\CS\Lab 03\Starter\Exercise 01
Visual Basic® D:\Lab Files\VB\Lab 03\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\Lab03\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 03\Starter\Exercise01\AdventureWorksMvc.sln and then click Open.
f Task 2: Open the AdventureWorks database
• Open the AdventureWorksLT2008R2 database by using Server Explorer.
a. In the AdventureWorksMvc – Microsoft Visual Studio window, on the View menu, click
Server Explorer, or press CTRL+ALT+S.
b.
In Server Explorer, right-click Data Connections, and then click Add Connection.c. In the Choose Data Source dialog box, in the Data source list, click SQL Server, and then click
Continue.
d. In the Add Connection dialog box, in the Server name box, type 10264A-GEN-DEV\SQLExpress, in the Select or enter a database name list, click
AdventureWorksLT2008R2, and then click OK .
e. In Server Explorer, expand 10264a-gen-dev\sqlexpress.AdventureWorksLT2008R2.SalesLT.
f Task 3: Examine the table schemas
1. Display the list of tables.
• In Server Explorer, expand Tables.
2. Open the Customer (SalesLT) table in the Table Designer.
• Right-click Customer (SalesLT), and then click Open Table Definition.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 250/449
Lab Answer Key: Developing MVC Models 3
3. Examine the schema of the table.
4. Close the Table Designer.
• In the SalesLT.Customer: Table(10264a-gen-dev\sqlexpress.AdventureWorksLT2008R2) window, click the Close button.
f Task 4: Add relationships between tables using Diagrams
1. Create a new database diagram containing the Customer and CustomerAddress tables.
a. In Server Explorer, right-click Database Diagrams, and then click Add New Diagram.
b. In the Microsoft Visual Studio dialog box, click Yes.
c. In the Add Table dialog box, click Customer, press and hold down CTRL, click
CustomerAddress, and then click Add.
d. Click Close.
Note: The relationship between the Customer and CustomerAddress table is one-to-many, which
means that a single customer can have multiple addresses.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 251/449
4 Lab Answer Key: Developing MVC Models
2. Close the Database Designer and do not save the diagram.
a. In the 10264A-GEN-DEV\Student.Diagram1: Diagram(10264a-gev-dev\sqlexpress.AdventureWorksLT2008R2) window, click the Close button.
b. In the Microsoft Visual Studio dialog box, click No.
3. Close Visual Studio 2010.
• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.
Exercise 2: Adding an ADO.NET Entity Data Model
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 03\Starter\Exercise 02
Visual Basic D:\Lab Files\VB\Lab 03\Starter\Exercise 02
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 252/449
Lab Answer Key: Developing MVC Models 5
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\Lab03\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 03\Starter\Exercise02\AdventureWorksMvc.sln and then click Open.
f Task 2: Add Entity Data Model to the web application1. Add a new ADO.NET Entity Data Model named AdventureWorks.edmx to the project, and then
generate the model from database. The model must be added to the Models folder.
a. In Solution Explorer, right-click Models, point to Add, and then click New Item.
b. In the Add New Item – AdventureWorksMvc dialog box, in the left pane, click Data.
c. In the middle pane, click ADO.NET Entity Data Model, in the Name box, type
AdventureWorks.edmx, and then click Add.
d. In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate fromdatabase, and then click Next.
2. Use the existing AdventureWorksLT2008ConnectionString connection string to connect to the
database, and save the connection settings in the Web.config file as AdventureWorksEntities.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 253/449
6 Lab Answer Key: Developing MVC Models
• On the Choose Your Data Connection page, in the Which data connection should yourapplication use to connect to the database? list, click
AdventureWorksLT2008ConnectionString (Settings), in the Save entity connection settings
in Web.config as box, type AdventureWorksEntities, and then click Next.
3. Select the Blog and Blogger tables from the database and name the model namespace
AdventureWorksModel.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 254/449
Lab Answer Key: Developing MVC Models 7
• On the Choose Your Database Objects page, in the Which database objects do you want toinclude in your model list, expand Tables, select the Blog and Blogger check boxes, in the
Model Namespace box, type AdventureWorksModel, and then click Finish.
4. Build the solution, and fix any errors.
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click BuildSolution, or press CTRL+SHIFT+B.
f Task 3: Add data repository
• Add a new data repository class named BlogRepository to the Models folder.
a. In Solution Explorer, right-click Models, point to Add, and then click New Item.
b. In the Add New Item – AdventureWorksMvc dialog box, in the left pane, click Visual C# or
Visual Basic.
c. In the middle pane, click Class, in the Name box, type BlogRepository, and then click Add.
f Task 4: Implement list, select, insert, update, and delete operations
1. Declare and instantiate a private AdventureWorksEntities object named db in the BlogRepository
class.
[Visual C#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 255/449
8 Lab Answer Key: Developing MVC Models
private AdventureWorksEntities db = new AdventureWorksEntities();
[Visual Basic]
Private db As New AdventureWorksEntities
a. In the BlogRepository.cs or BlogRepository.vb window, at the top of the BlogRepository class, type the following code.
[Visual C#]
private AdventureWorksEntities db = new AdventureWorksEntities();
[Visual Basic]
Private db As New AdventureWorksEntities
2. Add the following method to the BlogRepository class to return a list of all of the blogs.
[Visual C#]
public IQueryable<Blog> GetAllBlogs(){
return db.Blogs;
}
[Visual Basic]
Public Function GetAllBlogs() As IQueryable(Of Blog)Return db.Blogs
End Function
3. Add the following method to the BlogRepository class to return a list of all of the blogs for a specific
blogger.
[Visual C#]
public IQueryable<Blog> GetAllBlogs(int id)
{
return from blog in db.Blogswhere blog.BloggerID == id
select blog;
}
[Visual Basic]
Public Function GetAllBlogs(ByVal id As Integer) As IQueryable(Of Blog)
Return From blog In db.Blogs
Where blog.BloggerID = id
Select blogEnd Function
4. Add the following method to the BlogRepository class to return a specific blog.
[Visual C#]
public Blog GetBlog(int id)
{
return (from blog in db.Blogs
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 256/449
Lab Answer Key: Developing MVC Models 9
where blog.BlogID == id
select blog).SingleOrDefault();
}
[Visual Basic]
Public Function GetBlog(ByVal id As Integer) As Blog
Return (From blog In db.Blogs
Where blog.BlogID = idSelect blog).SingleOrDefault()
End Function
5. Add the following method to the BlogRepository class to return the name of the blogger.
[Visual C#]
public string GetBloggerName(int id){
var bloggerName = (from blogger in db.Bloggers
where blogger.BloggerID == id
select blogger.Name).FirstOrDefault();
return bloggerName;
}
[Visual Basic]
Public Function GetBloggerName(ByVal id As Integer) As StringDim bloggerName = (From blogger In db.Bloggers
Where blogger.BloggerID = id
Select blogger.Name).FirstOrDefault
Return bloggerName
End Function
6. Add the following methods to the BlogRepository class to add, update, delete, and save individual
blogs.
[Visual C#]
public void AddBlog(Blog blog)
{db.Blogs.AddObject(blog);
}
public void UpdateBlog(Blog blog)
{
db.Blogs.ApplyCurrentValues(blog);
}
public void DeleteBlog(Blog blog)
{db.Blogs.DeleteObject(blog);
}
public void Save()
{
db.SaveChanges();
}
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 257/449
10 Lab Answer Key: Developing MVC Models
Public Sub AddBlog(ByVal blg As Blog)
db.Blogs.AddObject(blg)End Sub
Public Sub UpdateBlog(ByVal blg As Blog)db.Blogs.ApplyCurrentValues(blg)
End Sub
Public Sub DeleteBlog(ByVal blg As Blog)
db.Blogs.DeleteObject(blg)
End Sub
Public Sub Save()
db.SaveChanges()
End Sub
7. Save all modified files.
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the File menu, click SaveAll, or press CTRL+SHIFT+S.
8. Close Visual Studio 2010.
• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.
Exercise 3: Model Data Validation
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution at the following location.
Programming Language Location
Visual C# D:\Lab Files\CS\Lab 03\Starter\Exercise 03
Visual Basic D:\Lab Files\VB\Lab 03\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\Lab03\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 03\Starter\Exercise03\AdventureWorksMvc.sln and then click Open.
f Task 2: Add a partial class to the Models folder
1. Add a new class named Blog to the Models folder.
a. In Solution Explorer, right-click Models, point to Add, and then click New Item.
b. In the Add New Item – AdventureWorksMvc dialog box, in the left pane, click Visual C# or
Visual Basic.
c. In the middle pane, click Class, in the Name box, type Blog, and then click Add.
2. Make the Blog class partial, by prefixing with the keyword partial / Partial.
[Visual C#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 258/449
Lab Answer Key: Developing MVC Models 11
public partial class Blog
[Visual Basic]
Partial Public Class Blog
3. Import the System.ComponentModel and System.ComponentModel.DataAnnotations namespaces.
[Visual C#]
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
[Visual Basic]
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel
a. In the Blog.cs or Blog.vb window, add the following code at the top.
[Visual C#]
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
[Visual Basic]
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel
f Task 3: Add business rules validation
1. Add another class named BlogMetadata to the Blog.cs or Blog.vb code file.
[Visual C#]
public class Blog_MetaData{
[DisplayName("Blog ID")]
public object BlogID { get; set; }
[DisplayName("Date Posted")]
[DisplayFormat(DataFormatString = "{0:d}")]
public object DatePosted { get; set; }
[Required]
public object Title { get; set; }
[Required]
[DisplayName("Blog Entry")]
public object BlogEntry { get; set; }
}
[Visual Basic]
Public Class Blog_MetaData
<DisplayName("Blog ID")>
Public Property BlogID As Object
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 259/449
12 Lab Answer Key: Developing MVC Models
<DisplayName("Date Posted")>
<DisplayFormat(DataFormatString:="{0:d}")>Public Property DatePosted As Object
<Required()>Public Property Title As Object
<Required()> <DisplayName("Blog Entry")>Public Property BlogEntry As Object
End Class
• In the Blog.cs or Blog.vb window, add the following code at the bottom.
[Visual C#]
public class Blog_MetaData{
[DisplayName("Blog ID")]
public object BlogID { get; set; }
[DisplayName("Date Posted")]
[DisplayFormat(DataFormatString = "{0:d}")]
public object DatePosted { get; set; }
[Required]
public object Title { get; set; }
[Required]
[DisplayName("Blog Entry")]
public object BlogEntry { get; set; }
}
[Visual Basic]
Public Class Blog_MetaData
<DisplayName("Blog ID")>
Public Property BlogID As Object
<DisplayName("Date Posted")>
<DisplayFormat(DataFormatString:="{0:d}")>Public Property DatePosted As Object
<Required()>Public Property Title As Object
<Required()> <DisplayName("Blog Entry")>Public Property BlogEntry As Object
End Class
2. Apply the MetadataType attribute to the Blog class, and reference the Blog_Metadata type as the
[Visual C#]
metadata type.
[MetadataType(typeof(Blog_MetaData))]
public partial class Blog
[Visual Basic]
<MetadataType(GetType(Blog_MetaData))>
Partial Public Class Blog
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 260/449
Lab Answer Key: Developing MVC Models 13
• indow, add the following above the class declaration.In the Blog.cs or Blog.vb w
[Visual C#]
[MetadataType(typeof(Blog_MetaData))]
public partial class Blog
[Visual Basic]
<MetadataType(GetType(Blog_MetaData))>
Partial Public Class Blog
3. B
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click BuildB.
• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.
1. In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
uild the solution, and fix any errors.
Solution, or press CTRL+SHIFT+
4. Close Visual Studio 2010.
f Task 4: Turn off the virtual machine and revert the changes
then click Turn Off .
2. In the Turn Off Machine dialog box, click Turn Off .
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 261/449
Lab Answer Key: Developing MVC Controllers 1
Module 4
Lab Answer Key: Developing MVC Controllers
Contents:Exercise 1: Creating an MVC Controller 2
Exercise 2: Adding code to list the existing blog entries 3
Exercise 3: Adding code to create a new blog entry 7
Exercise 4: Adding code to edit a blog entry 10
Exercise 5: Adding code to delete a blog entry 14
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 262/449
2 Lab Answer Key: Developing MVC Controllers
Lab 4: Developing MVC ControllersExercise 1: Creating an MVC Controller
f 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 Studio2010, 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\Lab04\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise01\AdventureWorksMvc.sln and then click Open.
f 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()>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 263/449
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 FunctionEnd Class
End Namespace
4. Build the solution, and fix any errors.
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click BuildSolution, 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
f 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 Studio2010, 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 264/449
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\Lab04\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise02\AdventureWorksMvc.sln and then click Open.
f 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()
f 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()
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 265/449
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
f 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);
}
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 266/449
6 Lab Answer Key: Developing MVC Controllers
[Visual Basic]
Function Blogger(ByVal id As Integer) As ActionResultDim blogs = blogRepository.GetAllBlogs(id)
Return View(blogs)
End Function
f 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 267/449
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.
•
Solution, or press CTRL+SHIFT+B.
•
f 1. Open Microsoft Visual Studio 2010.
•
2010, and then click Microsoft Visual Studio 2010.
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
a. In the Start Page – Microsoft Visual Studio en Project, or
og box, in the File name box, type D:\Lab Files\CS\Labarter\Exercise
Task 2: Create a Create action method
ntroller class.
window, on the File menu, click Oppress CTRL+SHIFT+O.
b. In the Open Project dial
04\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\St03\AdventureWorksMvc.sln and then click Open.
f 1. Add a Create action method in the BlogCo
[Visual C#]
public ActionResult Create()
{
}
[Visual Basic]
Function Create() As ActionResult
End Function
a. In Solution Explorer, expand Controllers, and then double-click BlogController.cs or
r code file, add the following method to the BlogController class.
BlogController.vb.
b. In the BlogControlle
[Visual C#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 268/449
8 Lab Answer Key: Developing MVC Controllers
public ActionResult Create()
{
}
[Visual Basic]
Function Create() As ActionResultEnd 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
f 1. Add a Create action method for an HTTP Post request that takes a Blog oTask 3: Create a Create action method for an HTTP Post request
bject as the only parameter.
[Visual C#]
[HttpPost]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
{
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 269/449
Lab Answer Key: Developing MVC Controllers 9
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.NowblogRepository.AddBlog(blg)
blogRepository.Save()
TempData("ConfirmationMessage") = blg.Title & " has been added"
Return RedirectToAction("Index")
CatchReturn 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();
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 270/449
10 Lab Answer Key: Developing MVC Controllers
Try
blg.DatePosted = DateTime.NowblogRepository.AddBlog(blg)
blogRepository.Save()
TempData("ConfirmationMessage") = blg.Title & " has been added"
Return RedirectToAction("Index")Catch
Return View(blg)
End TryEnd If
Return View(blg)
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 4: Adding code to edit a 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.
•
Solution, or press CTRL+SHIFT+B.
•
f 1. Open Microsoft Visual Studio 2010.
•
2010, and then click Microsoft Visual Studio 2010.
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
a. In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project, or
og box, in the File name box, type D:\Lab Files\CS\Labarter\Exercise
Task 2: Create an Edit action method
ID of a blog entry as the only parameter. The method
press CTRL+SHIFT+O.
b. In the Open Project dial
04\Starter\Exercise 04\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\St04\AdventureWorksMvc.sln and then click Open.
f 1.
Add an Edit action method that takes theshould be added to the BlogController class.
[Visual C#]
public ActionResult Edit(int id)
{
}
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 271/449
Lab Answer Key: Developing MVC Controllers 11
Function Edit(ByVal id As Integer) As ActionResult
End Function
a. In Solution Explorer, expand Controllers, and then double-click BlogController.cs or
b. In the BlogController code file, add the following method to the BlogController class.
BlogController.vb.
[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);
if (blog == null)
return RedirectToAction("Index");
return View(blog);}[Visual Basic]
Function Edit(ByVal id As Integer) As ActionResultDim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing ThenReturn RedirectToAction("Index")
End If
Return View(blogEntry)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 272/449
12 Lab Answer Key: Developing MVC Controllers
End Function
f 1. Add an Edit action method for an HTTP Post request that takes the ID o
Task 3: Create an Edit action method for an HTTP Post request
f 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)
If blogEntry Is Nothing ThenReturn RedirectToAction("Index")
End If
Try
UpdateModel(blogEntry, collection.ToValueProvider())
blogRepository.UpdateBlog(CType(blogEntry, Blog))blogRepository.Save()
TempData("ConfirmationMessage") = blogEntry.Title & " has been updated"
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 273/449
Lab Answer Key: Developing MVC Controllers 13
Return RedirectToAction("Index")
CatchReturn 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
ActionResultDim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing ThenReturn RedirectToAction("Index")
End If
TryUpdateModel(blogEntry, collection.ToValueProvider())
blogRepository.UpdateBlog(CType(blogEntry, Blog))
blogRepository.Save()
TempData("ConfirmationMessage") = blogEntry.Title & " has been updated"
Return RedirectToAction("Index")
CatchReturn View(blogEntry)
End Try
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.
•
Solution, or press CTRL+SHIFT+B.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 274/449
14 Lab Answer Key: Developing MVC Controllers
• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.
Ex
al Studio 2010
EN-DEV, point to All Programs, click Microsoft Visual Studio
location.
ercise 5: Adding code to delete a blog entry
f Task 1: Open the AdventureWorksMvc solution in Visu
1. Open Microsoft Visual Studio 2010.
• On the Start menu of 10264A-G
2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the following
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
I ge – Microsoft Visual Stud oject, or press
f Task 2
a blog entry as the only parameter. The method
n the Start Pa io window, on the File menu, click Open Pr
CTRL+SHIFT+O.
In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab 04\Starter\Exercise
05\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise
05\AdventureWorksMvc.sln and then click Open.
: Create a Delete action method
1. Add a Delete action method that takes the ID of
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
a. er, expand Controllers, and then double-click BlogController.cs or
r code file, add the following method to the BlogController class.
In Solution Explor
BlogController.vb.
b. In the BlogControlle
[Visual C#]
public ActionResult Delete(int id)
{
}
[Visual Basic]
Function Delete(ByVal id As Integer) As ActionResult
End Function
2. Add co action method to redirect to the Index view.de to the Delete
[Visual C#]
var blog = blogRepository.GetBlog(id);
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 275/449
Lab Answer Key: Developing MVC Controllers 15
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. V ction method matches the following code.erify that the final Delete a
[Visual C#]
public ActionResult Delete(int id)
{
var blog = blogRepository.GetBlog(id);
if (blog == null)
return RedirectToAction("Index");
return View(blog);
}
[Visual Basic]
Function Delete(ByVal id As Integer) As ActionResultDim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing Then
Return RedirectToAction("Index")End If
Return View(blogEntry)
End Function
f Task 3: Create a Delete action method for an HTTP Post request
f the blog entry and a1. Add a Delete action method for an HTTP Post request that takes the ID o
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 276/449
16 Lab Answer Key: Developing MVC Controllers
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")
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 ActionResultDim blogEntry = blogRepository.GetBlog(id)
If blogEntry Is Nothing ThenReturn RedirectToAction("Index")
End If
blogRepository.DeleteBlog(CType(blogEntry, Blog))
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 277/449
Lab Answer Key: Developing MVC Controllers 17
blogRepository.Save()
TempData("ConfirmationMessage") = blogEntry.Title & " has been deleted."
Return RedirectToAction("Index")
End Function
4. Build the solution, and fix any errors.
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click BuildSolution, or press CTRL+SHIFT+B.
5. Close Visual Studio 2010.
• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.
f 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 clickRevert.
4. In the Revert Virtual Machine dialog box, click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 278/449
Lab Answer Key: Developing MVC Views 1
Module 5
Lab Answer Key: Developing MVC Views
Contents:Exercise 1: Develop a List MVC View 4
Exercise 2: Develop a Details MVC view 5
Exercise 3: Develop a Create MVC view 7
Exercise 4: Develop an Edit MVC view 13
Exercise 5: Develop a Delete MVC view 19
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 279/449
2 Lab Answer Key: Developing MVC Views
Lab 5: Developing MVC ViewsExercise 1: Develop a List MVC View
f 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 Studio2010, 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\Lab05\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise01\AdventureWorksMvc.sln and then click Open.
f 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">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 280/449
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>
f 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%>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 281/449
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 BuildSolution, or press CTRL+SHIFT+B.
f 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®.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 282/449
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
f 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 Studio2010, 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\Lab05\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise02\AdventureWorksMvc.sln and then click Open.
f 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 astrongly-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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 283/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 284/449
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
f 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 Studio2010, 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\Lab05\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise03\AdventureWorksMvc.sln and then click Open.
f 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)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 285/449
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))" %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 286/449
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>
f 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 theBlog 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 astrongly-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" /><% } %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 287/449
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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 288/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 289/449
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.
f 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))" %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 290/449
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
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorksMvc solution from the following location.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 291/449
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\Lab05\Starter\Exercise 04\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\Starter\Exercise04\AdventureWorksMvc.sln and then click Open.
f Task 2: Create a partial view named Blog
1. Build the solution.
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click BuildSolution, 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" />
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 292/449
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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 293/449
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(OfAdventureWorksMvc.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>
f 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]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 294/449
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>
f 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.
•
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 295/449
18 Lab Answer Key: Developing MVC Views
f Task 5: Update the Create view to use the Blog partial view.
Content element in the Create 1. Replace the markup and code after the h2 element in the Content2view with the following.
[Visual C#]
<% Html.RenderPartial("Blog"); %>
[Visual Basic]
<% Html.RenderPartial("Blog") %>
a. Visual Studio window, click Create.aspx.
g the Content
In the AdventureWorks – Microsoft
b. Select the markup and code from immediately after the h2 element, till the closin
element, and then type the following.
[Visual C#]
<% Html.RenderPartial("Blog"); %>
[Visual Basic]
<% Html.RenderPartial("Blog") %>
2. Verify e view matches the following.that the markup and code in the Creat
[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>
<% 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">
Create</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
runat="server">
<h2>
Create</h2>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 296/449
Lab Answer Key: Developing MVC Views 19
<% Html.RenderPartial("Blog")%>
</asp:Content>
3. Run the application.
a. In Solution Explorer, click AdventureWorksMvc.
b. In the AdventureWorksMvc – Microsoft Visual Studio window, on the Debug menu, click
4. 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
5. 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 Yet Another Entry,
c. If the AutoComplete dialog box appears, in the AutoComplete dialog box, click No.
6. Close Internet Explorer.
In the Index – Windows Internet Explorer window, click the Close button.
7. Close Visual Studio 2010.
In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.
Exercise 5: Develop a Delete MVC view
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.
Programming Language Location
in the Blog Entry box, type This is yet another blog entry, and then click Submit.
•
•
f 1. Open Microsoft Visual Studio 2010.
•
2010, and then click Microsoft Visual Studio 2010.
Visual C# D:\Lab Files\CS\Lab 05\Starter\Exercise 05
Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 05
a. In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project, or
og box, in the File name box, type D:\Lab Files\CS\Labarter\Exercise
press CTRL+SHIFT+O.
b. In the Open Project dial
05\Starter\Exercise 05\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 05\St05\AdventureWorksMvc.sln and then click Open.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 297/449
20 Lab Answer Key: Developing MVC Views
f Task 2: Add a strongly-typed view named Delete that uses the default markup provided
by the Add View dialog box
1. Build the solution.
• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click BuildSolution, or press CTRL+SHIFT+B.
2. Add a delete, strongly-typed view of type Blog, named Delete, based on the Site.Master master
page, to the Blog folder. The view should use the default content supplied for a Delete operation.
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 Delete, select the Create astrongly-typed view check box, in the View data class list, click
AdventureWorksMvc.Models.Blog, in the View content list, click Delete, and then click Add.
-or-
[Visual Basic] In the Add View dialog box, in the View name box, type Delete, select the
Create a strongly-typed view check box, in the View data class list, click
AdventureWorksMvc.Blog, in the View content list, click Delete, and then click Add.
3. Update the markup and code that renders the Back to List link to match the following.
<%: Html.ActionLink("Back to List", "Blogger") %>
a. In the Delete.aspx window, locate the call to the Html.ActionLink method at the bottom of the
markup.
b. Select the following markup and code.
<%: Html.ActionLink("Back to List", "Index") %>
c. Replace the selected text with the following.
<%: Html.ActionLink("Back to List", "Blogger") %>
4. Verify that the markup and code in the Delete 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">
Delete</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Delete</h2><h3>
Are you sure you want to delete this?</h3>
<fieldset><legend>Fields</legend>
<div class="display-label">
BlogID</div><div class="display-field">
<%: Model.BlogID %></div>
<div class="display-label">BloggerID</div>
<div class="display-field">
<%: Model.BloggerID %></div>
<div class="display-label">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 298/449
Lab Answer Key: Developing MVC Views 21
DatePosted</div>
<div class="display-field"><%: String.Format("{0:g}", Model.DatePosted) %></div>
<div class="display-label">
Title</div><div class="display-field">
<%: Model.Title %></div>
<div class="display-label">BlogEntry</div>
<div class="display-field">
<%: Model.BlogEntry %></div></fieldset>
<% using (Html.BeginForm())
{ %>
<p><input type="submit" value="Delete" />
|
<%: Html.ActionLink("Back to List", "Blogger") %></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">Delete
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Delete</h2>
<h3>
Are you sure you want to delete this?</h3><fieldset>
<legend>Fields</legend>
<div class="display-label">
BlogID</div><div class="display-field">
<%: Model.BlogID %></div>
<div class="display-label">BloggerID</div>
<div class="display-field">
<%: Model.BloggerID %></div><div class="display-label">
DatePosted</div>
<div class="display-field"><%: String.Format("{0:g}", Model.DatePosted) %></div>
<div class="display-label">
Title</div><div class="display-field">
<%: Model.Title %></div><div class="display-label">
BlogEntry</div>
<div class="display-field">
<%: Model.BlogEntry %></div></fieldset>
<% Using Html.BeginForm()%>
<p><input type="submit" value="Delete" />
|
<%: Html.ActionLink("Back to List", "Blogger") %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 299/449
22 Lab Answer Key: Developing MVC Views
</p>
<% End Using%>
</asp:Content>
f 1. Run the application.
Task 3: Delete 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. Select a blog entry.
a. In the Blogger – Windows Internet Explorer window, next to the first blog entry from the top,
b. In the Delete – Windows Internet Explorer window, click Delete.
4. l se Internet Explorer.
In the Index – 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 4: Turn off the virtual machine and revert the changesht-click 10264A-GEN-DEV, and
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.
click Delete.
C o
•
•
f 1. In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, rig
then click Turn Off .
Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 300/449
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 301/449
2 Lab Answer Key: Designing for Discoverability
Lab 6: Designing for DiscoverabilityExercise 1: Mapping URLs of Web Forms Pages
f 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#® D:\Lab Files\CS\Lab 06\Starter\Exercise 01
Visual Basic® D:\Lab Files\VB\Lab 06\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\Lab06\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 06\Starter\Exercise01\AdventureWorks.sln and then click Open.
f Task 2: Add and verify a reference to the System.Web.Routing assembly
1. Add reference to the System.Web.Routing assembly.
a. In Solution Explorer, right-click AdventureWorks, and then click Add Reference.
b. In the Add Reference dialog box, click .NET.
In the list, click System.Web.Routing, and then click OK .
2. Verify reference to the System.Web.Routing assembly.
a. [Visual Basic] In Solution Explorer, click AdventureWorks, and then click the Show All Files
button.
b. In Solution Explorer, expand References.
c. Verify that the System.Web.Routing assembly is shown.
f Task 3: Map the page listing products by category
1. Open the Global.asax file.
• In Solution Explorer, double-click Global.asax.
2. Import the System.Web.Routing namespace in the Global.asax code file.
• At the top of the Global.asax.cs or Global.asax.vb code file, add the following code . [Visual C#]
using System.Web.Routing;
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 302/449
Lab Answer Key: Designing for Discoverability 3
Imports System.Web.Routing
3. Add a 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
);}
[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")
End Sub
• In the Global.asax.cs or Global.asax.vb window, in the Global class, add the following code.
[Visual C#]
void RegisterRoutes(RouteCollection routes){
routes.MapPageRoute(
"products-browse", // Route name
"products/{category}", // URL with parameters"~/Products.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 itroutes.MapPageRoute("products-browse", "products/{category}",
"~/Products.aspx")
End Sub
4. Modify the Application_Start method as shown.
[Visual C#]
void Application_Start()
{ RegisterRoutes(RouteTable.Routes);
}
[Visual Basic]
Private Sub Application_Start()RegisterRoutes(RouteTable.Routes)
End Sub
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 303/449
4 Lab Answer Key: Designing for Discoverability
5. Open the Products.aspx.cs or Products.aspx.vb code file.
• In Solution Explorer, right-click Products.aspx, and then click View Code.
6. Modify the Page_Load method in the Products class as shown.
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{if (!Page.IsPostBack)
{string categoryName = null;
string categoryId;
// Retrieve category param from "/Products/{Category}" URL
categoryId = Page.RouteData.Values["category"].ToString();
categoryName =
DataAccessLayer.Products.GetCategoryName(int.Parse(categoryId));
lblCategory.Text = categoryName;
var data =
DataAccessLayer.Products.GetProductsByCategory(int.Parse(categoryId));
gvProducts.DataSource = data;
gvProducts.DataBind();
}
}
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim categoryName As String = NothingDim categoryId As String
' Retrieve category param from "/Products/{Category}" URL
categoryId = Page.RouteData.Values("category").ToString()
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
End Sub
f Task 4: Test the pages1. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
2. Navigate directly to the Products page by using the following route.
products/1
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 304/449
Lab Answer Key: Designing for Discoverability 5
• In the Home Page – Windows Internet Explorer window, in the address bar, append the
following text.
products/1
Note: A grid should render with a single row containing products for the product category, with an IDvalue of 1.
3. Close Windows® Internet Explorer®.
• In the http://localhost:xxxx/products/1 – Windows Internet Explorer window, click the Closebutton.
f 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 305/449
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} URLproductId = 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.LoadIf Not Page.IsPostBack Then
Dim productID As String = Nothing
' Retrieve id param from /Products/{Id} URLproductID = 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
f sk 6: Test the pagesTa
1. Run the application . a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 306/449
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
f 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 EngineOptimization.
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 ChangeFrequency list, click Daily, in the Last Modified list, click Do Not Set, in the Priority list, click 1,
and then click OK.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 307/449
8 Lab Answer Key: Designing for Discoverability
• In the right pane, in the Management Group section, double-click Search EngineOptimization.
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 newallow rule.
b. In the Add Allow Rules dialog box, in the URL Paths list, select the Default Web Site andSitemap.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
f 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 Studio2010, 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\Lab06\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 06\Starter\Exercise03\AdventureWorks.sln and then click Open.
f 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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 308/449
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 SaveSite.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 StartWithout Debugging, or press CTRL+F5.
9. Close Internet Explorer.
• In the http://localhost:xxxx/products/1 – Windows Internet Explorer window, click the Close
button.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 309/449
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 StartDebugging, 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 . f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 310/449
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 311/449
2 Lab Answer Key: Writing Server-Side Code for Web Forms
Lab 7: Writing Server-Side Code for Web FormsExercise 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 Studio2010, and then click Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the following location.
Programming Language Location
Visual C#® D:\Lab Files\CS\Lab 07\Starter\Exercise 01
Visual Basic® D:\Lab Files\VB\Lab 07\Starter\Exercise 01
a. In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project, orpress CTRL+SHIFT+O.
b. In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab07\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 07\Starter\Exercise01\AdventureWorks.sln and then click Open.
Task 2: Create resource files for Default.aspx
1. Analyze the markup in Default.aspx.
a. In Solution Explorer, double-click Default.aspx.
b. Analyze the content of the Default.aspx file.
2. Generate local resources for Default.aspx, by using the Generate Local Resource functionalityavailable in Design view.
a. In the Default.aspx window, click Design.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Tools menu, click GenerateLocal Resource.
Note: This automatically creates the App_LocalResources folder in the root of your web application, if one does not already exist. The process also creates a resource file called Default.aspx.resx, in the App_LocalResources folder.
3. Switch back to Source view of Default.aspx.
• In the Default.aspx window, click Source.
4. Notice that both the lbCategories and btnCategory server controls have had an extra attributecalled meta:resourcekey added to the existing markup.
<asp:Button ... meta:resourcekey="btnCategoryResource1"></asp:Button><asp:ListBox ... meta:resourcekey="lbCategoriesResource1"></asp:ListBox>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 312/449
Lab Answer Key: Writing Server-Side Code for Web Forms 3
Note: The values of these attributes are used to find the localized values for the properties of thelocalizable controls in the Default.aspx.resx file.
5. Notice that the Page directive at the top of the page now contains the following information.
<%@ Page ... culture="auto" meta:resourcekey="PageResource1" uiculture="auto" %>
6. Open Default.aspx.resx.
• In Solution Explorer, in App_LocalResources, double-click Default.aspx.resx.
Note: In the Resource Editor, you will see a list with all the localizable properties of the localizablecontrols from the Default.aspx page.
7. Switch back to Default.aspx.
• In the AdventureWorks – Microsoft Visual Studio window, click Default.aspx.
8. Notice that the text strings Welcome to AdventureWorks! and Product Categories were notmodified, and they were not added to the .resx file either. This is because they were hard-coded inthe Web Forms page.
9. Localize the hard-coded Welcome to AdventureWorks! text implicitly, by adding a Localize servercontrol within the h2 element, with the following attributes.
Attribute Value
ID lclWelcome Text Welcome to AdventureWorks!
meta:resourcekey LocalizeResource1
a. Place the cursor within the h2 element, just before the text Welcome to AdventureWorks!.
b. Open the Toolbox, expand Standard, and then double-click Localize.
c. Modify the Localize server control to appear as follows.
<asp:Localize ID="lclWelcome" runat="server"
meta:resourcekey="lclWelcomeResource1" Text="Welcome toAdventureWorks!"></asp:Localize>
10. Delete the text Welcome to AdventureWorks! from the h2 element.
Note: Make sure that you do not delete the text Welcome to AdventureWorks! from the Localize server control.
11. Add a resource string named lclWelcomeResource1.Text to the Default.aspx.resx resource file. Thestring must have the value of Welcome to AdventureWorks!.
a. In the AdventureWorks – Microsoft Visual Studio window, click Default.aspx.resx.
b. In the bottom row of the Resource Editor, in the Name box, type lclWelcomeResource1.Text, inthe Value box, type Welcome to AdventureWorks!.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 313/449
4 Lab Answer Key: Writing Server-Side Code for Web Forms
12. Localize the hard-coded Product Categories text explicitly, by adding a Literal server control withinthe p element, with the following attributes.
Attribute Value
ID ProductCategoriesLiteral
Text <%$ Resources: ProductCategoriesLiteral.Text %>
a. In the AdventureWorks – Microsoft Visual Studio window, click Default.aspx.
b. Place the cursor within the p element, just before the text Product Categories.
c. Open the Toolbox, expand Standard, and then double-click Literal.
d. Modify the Literal server control to appear as follows.
<asp:Literal ID="ProductCategoriesLiteral" runat="server" Text="<%$ Resources:ProductCategoriesLiteral.Text %>"></asp:Literal>
13. Delete the text Product Categories from the p element.
Note: Make sure that you do not delete the text Product Categories from the Literal server control.
14. Add a resource string named ProductCategoriesLiteral.Text to the Default.aspx.resx resource file.The string must have the value of Product Categories.
a. In the AdventureWorks – Microsoft Visual Studio window, click Default.aspx.resx.
b. In the bottom row of the Resource Editor, in the Name box, typeProductCategoriesLiteral.Text, in the Value box, type Product Categories.
15. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
16. Verify that Default.aspx Web Form looks the same as it did before you modified it.
17. Close Windows® Internet Explorer®.
• 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\Lab07\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 ExistingItem.
b. In the Add Existing Item dialog box, in the File name box, type D:\Lab Files\CS\Lab07\Starter\Exercise 01\Default.aspx.de.resx or D:\Lab Files\VB\Lab 07\Starter\Exercise01\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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 314/449
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 thefollowing 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 theLoggedInTemplate 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 textWelcome.
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 GenerateLocal Resource.
Note: This generates a new file called Site.Master.resx in the App_LocalResources folder.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 315/449
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\Lab07\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 ExistingItem.
b. In the Add Existing Item dialog box, in the File name box, type D:\Lab Files\CS\Lab07\Starter\Exercise 01\Site.Master.de.resx or D:\Lab Files\VB\Lab 07\Starter\Exercise01\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 StartWithout Debugging, or press CTRL+F5.
2. Show the AdventureWorks home page in German, by changing the language preference in theInternet Options dialog box.
a. In the Home Page - Windows Internet Explorer window, on the Tools menu, click InternetOptions.
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], andthen click OK .
e. In the Language Preference dialog box, in the Language list, click German (Germany) [de-DE], and then click Move up.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 316/449
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 Studio2010, 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, orpress CTRL+SHIFT+O.
b. In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab07\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 07\Starter\Exercise02\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. Thecookie must be appended to the response.
[Visual C#]else
{if (lbCategories.SelectedIndex != -1)
{
string category = lbCategories.SelectedValue;
HttpCookie cookie = new HttpCookie("Preferences");
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 317/449
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]
ElseIf 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]
ElseIf 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 inthe request cookie collection, and if there is, read the LastCategory value from the cookie, and assignit to the SelectedValue property of the ListBox control.
[Visual C#]if (!Page.IsPostBack)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 318/449
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 ThenlbCategories.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 ThenlbCategories.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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 319/449
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 BuildSolution, 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 variablenamed 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") = 0End 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 theApplication 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();
}
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 320/449
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 += 1Application("OnlineVisitors") = visitors
Application.UnLock()
End Sub
4. In the Session_End decrement the value of the OnlineVisitors application variable by 1, if thecurrent value is not 0. Make sure you prevent multiple threads from writing to the applicationvariable, by locking the Application object before writing, and unlocking once you have finishedwriting 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 Thenvisitors -= 1Application("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 BuildSolution, 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 ispersisted. In the Page_Load method, notice how the product ID, product name, and list price, whichare not displayed to the user, are saved to hidden fields. In the btnOrder_Click event handler, noticethat a new List object of type clsShoppingCart is created and saved to Session state. Finally, the useris redirected to the ShoppingCart Web Form.
3. Open the ShoppingCart Web Form in Code view.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 321/449
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 thePage_Load event handler method. A check to see if a Session object named _cart exists isperformed. 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® instance named SQLExpress, for persistingsession information instead of the default InProc mode.
<system.web>
...
<sessionState mode="SQLServer" sqlConnectionString="Integrated Security=SSPI;DataSource=.\SQLExpress;" /></system.web>
• In the Web.config window, add the following markup just before the end system.web tag.
<sessionState mode="SQLServer" sqlConnectionString="Integrated Security=SSPI;DataSource=.\SQLExpress;" />
3. Configure the local SQL Server instance SQLExpress to host the state database, by running thefollowing command from the Visual Studio Command Prompt (2010). The Visual Studio CommandPrompt (2010) must be run as an administrator.
aspnet_regsql -E -S .\SQLExpress -ssadd
a. In the Start menu, point to All Programs, expand Microsoft Visual Studio 2010, expand Visual
Studio Tools, right-click Visual Studio Command Prompt (2010), and then click Run asadministrator.
b. In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then clickYes.
c. In the Visual Studio Command Prompt (2010) window, type the following, and then pressENTER: aspnet_regsql -E -S .\SQLExpress -ssadd
4. Open the SQL Server Command Line Tool, by running the following command from the VisualStudio Command Prompt (2010).
sqlcmd –E –S .\SQLExpress
• In the Visual Studio Command Prompt (2010) window, type the following, and then pressENTER: sqlcmd –E –S .\SQLExpress
5. Add permissions for the user Student to access the tempdb and ASPState database to use the newSQL Server Session state, by running commands from the SQL Server Command Line Tool withinthe Visual Studio Command Prompt (2010). The commands are saved in the D:\Lab Files\CS\Lab07\Starter\Exercise 02\ASPState.txt or D:\Lab Files\VB\Lab 07\Starter\Exercise 02\ASPState.txt file, from where you can copy them and paste them into the SQL Server Command Line Tool.
a. On the Start menu, click Run.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 322/449
Lab Answer Key: Writing Server-Side Code for Web Forms 13
b. In the Run dialog box, in the Open box, type D:\Lab Files\CS\Lab 07\Starter\Exercise02\ASPState.txt or D:\Lab Files\VB\Lab 07\Starter\Exercise 02\ASPState.txt, and then pressENTER.
c. In the ASPState.txt – Notepad window, on the Edit menu, click Select All, or press CTRL+A.
d. In the ASPState.txt – Notepad window, on the Edit menu, click Copy, or press CTRL+C.
e. In the ASPState.txt – Notepad window, click the Close button.
f. In the SQLCMD window, right-click next to line 1, and then click Paste.
6. Close the SQL Server Command Line Tool, by running the following command from the VisualStudio Command Prompt (2010).
quit
• In the SQLCMD window, type quit, and then press ENTER.
7. Close the Visual Studio Command Prompt (2010).
• In the Visual Studio Command Prompt (2010) window, type exit, and then press ENTER.
8. Close Visual Studio 2010.• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 3: Utilizing View State Effectively
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 Studio2010, 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 03
Visual Basic D:\Lab Files\VB\Lab 07\Starter\Exercise 03
a. In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project, orpress CTRL+SHIFT+O.
b. In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab07\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 07\Starter\Exercise03\AdventureWorks.sln and then click Open.
Task 2: Configure view state to persist page data
1. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
2. View the source of the Default.aspx page in Internet Explorer, by using the View Source functionality.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 323/449
14 Lab Answer Key: Writing Server-Side Code for Web Forms
• In the Home Page – Windows Internet Explorer window, right-click the page, and then clickView Source.
3. Analyze the HTML code, and pay special attention to the __VIEWSTATE field.
• In theHH
http://localhost:xxxx/ HH
– Original Source window, notice the size of the __VIEWSTATE field.
4. Close the View Source window.
• In theHH
http://localhost:xxxx/ HH
– Original Source window, click the Close button.
5. Close Internet Explorer.
• In the Home Page – Windows Internet Explorer window, click the Close button.
6. Open the Default.aspx Web Form.
• In Solution Explorer, double-click Default.aspx.
7. Disable view state for the lbCategories server control.
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"
DataValueField="ProductCategoryID"
Height="270px" Width="186px" EnableViewState="False"></asp:ListBox>
a. In the Default.aspx window, place the cursor in the markup for the lbCategories server control.
b. In the Properties window, in the EnableViewState list, click False.
8. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
9. View the source of the Default.aspx page in Internet Explorer, by using the View Source
functionality.• In the Home Page – Windows Internet Explorer window, right-click the page, and then click
View Source.
10. Analyze the HTML code, and pay special attention to the __VIEWSTATE field, which is now muchsmaller, almost half the size.
• In theHH
http://localhost:xxxx/ HH
– Original Source window, notice the size of the __VIEWSTATE field.
11. Close the View Source window.
• In theHH
http://localhost:xxxx/ HH
– Original Source window, click the Close button.
12. Notice the effects of disabling view state for the lbCategories server control, by clicking Submit.
Note: The lbCategories server control is now empty because it is not being populated by the server
code on a postback.
13. Close Internet Explorer.
• In the Home Page – Windows Internet Explorer window, click the Close button.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 324/449
Lab Answer Key: Writing Server-Side Code for Web Forms 15
Task 3: Disable view state and its effects
1. Disable view state for the Default Web Form by setting the EnableViewState property to False.
<%@ Page Title="Home Page" ... EnableViewState="False" %>
a. In the Default.aspx window, place the cursor in the markup for the Page directive.
b. In the Properties window, in the EnableViewState list, click False.
2. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
3. Click Submit.
Note: The lbCategories server control is now empty because it is not being populated by the servercode on a postback.
4. Close Internet Explorer.
• In the Home Page – Windows Internet Explorer window, click the Close button.
5. Enable view state for the lbCategories server control.
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"
DataValueField="ProductCategoryID"
Height="270px" Width="186px" EnableViewState="True"></asp:ListBox>
a. In the Default.aspx window, place the cursor in the markup for the lbCategories server control.
b. In the Properties window, in the EnableViewState list, click True.
6. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
7. Click Submit.
Note: The lbCategories server control is now empty, even if you enabled view state for the control.This is because disabling view state for a control or page will disable the view state for all child controls.
8. Close Internet Explorer.• In the Home Page – Windows Internet Explorer window, click the Close button.
9. Remove the EnableViewState attribute and value from the Page directive.
• In the Default.aspx window, delete the following text from the markup for the Page directive.
EnableViewState="False"
10. Remove the EnableViewState attribute and value from the lbCategories server control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 325/449
16 Lab Answer Key: Writing Server-Side Code for Web Forms
• In the Default.aspx window, delete the following text from the markup for the lbCategories server control.
EnableViewState="True"
11. Disable view state for the Default Web Form by setting the ViewStateMode property to Disabled.
<%@ Page Title="Home Page" ... ViewStateMode="Disabled" %>
a. In the Default.aspx window, place the cursor in the markup for the Page directive.
b. In the Properties window, in the ViewStateMode list, click Disabled.
12. Enable view state for the lbCategories server control by setting the ViewStateMode property toEnabled.
<asp:ListBox ID="lbCategories" runat="server" DataTextField="Name"
DataValueField="ProductCategoryID"Height="270px" Width="186px" ViewStateMode="Enabled"></asp:ListBox>
a. In the Default.aspx window, place the cursor in the markup for the lbCategories server control.
b. In the Properties window, in the ViewStateMode list, click Enabled.
13. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
14. Click Submit.
Note: The lbCategories server control is still populated because view state has been enabled for theserver control.
15. Close Internet Explorer.
• In the Home Page – Windows Internet Explorer window, click the Close button.
16. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 4: Adding Validation to 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 Studio2010, 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 04
Visual Basic D:\Lab Files\VB\Lab 07\Starter\Exercise 04
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 326/449
Lab Answer Key: Writing Server-Side Code for Web Forms 17
a. In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project, orpress CTRL+SHIFT+O.
b. In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab07\Starter\Exercise 04\AdventureWorks.sln or D:\Lab Files\VB\Lab 07\Starter\Exercise04\AdventureWorks.sln and then click Open.
Task 2: Add credit card fields to the check-out page1. Open the ShoppingCart.aspx Web Form.
• In Solution Explorer, double-click ShoppingCart.aspx.
2. Add a TextBox server control for the credit card field and name it txtCreditCard. Place the servercontrol below the gvCart GridView server control. Add describing text, Credit card number:, infront of the server control.
<br />
Credit card number: <asp:TextBox runat="server" ID="txtCreditCard"/>
Task 3: Add and configure a RequiredFieldValidator control for the txtCreditCard control
1. Add a RequiredFieldValidator control named CreditCardRequiredFieldValidator to theShoppingCart Web Form, and place it immediately after the txtCreditCard control.
<asp:TextBox runat="server" ID="txtCreditCard" />
<asp:RequiredFieldValidator ID="CreditCardRequiredFieldValidator" runat="server"></asp:RequiredFieldValidator>
2. Set the following properties as indicated.
• ControlToValidate = txtCreditCard
• ErrorMessage = Credit card number is required.
• Text = *
<asp:RequiredFieldValidator ID="CreditCardRequiredFieldValidator" runat="server" ControlToValidate="txtCreditCard" ErrorMessage="Credit card number is required."
Text="*"> </asp:RequiredFieldValidator>
Task 4: Add and configure a RegularExpressionValidator control for the credit card field
1. Add a RegularExpressionValidator control named CreditCardRegularExpressionValidator to theShoppingCart Web Form, and place it immediately after the CreditCardRequiredFieldValidator control. Add a self-closing HTML br element after the RegularExpressionValidator control.
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="CreditCardRegularExpressionValidator"runat="server">
</asp:RegularExpressionValidator><br />
2. Set the following properties as indicated.
• ControlToValidate = txtCreditCard
• ErrorMessage = Please enter a valid credit card number.
• Text = *
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 327/449
18 Lab Answer Key: Writing Server-Side Code for Web Forms
• ValidationExpression= ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$
<asp:RegularExpressionValidator ID="CreditCardRegularExpressionValidator"
runat="server"ControlToValidate="txtCreditCard" Text="*" ErrorMessage="Please enter a valid
credit card number."ValidationExpression="^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-
9]{13})$"></asp:RegularExpressionValidator>
3. Open the ShoppingCart Web Form in Code view.
• In the ShoppingCart.aspx window, right-click anywhere, and then click View Code.
4. Make sure that an order can be placed only if Page.IsValid is true. Add the check to thebtnPlaceOrder_Click event handler method.
[Visual C#]protected void btnPlaceOrder_Click(object sender, EventArgs e){
if (Page.IsValid){
Session["_cart"] = null;Response.Redirect("~/ThankYou.aspx", true);}
}
[Visual Basic]Protected Sub btnPlaceOrder_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnPlaceOrder.ClickIf Page.IsValid Then
Session("_cart") = Nothing
Response.Redirect("~/ThankYou.aspx", True)End If
End Sub
5. Run the application.
a. In Solution Explorer, click AdventureWorks.
b. In the AdventureWorks – Microsoft Visual Studio window, on the Debug menu, click StartWithout Debugging, or press CTRL+F5.
6. Select Bib-Shorts on the Product Categories list, and click Submit.
7. On the Products page, click Men's Bib-Shorts, L.
8. On the Men's Bib-Shorts, L page, click Order.
9. On the Shopping Cart page, click Place Order.
Note: Observe that an asterisk (*) is placed next to txtCreditCard server control because you have notfilled in this field.
10. On the Shopping Cart page, in the Credit card number box, type 1234123412341234, and thenclick Place Order.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 328/449
Lab Answer Key: Writing Server-Side Code for Web Forms 19
Note: Observe that an asterisk (*) is placed next to txtCreditCard server control because you have notentered a valid credit card number.
11. On the Shopping Cart page, in the Credit card number box, type 4058340022020047, and thenclick Place Order.
Note: Observe that you are redirected to the ThankYou Web Form because you have filled in a validcredit card number.
12. Close Internet Explorer.
• In theHH
http://localhost:xxxx/ThankYou.aspxHH
– Windows Internet Explorer window, click theClose button.
13. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Task 5: Turn off the virtual machine and revert the changes1. 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 clickRevert.
4. In the Revert Virtual Machine dialog box, click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 329/449
Lab Answer Key: Optimizing Data Management for Web Forms 1
Module 8
Lab Answer Key: Optimizing Data Management for WebForms
Contents:Lab 8A: Optimizing Data Management for Web Forms Exercise 1: Managing Data by Using LINQ to Entities 2
Exercise 2: Customizing the GridView 3
Exercise 3: Using ListView, DetailsView and Charts 17
Lab 8B: Optimizing Data Management for Web Forms
Exercise 4: Managing Data by Using ASP.NET Dynamic Data 25
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 330/449
2 Lab 8A: Optimizing Data Management for Web Forms
Lab 8A: Optimizing Data Management for WebFormsExercise 1: Managing Data by Using LINQ to Entities
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 Studio2010, and then click Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the D:\Lab Files\VB\Lab 08\Starter\Exercise 01 or
D:\Lab Files\CS\Lab 08\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\VB\Lab
08\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\CS\Lab 08\Starter\Exercise01\AdventureWorks.sln, and then click Open.
Task 2: Create a new Entity Framework Data Model
1. Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx. The data model
should be generated from a database, by using the AdventureWorksLT2008 connection string from
the Web.config file. All tables from the database, with the exception of the BuildVersion table,
should be added to the data model.
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 left pane, click Data, in the middle
pane, click ADO.NET Entity Data Model.
c. In the Name box, type AdventureWorks.edmx, and then click Add.
d. In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate fromdatabase, and then click Next.
e. On the Choose Your Data Connection page, in the Which data connection should yourapplication use to connect to the database? list, click AdventureWorksLT2008 (Settings),and then click Next.
f. On the Choose Your Database Objects page, on the Which database objects do you want to
include in your model? list, expand Tables, click Tables, and then click BuildVersion (dbo).
g. Click Finish.
2. Save and close the ADO.NET Entity Data Model item.
a. In the AdventureWorks.edmx window, on the File menu, click the Save AdventureWorks.edmx,or press CTRL+S.
b. In the AdventureWorks.edmx window, click the Close button.
3. Build the project and fix any errors.
• In the AdventureWorks – Microsoft Visual Studio window, on the Build menu, click BuildAdventureWorks.
4. Close Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 331/449
Lab Answer Key: Optimizing Data Management for Web Forms 3
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 2: Customizing the GridView
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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\VB\Lab 08\Starter\Exercise 02 or
D:\Lab Files\CS\Lab 08\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\VB\Lab08\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\CS\Lab 08\Starter\Exercise02\AdventureWorks.sln, and then click Open.
Task 2: Create a Shopping Cart Quantity user control
1.
Create a new user control named Quantity.ascx.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 left pane, click Web, in the middle
pane, click Web User Control.
c. In the Name box, type Quantity.ascx, and then click Add.
2. Add a TextBox control named QuantityTextBox to the user control.
• In Quantity.ascx window, add the following markup.
<asp:TextBox ID="QuantityTextBox"
runat="server"></asp:TextBox>
3. Add a RequiredFieldValidator control named QuantityRequiredFieldValidator to the user control.The RequiredFieldValidator control must validate the QuantityTextBox control, and display the
text “You must fill in the Quantity.” as the error message, if the user leaves the text box empty. The
display mode must be dynamic.
• In Quantity.ascx window, add the following markup, below the QuantityTextBox control.
<asp:RequiredFieldValidator ID="QuantityRequiredFieldValidator"
runat="server" ErrorMessage="You must fill in the Quantity."
ControlToValidate="QuantityTextBox"
Display="Dynamic"></asp:RequiredFieldValidator>
4. Add a public property named Text to the user control. The property must be of type String / string,
and get and set the Text property of the QuantityTextBox control.
[Visual Basic]
Public Property Text As String
GetReturn QuantityTextBox.Text
End Get
Set(ByVal value As String)QuantityTextBox.Text = value
End Set
End Property
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 332/449
4 Lab 8A: Optimizing Data Management for Web Forms
[Visual C#]
public string Text
{
get{
return QuantityTextBox.Text;
}set
{
QuantityTextBox.Text = value;}
}
a. In Solution Explorer, right-click Quantity.ascx, and then click View Code.
b. In the Quantity.ascx.vb or Quantity.ascx.cs window, add the following code, at the top of the
Quantity class.
[Visual Basic]
Public Property Text As String
GetReturn QuantityTextBox.Text
End Get
Set(ByVal value As String)QuantityTextBox.Text = value
End Set
End Property
[Visual C#]
public string Text
{get
{
return QuantityTextBox.Text;
}set
{QuantityTextBox.Text = value;
}
}
5. Save and close the user control.
a. In the AdventureWorks – Microsoft Visual Studio window, on the File menu, click Save All.
b. In the Quantity.ascx.vb or Quantity.ascx.cs window, click the Close button.
c. In the Quantity.ascx window, click the Close button.
6.
Build the project and fix any errors.• In the AdventureWorks – Microsoft Visual Studio window, on the Build menu, click Build
AdventureWorks.
Note: Observe the “Build succeeded” message in the Build pane of the Output window.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 333/449
Lab Answer Key: Optimizing Data Management for Web Forms 5
Task 3: Modify ShoppingCart entity class
1. Open the ShoppingCart.vb or ShoppingCart.cs class file.
• In Solution Explorer, right-click ShoppingCart.vb or ShoppingCart.cs, and then click ViewCode.
2. Add a private member variable named productQuantity of type Integer / int to the ShoppingCart
class.
[Visual Basic]
Private productQuantity As Integer
[Visual C#]
private int productQuantity;
• In the ShoppingCart.vb or ShoppingCart.cs window, add the following code, before the
Quantity property.
[Visual Basic]
• Private productQuantity As Integer
[Visual C#]
• private int productQuantity;
3. Modify the auto-implemented Quantity property, to get and set the productQuantity member
variable.
[Visual Basic]
Public Property Quantity As Integer
Get
Return productQuantityEnd Get
SetproductQuantity = value
End Set
End Property
[Visual C#]
public int Quantity
{
get
{return productQuantity;
}
set{
productQuantity = value;
}}
• In the ShoppingCart.vb or ShoppingCart.cs window, modify the auto-implemented
property to look like this.
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 334/449
6 Lab 8A: Optimizing Data Management for Web Forms
Public Property Quantity As Integer
GetReturn productQuantity
End GetSet
productQuantity = value
End Set
End Property
[Visual C#]
public int Quantity
{get
{
return productQuantity;
}set
{
productQuantity = value;}
}
4. Add an auto-implemented TotalPrice property, of type Decimal / decimal.
[Visual Basic]
Public Property TotalPrice As Decimal
[Visual C#]
public decimal TotalPrice { get; set; }
• In the ShoppingCart.vb or ShoppingCart.cs window, add the following code after the ListPrice
property.
[Visual Basic]
Public Property TotalPrice As Decimal
[Visual C#]
public decimal TotalPrice { get; set; }
5. Update the TotalPrice property, when the Quantity property is set.
[Visual Basic]
TotalPrice = productQuantity * ListPrice
[Visual C#]
TotalPrice = productQuantity * ListPrice;
• In the ShoppingCart.vb or ShoppingCart.cs window, append the following code to the
Quantity property setter.
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 335/449
Lab Answer Key: Optimizing Data Management for Web Forms 7
TotalPrice = productQuantity * ListPrice
[Visual C#]
TotalPrice = productQuantity * ListPrice;
6. Save and close the ShoppingCart entity class.
a. In the AdventureWorks – Microsoft Visual Studio window, on the File menu, click SaveShoppingCart.vb or Save ShoppingCart.cs.
b. In the ShoppingCart.vb or ShoppingCart.cs window, click the Close button.
7. Build the project and fix any errors.
• In the AdventureWorks – Microsoft Visual Studio window, on the Build menu, click BuildAdventureWorks.
Task 4: Convert a BoundField column to TemplateField
1. Open the ShoppingCart.aspx content page in Design view.
• In Solution Explorer, right-click ShoppingCart.aspx, and then click View Designer.
2. Select the gvCart GridView control.
• In the ShoppingCart.aspx window, click gvCart.
3. Open the Fields dialog box for the GridView control, by using the Smart Tag.
a. On the GridView control, click the Smart Tag button.
b. In the GridView Tasks dialog box, click Edit Columns.
4. Convert the Quantity field to a template field.
a. In the Fields dialog box, in the Selected fields list, click Quantity.
b. Click Convert this field into a TemplateField.
Task 5: Add computed column to GridView control
1. Append a new template field with a HeaderText property value of Total Price and close the Fields
dialog box.
a. In the Fields dialog box, in the Available fields list, click TemplateField, and then click Add.
b. In the TemplateField properties list, in the HeaderText box, type Total Price, and then click
OK .
2. Open the ShoppingCart.aspx content page in Source view.
• In the ShoppingCart.aspx window, click Source.
Note: Observe how the Quantity field/column has been converted into a TemplateField, and
the newly added Total Price TemplateField.
Task 6: Make GridView updatable
1. Open the ShoppingCart.aspx content page in Design view.
• In the ShoppingCart.aspx window, click Design.
2. Select the gvCart GridView control.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 336/449
8 Lab 8A: Optimizing Data Management for Web Forms
• In the ShoppingCart.aspx window, click gvCart.
3. Set the AutoGenerateEditButton property to a value of True.
• In the Properties window, on the AutoGenerateEditButton list, click True.
4. Add an event handler for the RowCancelingEdit event.
a. In the Properties window, click the Events button.b. Double-click the text box for the RowCancelingEdit event.
5. Add an event handler for the RowEditing event.
a. In the AdventureWorks – Microsoft Visual Studio window, click ShoppingCart.aspx.
b. Double-click the text box for the RowEditing event.
6. Add an event handler for the RowUpdating event.
a. In the AdventureWorks – Microsoft Visual Studio window, click ShoppingCart.aspx.
b. Double-click the text box for the RowUpdating event.
7. Make the existing code in the Page_Load event handler execute only on first request by wrapping
the existing code in the Page_Load event handler in an If / if statement.
• Wrap the existing code in the Page_Load event handler in the following If / if statement.
[Visual Basic]
If Not IsPostBack Then
End If
[Visual C#]
if (!IsPostBack)
{
}
8. Add a new Sub/void method named BindData to the ShoppingCart1 class.
[Visual Basic]
Private Sub BindData()
Dim cart As List(Of ShoppingCart) =
CType(Session("_cart"), List(Of ShoppingCart))
gvCart.DataSource = cartgvCart.DataBind()
End Sub
[Visual C#]
private void BindData()
{List<ShoppingCart> cart = (List<ShoppingCart>)
Session["_cart"];
gvCart.DataSource = cart;gvCart.DataBind();
}
• Add the following code to the ShoppingCart1 class.
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 337/449
Lab Answer Key: Optimizing Data Management for Web Forms 9
Private Sub BindData()
Dim cart As List(Of ShoppingCart) =CType(Session("_cart"), List(Of ShoppingCart))
gvCart.DataSource = cartgvCart.DataBind()
End Sub
[Visual C#]
private void BindData()
{
List<ShoppingCart> cart = (List<ShoppingCart>)
Session["_cart"];gvCart.DataSource = cart;
gvCart.DataBind();
}
9. Add code to the gvCart_RowEditing method, for setting the edit index, and bind the data by
using the BindData method.
[Visual Basic]
Protected Sub gvCart_RowEditing(ByVal sender As Object, ByVal
e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles
gvCart.RowEditing' Set edit indexgvCart.EditIndex = e.NewEditIndex
' Bind dataBindData()
End Sub
[Visual C#]
protected void gvCart_RowEditing(object sender,
GridViewEditEventArgs e)
{
// Set edit indexgvCart.EditIndex = e.NewEditIndex;// Bind data
BindData();
}
• Add the following code to the gvCart_RowEditing method.
[Visual Basic]
' Set edit index
gvCart.EditIndex = e.NewEditIndex
' Bind dataBindData()
[Visual C#]
// Set edit index
gvCart.EditIndex = e.NewEditIndex;// Bind data
BindData();
10. Add code to the gvCart_RowCancelingEdit method, for resetting the edit index and bind the
data by using the BindData method.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 338/449
10 Lab 8A: Optimizing Data Management for Web Forms
[Visual Basic]
Protected Sub gvCart_RowCancelingEdit(ByVal sender As Object,
ByVal e As
System.Web.UI.WebControls.GridViewCancelEditEventArgs) HandlesgvCart.RowCancelingEdit
' Reset edit index
gvCart.EditIndex = -1' Bind data
BindData()
End Sub
[Visual C#]
protected void gvCart_RowCancelingEdit(object sender, GridViewCancelEditEventArgs
e)
{
// Reset edit indexgvCart.EditIndex = -1;
// Bind dataBindData();
}
• Add the following code to the gvCart_RowCancelingEdit method.
[Visual Basic]
' Reset edit index
gvCart.EditIndex = -1' Bind data
BindData()
[Visual C#]
// Reset edit index
gvCart.EditIndex = -1;
// Bind dataBindData();
11. Add code to the gvCart_RowUpdating method, for retrieving the existing cart from Session.
[Visual Basic]
' Retrieve existing cart from session
Dim cart As List(Of ShoppingCart) = CType(Session("_cart"),List(Of ShoppingCart))
[Visual C#]
// Retrieve existing cart from session
List<ShoppingCart> cart = (List<ShoppingCart>) Session["_cart"];
• Add the following code to the gvCart_RowUpdating method.
[Visual Basic]
' Retrieve existing cart from session
Dim cart As List(Of ShoppingCart) = CType(Session("_cart"), List(Of
ShoppingCart))
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 339/449
Lab Answer Key: Optimizing Data Management for Web Forms 11
[Visual C#]
// Retrieve existing cart from session
List<ShoppingCart> cart = (List<ShoppingCart>) Session["_cart"];
12. Append code to the gvCart_RowUpdating method, for retrieving the current row from the
GridView control.
[Visual Basic]
' Get current row
Dim row As GridViewRow = gvCart.Rows(e.RowIndex)
[Visual C#]
// Get current row
GridViewRow row = gvCart.Rows[e.RowIndex];
• Append the following code to the gvCart_RowUpdating method.
[Visual Basic]
' Get current row
Dim row As GridViewRow = gvCart.Rows(e.RowIndex)
[Visual C#]
// Get current row
GridViewRow row = gvCart.Rows[e.RowIndex];
13. Append code to the gvCart_RowUpdating method, for finding the matching row in the stored
cart, stored in a new variable named cartToEdit of type ShoppingCart. Use the generic List Find
method with an anonymous Lambda expression.
[Visual Basic]
' Find matching row in stored cart
Dim cartToEdit As ShoppingCart =cart.Find(Function(cartToFind) cartToFind.ProductId =
Integer.Parse(row.Cells(1).Text))
[Visual C#]
// Find matching row in stored cart
ShoppingCart cartToEdit = cart.Find((cartToFind) =>cartToFind.ProductId == int.Parse(row.Cells[1].Text));
• Append the following code to the gvCart_RowUpdating method.
[Visual Basic]
' Find matching row in stored cart
Dim cartToEdit As ShoppingCart =cart.Find(Function(cartToFind) cartToFind.ProductId =
Integer.Parse(row.Cells(1).Text))
[Visual C#]
// Find matching row in stored cart
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 340/449
12 Lab 8A: Optimizing Data Management for Web Forms
ShoppingCart cartToEdit = cart.Find((cartToFind) =>
cartToFind.ProductId == int.Parse(row.Cells[1].Text));
14. Append code to the gvCart_RowUpdating method, for updating the quantity value of the
cartToEdit shopping cart with the value of the Text property of the Quantity user control,
located in the current row of the GridView control.
[Visual Basic]
' Update values
Dim qty As Quantity =
CType(gvCart.Rows(e.RowIndex).FindControl("Quantity1"),Quantity)
cartToEdit.Quantity = Integer.Parse(qty.Text)
[Visual C#]
// Update values
Quantity qty =gvCart.Rows[e.RowIndex].FindControl("Quantity1") as Quantity;
cartToEdit.Quantity = int.Parse(qty.Text);
• Append the following code to the gvCart_RowUpdating method.
[Visual Basic]
' Update values
Dim qty As Quantity =
CType(gvCart.Rows(e.RowIndex).FindControl("Quantity1"),
Quantity)cartToEdit.Quantity = Integer.Parse(qty.Text)
[Visual C#]
// Update values
Quantity qty =gvCart.Rows[e.RowIndex].FindControl("Quantity1") as
Quantity;cartToEdit.Quantity = int.Parse(qty.Text);
15. Append code to the gvCart_RowUpdating method, to save the updated cart to Session state.
[Visual Basic]
' Save updated cart to session
Session("_cart") = cart
[Visual C#]
// Save updated cart to sessionSession["_cart"] = cart;
• Append the following code to the gvCart_RowUpdating method.
[Visual Basic]
' Save updated cart to session
Session("_cart") = cart
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 341/449
Lab Answer Key: Optimizing Data Management for Web Forms 13
[Visual C#]
// Save updated cart to session
Session["_cart"] = cart;
16. Append code to the gvCart_RowUpdating method, for resetting the edit index and bind the
data by using the BindData method.
[Visual Basic]
' Reset edit index
gvCart.EditIndex = -1' Bind data
BindData()
[Visual C#]
// Reset edit index
gvCart.EditIndex = -1;
// Bind dataBindData();
• Append the following code to the gvCart_RowUpdating method.
[Visual Basic]
' Reset edit index
gvCart.EditIndex = -1' Bind data
BindData()
[Visual C#]
// Reset edit index
gvCart.EditIndex = -1;// Bind data
BindData();
17. Save and close the ShoppingCart code-behind file.
a. In the AdventureWorks – Microsoft Visual Studio window, on the File menu, click SaveShoppingCart.aspx.vb or Save ShoppingCart.aspx.cs.
b. In the ShoppingCart.aspx.vb or ShoppingCart.aspx.cs window, click the Close button.
18. Build the project and fix any errors.
• In the AdventureWorks – Microsoft Visual Studio window, on the Build menu, click BuildAdventureWorks.
Task 7: Add user control to TemplateField1. Add the user control to the Shopping Cart Web Form.
a. In Solution Explorer, click Quantity.ascx, and then drag it to the designer.
b. Open the ShoppingCart.aspx content page in Source view.
c. In the ShoppingCart.aspx window, click Source.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 342/449
14 Lab 8A: Optimizing Data Management for Web Forms
Note: Observe how the Quantity user control has been registered using the Register directive,
and the user control has been added to the web form.
2. Move the markup for the Quantity user control to the top of the EditItemTemplate element.
<EditItemTemplate>
<uc1:Quantity ID="Quantity1" runat="server" /><asp:TextBox ID="TextBox1" runat="server" Text='<%#
Bind("Quantity") %>'></asp:TextBox></EditItemTemplate>
a. In the ShoppingCart.aspx window, locate and select the markup for the Quantity user control.
<uc1:Quantity ID="Quantity1" runat="server"/>
b. Right-click the selection, and then click Cut.
c. Place the cursor after the opening EditItemTemplate tag, and then press ENTER.
d. Press CTRL+V.
3. Copy the Text attribute and value from the TextBox1 control to the Quantity1 control.
<uc1:Quantity ID="Quantity1" runat="server" Text='<%#
Bind("Quantity") %>' />
a. In the ShoppingCart.aspx window, locate the TextBox1 control, and select the markup for the
Text attribute.
Text='<%# Bind("Quantity") %>'
b. Right-click the selection, and then click Copy.
c. Place the cursor in the Quantity1 element, after the runat attribute, and then press CTRL+V.
4. Delete the TextBox1 control.
a. In the ShoppingCart.aspx window, locate and select the TextBox1 control.
<asp:TextBox ID="TextBox1" runat="server" Text='<%#
Bind("Quantity") %>'></asp:TextBox>
b. Right-click the selection, and then click Delete.
5. Make the ProductId BoundField control read-only.
• In the ShoppingCart.aspx window, add the following markup to the BoundField element with a
DataField attribute value of ProductId.
ReadOnly="true"
6. Format the display of the ListPrice BoundField control using the DataFormatString attribute and a
value of {0:c}.
• In the ShoppingCart.aspx window, add the following markup to the BoundField element with a
DataField attribute value of ListPrice.
DataFormatString="{0:c}"
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 343/449
Lab Answer Key: Optimizing Data Management for Web Forms 15
7. Modify the format of the TemplateField control with a HeaderText attribute value of Total Price, to
appear as follows.
<asp:TemplateField HeaderText="Total Price">
<ItemTemplate><asp:Label ID="Label1" runat="server" Text='<%#
Eval("TotalPrice") %>' DataFormatString="{0:c}"></asp:Label>
</ItemTemplate></asp:TemplateField>
Task 8: Implement GridView paging
1. Set the AllowPaging property to true for GridView control.
a. In the ShoppingCart.aspx window, place the cursor in the opening tag for the GridView control.
b. In the Properties window, in the AllowPaging list, click True.
2. Set the PageSize property to 1 for GridView control.
a. In the ShoppingCart.aspx window, place the cursor in the opening tag for the GridView control.
b. In the Properties window, in the PageSize box, type 1, and then press ENTER.
3. Add an event handler for the PageIndexChanging event.
a. In the ShoppingCart.aspx window, click Design.
b. In the Properties window, click the Events button.
c. Double-click the text box for the PageIndexChanging event.
4. Add code to prevent page index to change, when in edit mode, and display an appropriate error
message in the lblMessage Label control, by using the following code.
[Visual Basic]
' Cancel paging operation if user attempts to navigate
' to another page while in edit mode
If CType(sender, GridView).EditIndex <> -1 Then' Cancel paging operation
e.Cancel = True
' Display error messageDim newPageIndex As Integer = e.NewPageIndex + 1lblMessage.Text = "Update the item before moving to page " &
newPageIndex.ToString()Else
' Clear message text
lblMessage.Text = ""' Set page indexCType(sender, GridView).PageIndex = e.NewPageIndex
BindData()End If
[Visual C#]
// Cancel paging operation if user attempts to navigate
// to another page while in edit mode
if (((GridView) sender).EditIndex != -1){
// Cancel paging operation
e.Cancel = true;
// Display error message
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 344/449
16 Lab 8A: Optimizing Data Management for Web Forms
int newPageIndex = e.NewPageIndex + 1;
lblMessage.Text = "Update the item before moving to page " +newPageIndex.ToString();
}else{
// Clear message text
lblMessage.Text = "";// Set page index
((GridView) sender).PageIndex = e.NewPageIndex;BindData();
}
• Add the following code to the gvCart_PageIndexChanging method.
[Visual Basic]
' Cancel paging operation if user attempts to navigate
' to another page while in edit mode
If CType(sender, GridView).EditIndex <> -1 Then
' Cancel paging operatione.Cancel = True
' Display error messageDim newPageIndex As Integer = e.NewPageIndex + 1
lblMessage.Text = "Update the item before moving to
page " &newPageIndex.ToString()
Else
' Clear message text
lblMessage.Text = ""' Set page index
CType(sender, GridView).PageIndex = e.NewPageIndex
BindData()End If
[Visual C#]
// Cancel paging operation if user attempts to navigate
// to another page while in edit modeif (((GridView) sender).EditIndex != -1)
{// Cancel paging operatione.Cancel = true;
// Display error message
int newPageIndex = e.NewPageIndex + 1;
lblMessage.Text = "Update the item before moving topage " +
newPageIndex.ToString();
}else
{// Clear message textlblMessage.Text = "";
// Set page index
((GridView) sender).PageIndex = e.NewPageIndex;BindData();
}
5. Save and close the ShoppingCart files.
a. In the AdventureWorks – Microsoft Visual Studio window, on the File menu, click Save All.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 345/449
Lab Answer Key: Optimizing Data Management for Web Forms 17
b. In the ShoppingCart.aspx.vb or ShoppingCart.aspx.cs window, click the Close button.
c. In the ShoppingCart.aspx window, click the Close button.
6. Build the project and fix any errors.
• In the AdventureWorks – Microsoft Visual Studio window, on the Build menu, click BuildAdventureWorks.
Task 9: Test GridView control
1. Run the application.
• Press CTRL+F5.
2. On the Home page, in the Product Categories list, click Bike Stands, and then click Submit.
3. On the Products page, in the Bike Stands list, click All-Purpose Bike Stand.
4. On the Product Detail page, click Order.
5. On the Shopping Cart page, click Edit.
6. In the Quantity box, type 5, and then click Update.
The Quantity and Total Price columns are updated.
7. On the Shopping Cart page, click Continue Shopping.
8. On the Home page, in the Product Categories list, click Cranksets, and then click Submit.
9. On the Products page, in the Cranksets list, click HL Crankset.
10. On the Product Detail page, click Order.
Note: Observe that the customized pager has been added to the GridView, now that more items than
the specified page size have been added to the GridView.
11. On the Shopping Cart page, in the GridView pager, click 2.
The page index is changed and the content is updated appropriately.
12. Close Windows® Internet Explorer®.
13. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 3: Using ListView, DetailsView and Charts
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\VB\Lab 08\Starter\Exercise 03 or
D:\Lab Files\CS\Lab 08\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\VB\Lab08\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\CS\Lab 08\Starter\Exercise03\AdventureWorks.sln, and then click Open.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 346/449
18 Lab 8A: Optimizing Data Management for Web Forms
Task 2: Create the Sales Orders Master Details view
1. Build the project.
• In the AdventureWorks – Microsoft Visual Studio window, on the Build menu, click BuildAdventureWorks.
2. Open the SalesOrders.aspx content page in Design view.
• In Solution Explorer, right-click SalesOrders.aspx, and then click View Designer.
3. Place the cursor in the HTML p element at the bottom of the MainContent Content control.
4. Add a ListView control named SalesOrdersListView to the p element.
a. In the Toolbox, expand Data, and the double-click ListView.
b. In the Properties window, in the (ID) box, type SalesOrdersListView.
5. Add a new LinqDataSource control, by using the SalesOrdersListView Smart Tag.
a. On the SalesOrdersListView control, click the Smart Tag.
b. In the ListView Tasks dialog box, in the Choose Data Source list, click <New data source…>.
6. Use LINQ as the data source, and name the LinqDataSource control SalesOrdersLinqDataSource,by using the Data Source Configuration Wizard.
• In the Data Source Configuration Wizard, on the Choose a Data Source Type page, click LINQ,
in the Specify an ID for the data source box, type SalesOrdersLinqDataSource, and then click
OK .
7. Select the AdventureWorks.AdventureWorksLT2008Entities object context from the existing
Entity Data Model as the object context for the LinqDataSource control.
• In the Data Source Configuration Wizard, on the Choose a Context Object page, in the Choose your context object list, click AdventureWorks.AdventureWorksLT2008Entities, and then
click Next.
8. Select the SalesOrderHeaders table and include the SalesOrderID, OrderDate, DueDate, ShipDate
and CustomerID fields for the LinqDataSource control.
• In the Data Source Configuration Wizard, on the Configure Data Selection page, in the Table
list, click SalesOrderHeaders (ObjectSet<SalesOrderHeader>), and in the Select list, click
SalesOrderID, OrderDate, DueDate, ShipDate, and CustomerID.
9. Select only sales orders that have already shipped, by specifying a where clause, and compare
ShipDate with the DateTime.Now method.
a. In the Data Source Configuration Wizard, on the Configure Data Selection page, click Where.
b. In the Configure Where Expression dialog box, in the Column list, click ShipDate, in the
Operator list, click <=, in the Source list, click None, in the Parameter properties section, in the
Value box, type DateTime.Now, and then click Add.
c. In the Configure Where Expression dialog box, click OK .
10. Order the sales orders by CustomerID and ShipDate, by specifying an Order By clause.
a. In the Data Source Configuration Wizard, on the Configure Data Selection page, click OrderBy.
b. In the Configure OrderBy Expression dialog box, in the Sort by area, in the list, click
CustomerID, in the top most Then by area, in the list, click ShipDate, and then click OK .
11. Finish the Data Source Configuration Wizard.
• In the Data Source Configuration Wizard, on the Configure Data Selection page, click Finish.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 347/449
Lab Answer Key: Optimizing Data Management for Web Forms 19
12. Set the SalesOrderID field as the DataKeyNames property value.
• In the Property window, in the DataKeyNames box, type SalesOrderID.
13. Open the SalesOrders.aspx web form in Source view.
• In the SalesOrders.aspx window, click Source.
14. Remove the WhereParameters element from the LinqDataSource control.• In the SalesOrders.aspx window, locate and delete the following markup.
<WhereParameters>
<asp:Parameter DefaultValue="DateTime.Now" Name="ShipDate"Type="DateTime" />
</WhereParameters>
15. Modify the Where property to appear as follows.
Where="ShipDate <= DateTime.Now"
16. Open the SalesOrders.aspx web form in Design view.
• In the SalesOrders.aspx window, click Design.
17. Save the changes.
• In the SalesOrders.aspx window, on the File menu, click Save SalesOrders.aspx, or press
CTRL+S.
18. Configure the SalesOrdersListView control, by using the SalesOrdersListView Smart Tag. Refresh
the schema before configuring the control.
a. On the SalesOrdersListView control, click the Smart Tag.
b. In the ListView Tasks dialog box, click Refresh Schema, and then click Configure ListView.
19. Select the Grid layout and the Professional style for the SalesOrdersListView control.
• In the Configure ListView dialog box, in the Select a Layout list, click Grid, and in the Select aStyle list, click Professional.
20. Enable paging for the SalesOrdersListView control.
a. In the Configure ListView dialog box, select the Enable Paging check box, and then click OK .
b. In the Microsoft Visual Studio dialog box, click Yes.
21. Disable editing and inserting a SalesOrderHeader item in the SalesOrdersListView control, by
deleting the corresponding templates in Source view.
a. In the SalesOrders.aspx window, click Source.
b. Select and delete the EditItemTemplate and InsertItemTemplate elements and the content.
22.
Add a Select button to the AlternatingItemTemplate and ItemTemplate elements. Use the Button server control and place it at the top of the HTML tr element.
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select"/>
</td>
a. In the SalesOrders.aspx window, insert the following markup at the top of the HTML tr element
within the AlternatingItemTemplate element.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 348/449
20 Lab 8A: Optimizing Data Management for Web Forms
b. In the SalesOrders.aspx window, insert the following markup at the top of the HTML tr element
within the ItemTemplate element.
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select"/>
</td>
23. Add an empty HTML th element to the LayoutTemplate element. Make the th element a server
control and place it at the top of the HTML tr element.
<th runat="server">
</th>
• In the SalesOrders.aspx window, insert the following markup at the top of the HTML tr element
within the itemPlaceholderContainer table element in the LayoutTemplate element.
<th runat="server">
</th>
24. Add an empty HTML td element to the SelectedItemTemplate element. Place it at the top of the
HTML tr element.
<td>
</td>
• In the SalesOrders.aspx window, insert the following markup at the top of the HTML tr element
within the SelectedItemTemplate element.
<td>
</td>
25. Add an empty HTML p element below the existing p element.
<p></p>
• In the SalesOrders.aspx window, insert the following markup below the existing p element.
<p>
</p>
26. Add a new LinqDataSource control with the following markup, within the empty HTML p element.
<asp:LinqDataSource ID="SalesOrderDetailsLinqDataSource"
runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"
EntityTypeName="" TableName="SalesOrderDetails"Where="SalesOrderID == @SalesOrderID">
<WhereParameters>
<asp:ControlParameter ControlID="SalesOrdersListView"Name="SalesOrderID" PropertyName="SelectedValue"
Type="Int32" DefaultValue="0" />
</WhereParameters>
</asp:LinqDataSource>
• In the SalesOrders.aspx window, insert the following markup within the empty p element.
<asp:LinqDataSource ID="SalesOrderDetailsLinqDataSource"
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 349/449
Lab Answer Key: Optimizing Data Management for Web Forms 21
runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"
EntityTypeName="" TableName="SalesOrderDetails"Where="SalesOrderID == @SalesOrderID">
<WhereParameters>
<asp:ControlParameter
ControlID="SalesOrdersListView" Name="SalesOrderID" PropertyName="SelectedValue"Type="Int32" DefaultValue="0" />
</WhereParameters></asp:LinqDataSource>
27. Add a DetailsView control with the following markup, at the top of the new HTML p element.
<asp:DetailsView ID="SalesOrderDetailDetailsView"
runat="server" DataSourceID="SalesOrderDetailsLinqDataSource"
Height="50px" Width="125px" AutoGenerateRows="False">
<Fields><asp:BoundField DataField="SalesOrderDetailID"
HeaderText="SalesOrderDetailID"SortExpression="SalesOrderDetailID" />
<asp:BoundField DataField="OrderQty"
HeaderText="OrderQty" SortExpression="OrderQty" /><asp:BoundField DataField="ProductID"
HeaderText="ProductID" SortExpression="ProductID" />
<asp:BoundField DataField="UnitPrice"HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitPriceDiscount" HeaderText="UnitPriceDiscount"
SortExpression="UnitPriceDiscount" /><asp:BoundField DataField="LineTotal"
HeaderText="LineTotal" SortExpression="LineTotal" />
<asp:BoundField DataField="rowguid"HeaderText="rowguid" SortExpression="rowguid" />
<asp:BoundField DataField="ModifiedDate"
HeaderText="ModifiedDate" SortExpression="ModifiedDate" /></Fields>
</asp:DetailsView>
• In the SalesOrders.aspx window, insert the following markup at the top of the new p element.
<asp:DetailsView ID="SalesOrderDetailDetailsView"
runat="server" DataSourceID="SalesOrderDetailsLinqDataSource"Height="50px" Width="125px" AutoGenerateRows="False"><Fields>
<asp:BoundField DataField="SalesOrderDetailID"HeaderText="SalesOrderDetailID"
SortExpression="SalesOrderDetailID" />
<asp:BoundField DataField="OrderQty"HeaderText="OrderQty" SortExpression="OrderQty" />
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" SortExpression="ProductID" /><asp:BoundField DataField="UnitPrice"
HeaderText="UnitPrice" SortExpression="UnitPrice" /><asp:BoundField DataField="UnitPriceDiscount"
HeaderText="UnitPriceDiscount"
SortExpression="UnitPriceDiscount" />
<asp:BoundField DataField="LineTotal"HeaderText="LineTotal" SortExpression="LineTotal" />
<asp:BoundField DataField="rowguid"
HeaderText="rowguid" SortExpression="rowguid" />
<asp:BoundField DataField="ModifiedDate"HeaderText="ModifiedDate" SortExpression="ModifiedDate" />
</Fields>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 350/449
22 Lab 8A: Optimizing Data Management for Web Forms
</asp:DetailsView>
Task 3: Test Master Details view
1. Run the application.
• Press CTRL+F5.
2. On the Sales Orders page, click Select, for any item in the ListView control.
Note: Notice how the DetailsView containing the Sales Order Details is displayed below the ListView
control.
3. Close Windows® Internet Explorer®.
Task 4: Create Sales Order Items History dashboard
1. Open the SalesOrderItemsHistory.aspx content page in Source view.
• In Solution Explorer, right-click SalesOrderItemsHistory.aspx, and then click View Markup.
2. Add an EntityDataSource control named SalesOrderItemsEntityDataSource to the MainContent Content control.
<asp:EntityDataSource ID="SalesOrderItemsEntityDataSource"
runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"CommandText="SELECT Headers.SalesOrderNumber,
Headers.OrderDate, SUM(Details.OrderQty) AS SalesOrderItems
FROM SalesOrderHeaders AS Headers INNER JOINSalesOrderDetails AS Details ON Headers.SalesOrderID =
Details.SalesOrderID
GROUP BY Headers.SalesOrderID, Headers.SalesOrderNumber,Headers.OrderDate"
ConnectionString="name=AdventureWorksLT2008Entities"
DefaultContainerName="AdventureWorksLT2008Entities"EnableFlattening="False">
</asp:EntityDataSource>
• In the SalesOrderItemsHistory.aspx window, place the cursor between the opening and closing
MainContent tags, and type the following markup.
<asp:EntityDataSource ID="SalesOrderItemsEntityDataSource"
runat="server"
ContextTypeName="AdventureWorks.AdventureWorksLT2008Entities"CommandText="SELECT Headers.SalesOrderNumber,
Headers.OrderDate, SUM(Details.OrderQty) AS SalesOrderItems
FROM SalesOrderHeaders AS Headers INNER JOINSalesOrderDetails AS Details ON
Headers.SalesOrderID = Details.SalesOrderID
GROUP BY Headers.SalesOrderID,Headers.SalesOrderNumber, Headers.OrderDate"
ConnectionString="name=AdventureWorksLT2008Entities"
DefaultContainerName="AdventureWorksLT2008Entities"EnableFlattening="False">
</asp:EntityDataSource>
3. Open the SalesOrderItemsHistory.aspx content page in Design view.
• In the SalesOrderItemsHistory.aspx window, click Design.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 351/449
Lab Answer Key: Optimizing Data Management for Web Forms 23
4. Add a Chart control named SalesOrderItemsHistoryChart.
a. In the Toolbox, expand Data, and then double-click Chart.
b. In the Properties window, in the (ID) box, type SalesOrderItemsHistoryChart.
5. Set the Chart type to Bar by using the Smart Tag.
a. With the SalesOrderItemsHistoryChart selected, click the Smart Tag.b. In the Chart Type list, click Bar.
6. Use the SalesOrderItemsEntityDataSource control as the data source. By using the DataSourceID
property, the X values should come from the SalesOrderItems field, the Y values should come from
the OrderDate field. Refresh the schema, after selecting the data source control.
a. With the SalesOrderItemsHistoryChart selected, click the Smart Tag.
b. In the Choose Data Source list, click SalesOrderItemsEntityDataSource.
c. Click Refresh Schema.
d. In the X Value Member list, click SalesOrderItems.
e.
In the Y Value Member list, click OrderDate.7. Modify the default chart area, by setting the X and Y axis titles to # Sales Order Items and Order
Date. Use the ChartArea Collection Editor, accessible from the Properties window.
a. In the Properties window, in the ChartAreas box, click the ellipsis button.
b. In the ChartArea Collection Editor, in the ChartArea1 properties list, in the Axes box, click the
ellipsis button.
c. In the Axis Collection Editor, in the X axis properties list, in the Title box, type # Sales OrderItems.
d. In the Members list, click Y (Value) axis, in the Y (Value) axis properties list, in the Title box,
type Order Date, and then click OK .
e. In the ChartArea Collection Editor, click OK.
Task 5: Test Master Details view
1. Run the application.
• Press CTRL+F5.
Note: Notice how the Chart shows how the number of items per order is shown by order date.
2. Close Windows Internet Explorer.
3. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 352/449
24 Lab 8A: Optimizing Data Management for Web Forms
4. In the Revert Virtual Machine dialog box, click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 353/449
Lab Answer Key: Optimizing Data Management for Web Forms 25
Lab 8B: Optimizing Data Management for WebFormsExercise 4: Managing Data by Using ASP.NET Dynamic Data
Task 1: Create New ASP.NET Dynamic Data 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 Studio2010, and then click Microsoft Visual Studio 2010.
3. Create an ASP.NET Dynamic Data Web application named AWDynamicData by using the NewProject dialog box, and the ASP.NET Dynamic Data Entities Web Application project template.
Place the project in the D:\Lab Files\VB\Lab 08\Starter\Exercise 04 or D:\Lab Files\CS\Lab08\Starter\Exercise 04 folder.
a. On the File menu, click New Project.
b. In the New Project dialog box, in the left pane, click Visual Basic or Visual C#.
c. In the middle pane, click ASP.NET Dynamic Data Entities Web Application.
d. In the Name box, type AWDynamicData, in the Location box, type D:\Lab Files\VB\Lab08\Starter\Exercise 04 or D:\Lab Files\CS\Lab 08\Starter\Exercise 04 and then click OK.
Task 2: Add New ADO.NET Entity Data Model
1. Add an ADO.NET Entity Data Model project item named AWEDM.edmx.
a. In Solution Explorer, right-click AWDynamicData, point to Add, and then click New Item.
b. In the Add New Item - AWDynamicData dialog box, in the left pane, click Data, in the middle
pane, click ADO.NET Entity data Model.
c. In the Name box, type AWEDM.edmx, and then click Add.
2. Generate the model from the AdventureWorksLT2008R2 database, on the .\SQLEXPRESS server,
and select only the Customer (SalesLT), SalesOrderDetail (SalesLT), and SalesOrderHeader(SalesLT) tables.
a. In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate from
database, and then click Next.
b. On the Choose Your Data Connection page, click New Connection.
c. In the Choose Data Source dialog box, in the Data source list, click Microsoft SQL Server, and
then click Continue.
d.
In the Connection Properties dialog box, in the Server name box, type .\SQLEXPRESS.e. In the Select or enter a database name list, click AdventureWorksLT2008R2, and then click
OK .
f. In the Entity Data Model Wizard, on the Choose Your Data Connection page, click Next.
g. On the Choose Your Database Objects page, on the Which database objects do you want to
include in your model? list, expand Tables, click Customer (SalesLT), SalesOrderDetail(SalesLT), SalesOrderHeader (SalesLT), and then click Finish.
3. Save and close the AWEDM.edmx file.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 354/449
26 Lab 8B: Optimizing Data Management for Web Forms
a. On the File menu of Visual Studio 2010, click Save AWEDM.edmx.
b. In the AWEDM.edmx window, click the Close button.
Task 3: Register Object Context
1. In the Global.asax.vb or Global.asax.cs file, add context registration to the RegisterRoutes procedure,
registering all tables for the AWDynamicData.AdventureWorksLT2008R2Entities object context.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AWDynamicData.AdventureWorksLT2008R2Entities),
New ContextConfiguration() With {.ScaffoldAllTables = True})
[Visual C#]
DefaultModel.RegisterContext(typeof(AWDynamicData.AdventureWorksLT2008R2Entities),
new ContextConfiguration()
{ScaffoldAllTables = true
});
• In the Global.asax.vb or Global.asax.cs window, add the following code at the top of to the
RegisterRoutes procedure.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AWDynamicData.AdventureWorksLT2008R2Entities
),New ContextConfiguration() With {.ScaffoldAllTables = True})
[Visual C#]
DefaultModel.RegisterContext(typeof(AWDynamicData.AdventureWorksLT2008R2Entities)
,new ContextConfiguration(){
ScaffoldAllTables = true
});
2. Save and close the Global.asax.vb or Global.asax.cs file.
a. On the File menu of Visual Studio 2010, click Save Global.asax.vb or Save Global.asax.cs.
b. In the Global.asax.vb or Global.asax.cs window, click the Close button.
Task 4: Run the Application
1. Build and run the Web application.
• On the Debug menu of Visual Studio 2010, click Start Without Debugging.
Note: The page displayed in the browser displays a list of the tables you added to the data model.
2. View the Customers page, showing all customers.
• In the Dynamic Data Site – Windows Internet Explorer window, click Customers.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 355/449
Lab Answer Key: Optimizing Data Management for Web Forms 27
Note: The page displays the List view that contains the data from the Customers table.
3. View the Details view, for a customer.
• In the Customers - Windows Internet Explorer window, click Details, to the left of a customer.
Note: The page displays the Details view that contains the data for the selected row from the
Customers table.
4. View the Customers page, showing all customers, by clicking Show all items.
• In the Customers - Windows Internet Explorer window, click Show all items.
5. Sort the customers by the LastName column.
• In the Customers - Windows Internet Explorer window, click LastName.
Note: The page displays the List view that contains the data of customers, sorted by last name.
6. View the sales order headers associated with the second customer displayed from the top.
• In the Customers - Windows Internet Explorer window, in the second row, under SalesOrderHeaders, click View SalesOrderHeaders.
Note: The page displays the List view that contains the data of customer sales order headers.
7. Filter the sales order headers by entries that have the OnlineOrderFlag column set to True.
• In the OnlineOrderFlag list, click True.
Note: The page now displays no sales order headers, because none of the sales order headers have the
OnlineOrderFlag set to true.
8. View the customers page.
• In the SalesOrderHeaders - Windows Internet Explorer window, press BACKSPACE twice.
9. Create a new customer, by clicking Insert new item.
• In the Customers - Windows Internet Explorer window, at the end of the page, click Insert newitem to create a new customer.
10. Save the new customer, with empty fields, and then cancel the new customer.
• In the Customers - Windows Internet Explorer window, at the end of the page, click Insert, andview the smart validation that has been added to the required fields, and then click Cancel.
Note: The page displays the List view that contains the data from the Customers table. This is the
default view and the one you are returned to, after cancelling.
11. Edit the last customer displayed.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 356/449
28 Lab 8B: Optimizing Data Management for Web Forms
• In the Customers - Windows Internet Explorer window, at the end of the page, click Edit to
modify a customer.
Note: The page displays the Edit view that contains the data for the selected row from the Customers
table.
12. Cancel the edit and close Windows Internet Explorer.
a. In the Customers - Windows Internet Explorer window, at the end of the page, click Cancel to
cancel the edit operation.
b. In the Customers - Windows Internet Explorer window, click the Close button.
13. Close Microsoft Visual Studio 2010.
• In the AWDynamicData - Microsoft Visual Studio window, click the Close button.
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 357/449
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 1
Module 9
Lab Answer Key: Ensuring Quality by Debugging, UnitTesting, and Refactoring
Contents:
Exercise 1: Configuring Error Handling 2
Exercise 2: Debugging Code 3
Exercise 3:
Logging 7
Exercise 4: Creating Unit Tests 10
Exercise 5: Implementing the Test-First/Test-Driven DevelopmentMethodology 14
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 358/449
2 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
Lab 9: Debugging, Unit Testing, andRefactoringExercise 1: Configuring Error Handling
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 Studio2010, 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:\LabFiles\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\Exercise01\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"/>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 359/449
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 SaveWeb.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 – WindowsInternet 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 Studio2010, 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:\LabFiles\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\Lab09\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise02\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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 360/449
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 – WindowsInternet 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 361/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 362/449
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 InternetExplorer.
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 363/449
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\Lab09\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise03\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));
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 364/449
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) HandlesMe.Load
If Not Page.IsPostBack ThenDim categoryName As String = String.EmptyDim categoryID As String = String.Empty
If Not Request("id") Is Nothing ThencategoryID = Request("id")
End If
Try
categoryName =AdventureWorks.DataAccessLayer.Products.GetCategoryName(Integer.Parse(categoryID))
Catch ex As ExceptionDim 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 IfEnd 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 365/449
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 – WindowsInternet 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#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 366/449
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 BuildAdventureWorks.
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 Studio2010, 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:\LabFiles\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\Lab09\Starter\Exercise 04\MyClassLibrary.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise04\MyClassLibrary.sln, and then click Open.
Task 2: Create a method to add two numbers
1. Open the Calculator.cs or Calculator.vb file.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 367/449
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 SaveCalculator.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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 368/449
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
valueDim 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 valueDim 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 369/449
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 valueint 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
valueDim p1 As Integer = 2 ' TODO: Initialize to an appropriate valueDim p2 As Integer = 3 ' TODO: Initialize to an appropriate value
Dim expected As Integer = 6 ' TODO: Initialize to an appropriate value
Dim actual As Integeractual = 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 370/449
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\Lab09\Starter\Exercise 05\MyClassLibrary.sln or D:\Lab Files\VB\Lab 09\Starter\Exercise05\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()
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 371/449
Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring 15
Assert.IsNotNull(target)
Dim expected As Integer = 6Dim unexpected As Integer = 5Dim 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 = 6Dim 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 SaveCalculatorTest.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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 372/449
16 Lab Answer Key: Ensuring Quality by Debugging, Unit Testing, and Refactoring
• In the MyClassLibrary – Microsoft Visual Studio window, on the Build menu, click BuildSolution 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 IntegerReturn 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 373/449
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 BuildSolution 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 374/449
Lab Answer Key: Securing a Web Application 1
Module 10
Lab Answer Key: Securing a Web ApplicationContents:
Exercise 1: Configuring ASP.NET Membership and Roles 2
Exercise 2: Authentication 3
Exercise 3: Authorization 8
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 375/449
2 Lab Answer Key: Securing a Web Application
Lab 10: Securing a Web ApplicationExercise 1: Configuring ASP.NET Membership and Roles
f 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 Studio2010, 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:\LabFiles\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\Lab10\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 10\Starter\Exercise01\AdventureWorks.sln, and then click Open.
f 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, clickSecurity.
5. Click Select authentication type.
6. Click From the internet, and then click Done.
f 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-mailSecurityQuestion Security Answer
Mary Pa$$w0rd [email protected] Favorite pet Cat
• In the User Name box, type Mary, in the Password box, type Pa$$w0rd, in the ConfirmPassword box, type Pa$$w0rd, in the E-mail box, type [email protected], in theSecurity 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 376/449
Lab Answer Key: Securing a Web Application 3
UserName Password E-mail
SecurityQuestion Security Answer
John Pa$$w0rd [email protected] 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 [email protected], in theSecurity Question box, type High School, in the Security Answer box, type Central.
6. Click Create User.
7. Click Continue.
f 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, clickSecurity.
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.
f 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 theClose button.
9. Close Visual Studio 2010.• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 2: Authentication
f Task 1: Open an existing ASP.NET web application
1. Open Microsoft Visual Studio 2010.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 377/449
4 Lab Answer Key: Securing a Web Application
• On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio2010, 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:\LabFiles\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\Lab10\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 10\Starter\Exercise02\AdventureWorks.sln, and then click Open.
f 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 Fromthe 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>
f Task 3: Use the Login control1. 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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 378/449
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 isrequired." 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 followingmarkup 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.
f 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#]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 379/449
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 userif (Membership.ValidateUser(LoginUser.UserName.Trim(),
LoginUser.Password.Trim()))e.Authenticated = true;
}
}
[Visual Basic]
Protected Sub LoginUser_Authenticate(ByVal sender As Object, ByVal e AsAuthenticateEventArgs) 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 380/449
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.
f Task 5: Configure password recovery
1. Add a new Web Form named EmailPassword to the Account folder. The Web Form must be basedon 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 Formusing 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, andthen click OK .
2. Drag a PasswordRecovery server control from the Login section of the Toolbox to theEmailPassword.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="[email protected]">
<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="[email protected]"><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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 381/449
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
f 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 Studio2010, 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:\LabFiles\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\Lab10\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 10\Starter\Exercise03\AdventureWorks.sln, and then click Open.
f Task 2: Allow anonymous access to the EmailPassword Web Form1. 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.
f 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 bebased 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 Formusing 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, andthen click OK .
3. Add the following header to the Home.aspx Web Form.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 382/449
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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 383/449
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® 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.
• In the Username box, type Mary, in the Password box, type Pa$$w0rd, and then click Log In.
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.
• In the http://localhost:xxxx/Contributors/Home.aspx – Windows Internet Explorer window, clickthe Close button.
10. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
f 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 clickTurn 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 clickRevert.
4. In the Revert Virtual Machine dialog box, click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 384/449
Lab Answer Key: Applying Master Pages and CSS 1
Module 11
Lab Answer Key: Applying Master Pages and CSS
Contents:
Exercise 1: Modify a Master Page 2
Exercise 2: Create a Nested Master Page 4
Exercise 3: Integrate a Master Page 7
Exercise 4: Implement Control Skins 11 Exercise 5: Apply Styles and Themes 12
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 385/449
2 Lab Answer Key: Applying Master Pages and CSS
Lab 11: Applying Master Pages and CSSExercise 1: Modify a Master Page
f 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 Studio2010, 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:\LabFiles\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\Lab11\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starter\Exercise01\AdventureWorks.sln, and then click Open.
f 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.
f 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" />
f 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.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 386/449
Lab Answer Key: Applying Master Pages and CSS 3
<asp:Content ID="PageFooterContent" runat=”="server"”
ContentPlaceHolderID="FooterContent">
</asp:Content>
f 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
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 387/449
4 Lab Answer Key: Applying Master Pages and CSS
Exercise 2: Create a Nested Master Page
f 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\Lab11\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starter\Exercise02\AdventureWorks.sln, and then click Open.
f 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 MasterPage, 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 388/449
Lab Answer Key: Applying Master Pages and CSS 5
f 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>
f 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
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 389/449
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 390/449
Lab Answer Key: Applying Master Pages and CSS 7
f 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
f 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 Studio2010, 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:\LabFiles\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\Lab11\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starter\Exercise03\AdventureWorks.sln, and then click Open.
f Task 2: Open the Site.Master master page
• Open the Site.Master file.
• In Solution Explorer, double-click Site.Master.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 391/449
8 Lab Answer Key: Applying Master Pages and CSS
f 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" />
f 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
GetReturn StatusMessageLabel.Text
End Get
Set(ByVal value As String)StatusMessageLabel.Text = value
End Set
End Property
f 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" %>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 392/449
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));
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 393/449
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) HandlesMe.Load
If Not Page.IsPostBack Then
Dim categoryName As String = NothingDim 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 = datagvProducts.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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 394/449
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
f 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
f
kin file with the following markup.
9. Close Visual Studio 2010.
• In the AdventureWor
ercise 4: Implement Control Skins
f Task 1: Open an existing ASP.NET we
1. Open Microsoft Visual Studio 2010.
• On the Start menu of 10264A-G
2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\ Files\VB\Lab 11\Starter\Exercise 04 folder.
a. In the Start Page – Microsoft Visual Stud
b. In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab
11\Starter\Exercise 04\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starte04\AdventureWorks.sln, and then click Open.
Task 2: Create a new theme named Default
• Add new theme folder named Default to projec
a. In Solution Explorer, right-click AdventureWoand then click Theme.
b. In the text box, type De
f Task 3: Create a Controls.skin file in the Default them
• Add a new skin file named Controls.skin to the Default theme fol
a. In Solution Explorer, under App_Themes, right-click Default, point toItem.
b. In the Add New Item – AdvName box, type Controls.skin, and then click Add.
Task 4: Create two standard control skins
1. Replace the existing markup in the Controls.s
<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"/>
a. nd then press DELETE.In the Controls.skin window, press CTRL+A, a
b. Type 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"/>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 395/449
12 Lab Answer Key: Applying Master Pages and CSS
2. Save
• In click the Close button.
ontrol
spx.
ge directive.
and close the Controls.skin file.
the Controls.skin window, press CTRL+S, and then
f Task 5: Apply one skin to a ListBox c
1. Open the Default.aspx Web Form.
• In Solution Explorer, double-click Default.a
2. Add the following markup to the Pa
<%@ Page Title="Home Page" ... Theme="Default" %>
• In the Default.aspx window, in the Page directive, append the following markup.
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">
• ing markup.In the Default.aspx window, in the opening ListBox tag, append the follow
SkinID="BlueListBox"
4. Run the application.
• P
blue background color in the ListBox control.
ress CTRL+F5.
Note: Observe the light
5. Close Windows Internet Explorer.
• In the Home Page – Windows Internet Explorer window, click the Close button.
.
Themes
f Task 1: Open an existing ASP.NET web application
l Programs, click Microsoft Visual Studio.
name box, type D:\Lab Files\CS\Lab
6. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button
Exercise 5: Apply Styles and
1. Open Microsoft Visual Studio 2010.
• On the Start menu of 10264A-GEN-DEV, point to Al2010, and then click Microsoft Visual Studio 2010
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 11\Starter\Exercise 05 or D:\LabFiles\VB\Lab 11\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 File11\Starter\Exercise 05\AdventureWorks.sln or D:\Lab Files\VB\Lab 11\Starter\Exercise05\AdventureWorks.sln, and then click Open.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 396/449
Lab Answer Key: Applying Master Pages and CSS 13
f 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:\LabFiles\CS\Lab 11\Starter\Exercise 05 or D:\Lab Files\VB\Lab 11\Starter\Exercise 05 folder.
t to Add, and then click Existing Item.
b
hen
f Task 3: Modify the existing styles
• In Solution Explorer, under Styles, double-click StyleB.css.
the .header class by using the Modify Style dialog box.
n the left side, point to CSSader, and then click Build Style.
4. Change the background color to Red, and close the Modify Style dialog box.
• In the Modify Style dialog box, on the background color list, click Red, and then click OK .
5. Save and close the StyleB.css file.
• In the StyleB.css window, press CTRL+S, and then click the Close button.
a. In Solution Explorer, right-click Styles, poin
b. In the Add Existing Item – AdventureWorks dialog box, in the File name box, type D:\La
Files\CS\Lab 11\Starter\Exercise 05 or D:\Lab Files\VB\Lab 11\Starter\Exercise 05, and tclick Add.
c. In the Add Existing Item – AdventureWorks dialog box, in the right pane, select StyleA.css
and StyleB.css, and then click Add.
1. Open the StyleB.css file.
2. In the CSS Outline window, modify
• In the AdventureWorks – Microsoft Visual Studio window, o
Outline or Document Outline, expand Classes, right-click
3. In the Modify Style dialog box, select the Background category.
.he
• In the Modify Style dialog box, on the Category list, click Background.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 397/449
14 Lab Answer Key: Applying Master Pages and CSS
f Task 4: Create two themes based on existing styles
1. Create two new folders named Blue and Red, in the App_Themes folder.
dd ASP.NET Folder, and
then click Theme.
Blue and press ENTER.
, point to Add, point to Add ASP.NET Folder, and
then click Theme.
Red, and then press ENTER.
nd drag StyleA.css to App_Themes\Blue.
nd drag StyleB.css to App_Themes\Red.
k Default.aspx.ox control.
a. In Solution Explorer, right-click App_Themes, point to Add, point to A
b. In the textbox, type
c. In Solution Explorer, right-click App_Themes
d. In the text box, type
2. Move the StyleA.css file to the Blue folder.
• In Solution Explorer, under Styles, click a
3. Move the StyleB.css file to the Red folder.
• In Solution Explorer, under Styles, click a
4. Open the Default.aspx Web Form.
• In Solution Explorer, double-clic
5. Remove the SkinId attribute and value from the ListB
SkinID="BlueListBox"
• indow, in the markup for the lbCategories ListBox control, delete the
following markup.
In the Default.aspx w
SkinID="BlueListBox"
6. Remo d value from the Page directive.ve the theme attribute an
Theme="Default"
• spx window, in the markup for the Page directive, delete the following markup.In the Default.a
Theme="Default"
7. Save lt.aspx file.
s CTRL+S, and then click the Close button.
uble-click Web.config.
e pages element with the theme attribute to the
system.web element.
and close the Defau
• In the Default.aspx window, pres
f Task 5: Change the theme in the Web.config file
1. Open the Web.config file.
• In Solution Explorer, do
2. Set the global page theme to the Red, by adding th
<pages theme="Red"/>
</system.web>
• nfig window, add the following markup to the system.web element, just before
the closing system.web tag.
In the Web.co
<pages theme="Red"/>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 398/449
Lab Answer Key: Applying Master Pages and CSS 15
3. Save file.
• In the Web.config window, press CTRL+S, and then click the Close button.
1. Run the application.
colors and slightly different layout.
and close the Web.config
f Task 6: Test the new theme
• Press CTRL+F5.
Note: Observe the new
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.
1. In Hyper-V™ Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click
f Task 7: Turn off the virtual machine and revert the changes
Turn Off .
2. In the Turn Off Machine dialog box, click Turn Off .
Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 399/449
Lab Answer Key: Developing Client-side Scripts and Services 1
Module 12
Lab Answer Key: Developing Client-side Scripts and ServicesContents:
Exercise 1: Using jQuery 2
Exercise 2: Using Advanced jQuery 6
Exercise 3: Creating a WCF Service 8
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 400/449
2 Lab Answer Key: Developing Client-side Scripts and Services
Lab 12: Creating Client-side Scripts and ServicesExercise 1: Using jQuery
f 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 Studio2010, 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:\LabFiles\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\Lab12\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 12\Starter\Exercise01\AdventureWorks.sln, and then click Open.
f 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 401/449
Lab Answer Key: Developing Client-side Scripts and Services 3
f 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, clickBike 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>
f 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)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 402/449
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) HandlesMe.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 ThengvCart.UseAccessibleHeader = TruegvCart.HeaderRow.TableSection = TableRowSection.TableHeadergvCart.FooterRow.TableSection = TableRowSection.TableFooter
End IfEnd 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 403/449
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
•
•
Bike Stands, and then click Submit.
•
click All-Purpose Bike Stand.
•
window, click Order.
•
Continue Shopping.
•
Bib-Shorts, and then click Submit.
•
click Men's Bib-Shorts, L.
•
window, click Order.
•
the View menu, click Source.
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 404/449
6 Lab Answer Key: Developing Client-side Scripts and Services
• In the http://localhost:xxxxx/ShoppingCart.aspx – Original Source window, click the Close
button.
14. Click the ID column header.
• In the on the different column headers and it will sort the data in ascending and descending
order
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.
• In the Home Page – Windows Internet Explorer window, click the Close button.
16. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 2: Using Advanced jQuery
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 12\Starter\Exercise 02 or D:\LabFiles\VB\Lab 12\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\Lab12\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 12\Starter\Exercise02\AdventureWorks.sln, and then click Open.
f Task 2: Implement jQuery events and effects
1. Open the Products.aspx Web Form.
• In Solution Explorer, double-click Products.aspx.
2. Locate the markup for the GridView control named gvProducts.
• In the Products.aspx window, 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>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 405/449
Lab Answer Key: Developing Client-side Scripts and Services 7
• In the Products.aspx window, add the following markup to the Columns element of the
gvProducts GridView control. Add it after the BoundField control, with a DataField attribute
value of ListPrice.
<asp:TemplateField HeaderText="Ad"> <ItemTemplate>
<div style="display: none">
Advertisement for <%# Eval("Name") %>
</div> </ItemTemplate>
</asp:TemplateField>
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>
• In the Products.aspx window, add the following script element to the Products.aspx Web
Form, at the end of the Content control with an ID attribute value of BodyContent. Add it after
the closing p tag.
<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>
5. Run the application.
• Press CTRL+F5.
On the Products page, hover the mouse over the name of the product.
Note: The custom advertisement message is displayed in the rightmost column.
6. Close Windows Internet Explorer.
• In the http://localhost:xxxxx/Products.aspx – Windows Internet Explorer window, click the
Close button.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 406/449
8 Lab Answer Key: Developing Client-side Scripts and Services
f 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">
$(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.
• Press CTRL+F5.
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.
• In the http://localhost:xxxxx/Products.aspx – 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 3: Creating a WCF Service
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 12\Starter\Exercise 03 or D:\LabFiles\VB\Lab 12\Starter\Exercise 03 folder.
a. In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 407/449
Lab Answer Key: Developing Client-side Scripts and Services 9
b. In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab12\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 12\Starter\Exercise03\AdventureWorks.sln, and then click Open.
f Task 2: Create an Ajax-enabled WCF service
• Add a new Ajax-enabled WCF service named ProductsService to the project.
a. In Solution Explorer, right-click AdventureWorks, point to Add, and then click New Item.
b. In the Add New Item - AdventureWorks dialog box, in the middle pane, click Ajax-enabledWCF Service, in the Name box, type ProductsService.svc, and then click Add.
f 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 isWebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]public void DoWork()
{
// Add your operation implementation here
return;}
// Add more operations here and mark them with [OperationContract]
[Visual Basic]' To use HTTP GET, add <WebGet()> attribute. (Default ResponseFormat is
WebMessageFormat.Json)
' To create an operation that returns XML,' add <WebGet(ResponseFormat:=WebMessageFormat.Xml)>,' and include the following line in the operation body:
' WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"
<OperationContract()>Public Sub DoWork()
' Add your operation implementation here
End Sub
' Add more operations here and mark them with <OperationContract()>
• In the ProductsService.svc window, select the following code, and then press DELETE.
[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;
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 408/449
10 Lab Answer Key: Developing Client-side Scripts and Services
}
// Add more operations here and mark them with [OperationContract]
[Visual Basic] ' To use HTTP GET, add <WebGet()> attribute. (Default ResponseFormat isWebMessageFormat.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 hereEnd 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();using (var db = new AdventureWorksEntities()){
var randomNumber = random.Next(1, db.Products.Count() + 1);var randomProduct = (from p in db.Products
where p.ProductID == randomNumberselect 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.ProductsWhere p.ProductID = randomNumberSelect New With {p.Name, p.ListPrice,
p.ProductNumber}).FirstOrDefault()
Return NewSystem.Web.Script.Serialization.JavaScriptSerializer().Serialize(randomProduct)
End UsingEnd Function
End Class
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 409/449
Lab Answer Key: Developing Client-side Scripts and Services 11
• In the ProductsService.svc window, add the following code in the ProductsService class.
[Visual C#] [OperationContract]
public string GetRandomProduct()
{
var random = new Random();
int randomNumber = 0;
using (var db = new AdventureWorksEntities()){
int count = 0;
while (count == 0)
{
randomNumber = random.Next(500, 1000);
var query = (from p in db.Products
where p.ProductID == randomNumberselect p);
count = query.Count();}
var randomProduct = (from p in db.Productswhere p.ProductID == randomNumber
select new { p.Name, p.ListPrice, p.ProductNumber
}).FirstOrDefault();
return new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(randomProduct);
}
}
[Visual Basic] <OperationContract()>
Public Function GetRandomProduct() As StringDim random = New Random()Dim randomNumber As Integer
Using db = New AdventureWorksEntities()Dim count As Integer = 0
While count = 0randomNumber = random.[Next](500, 1000)
Dim query = (From p In db.Products
Where p.ProductID = randomNumberSelect p)
count = query.Count()
End While
Dim randomProduct = (From p In db.Products
Where p.ProductID = randomNumberSelect New With {p.Name, p.ListPrice,
p.ProductNumber}).FirstOrDefault()
Return New
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(randomProduct)
End Using
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 410/449
12 Lab Answer Key: Developing Client-side Scripts and Services
End Function
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.
f Task 4: Examine the service configuration in the Web.config file
1. Open the Web.config file.
• In Solution Explorer, double-click Web.config.
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>
f Task 5: Invoke WCF service using client-side code from the master page
1. Open the Site.Master master page.
• In Solution Explorer, double-click Site.Master.
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>
• In the Site.Master window, add the following markup to the form element at the top of the
Site.Master file, after the opening form tag.
<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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 411/449
Lab Answer Key: Developing Client-side Scripts and Services 13
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;
});
}
• In the Site.Master window, append the following code to the script element at the bottom of
the Site.Master file.
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>
• In the Site.Master window, add the following markup to the div element with a class attribute
value of main, after the MainContent ContentPlaceHolder control.
<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">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 412/449
14 Lab Answer Key: Developing Client-side Scripts and Services
</label>
<br />Product Number:
<label id="ProductNumber">
</label><br />
Product Price: $<label id="ProductPrice"></label>
<br /></div>
5. Run the application.
Press CTRL+F5.
Note: The random product is displayed on the right side.
•
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.
f 1. In Hyper-V™ Manager, in the Virtual Machines pane, right-click 10
Turn Off .
Revert.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 413/449
Lab Answer Key: Implementing Advanced Ajax in a Web Application 1
Module 13
Lab Answer Key: Implementing Advanced Ajax in a WebApplication
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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 414/449
2 Lab Answer Key: Implementing Advanced Ajax in a Web Application
Lab 13: Implementing Advanced Ajax for theAdventureWorks Web ApplicationExercise 1: Using Microsoft Ajax in an MVC Page
f 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 Studio2010, 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\Exercise01\AdventureWorksMvc.sln, and then click Open.
f 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>
f 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.
[Visual C#]
public ActionResult Index(string CategoryID)
{
int id = int.Parse(CategoryID);var prodCategories = pr.GetCategories();
return View(prodCategories);
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 415/449
Lab Answer Key: Implementing Advanced Ajax in a Web Application 3
}
[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
[Visual C#]
Index method from the following:
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)
f 1. Create a strongly typed, partial view named _AjaxProductCa
Task 4: Create an Ajax Product Categories partial view
tegories, based on the
f
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
sMvc.Models.ProductCategory> or IEnumerable(Of
IEnumerable<AdventureWorksMvc.Models.ProductCategory> or IEnumerable(OAdventureWorksMvc.Models.ProductCategory) data class.
Create a partial view (.ascx) check box, select the Create a strongly-typed view check box, inthe View data class box, type
IEnumerable<AdventureWork AdventureWorksMvc.ProductCategory), and then click Add.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 416/449
4 Lab Answer Key: Implementing Advanced Ajax in a Web Application
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">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 417/449
Lab Answer Key: Implementing Advanced Ajax in a Web Application 5
</div>
<% End Using%>
f 1. Open the Index.aspx view in the Views/Products fold
Task 5: Render the Partial view on the Index view
er.
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
3. Add the following markup to the Index view, at the top of the Content2 Content control.
[Visual C#]
•
•
the Content control with an ID attribute value of Content2, and then press DELETE.
<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
5. Add the following markup to the Index view, at the top of the Content1 Content control.
•
the Content control with an ID attribute value of Content1, and then press DELETE.
Products
6. Base the Index view on a different data class, by modifying the Inherits attribute value in the Page
[Visual C#]
directive.
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AdventureWorksMvc.Models.ProductCategor
y>>"
[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
[Visual C#]
following value.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 418/449
6 Lab Answer Key: Implementing Advanced Ajax in a Web Application
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
f 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 Studio2010, 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\Lab13\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 13\Starter\Exercise02\AdventureWorksMvc.sln, and then click Open.
f 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>
f Task 3: Create the Featured Products action
1.
Open the ProductsController.cs or ProductsController.vb file in the Controllers folder.• 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)
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 419/449
Lab Answer Key: Implementing Advanced Ajax in a Web Application 7
{
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
f 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 elementat 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 theresults 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.
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 420/449
8 Lab Answer Key: Implementing Advanced Ajax in a Web Application
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
f 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 Studio2010, 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\Lab13\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 13\Starter\Exercise03\AdventureWorksMvc.sln, and then click Open.
f 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 () {$(this).text('Loading...');$('.error').text('');
});$('.log').ajaxComplete(function () {
$(this).text('');});
});
• In the Index.aspx window, add the following code:
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 421/449
Lab Answer Key: Implementing Advanced Ajax in a Web Application 9
$('.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 });
});
f 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...');
});
• 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
</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">
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 422/449
10 Lab Answer Key: Implementing Advanced Ajax in a Web Application
</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();$("#featured-products").load('<%= Url.Action("FeaturedProducts") %>',
{ CategoryId: id });});
$('.log').ajaxStart(function () {
$(this).text('Loading...');
$('.error').text('');});
$('.log').ajaxComplete(function () {
$(this).text('');});
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 423/449
Lab Answer Key: Implementing Advanced Ajax in a Web Application 11
$('.error').ajaxError(function () {
$(this).text('There was an error! Please try again later...');});
});
</script>
</asp:Content>
f Task 4: Test the Index view
1. Run the application.
• 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-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.
• 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.
f 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 clickTurn 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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 424/449
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 ProjectUsing One-Click Publish 2
Exercise 2: Creating a Web Deployment Package 5
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 425/449
2 Lab Answer Key: ASP.NET Deployments
Lab 14: Deploying AdventureWorksExercise 1: Creating a Profile for Deploying a Web Application Project UsingOne-Click Publish
f Task 1: Create a new ASP.NET web application1. 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 Studio2010, and then click Microsoft Visual Studio 2010.
3. Create a new ASP.NET Web Application named Deployment in the D:\Lab Files\CS\Lab14\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\Lab14\Starter\Exercise 01, and then click OK .
f 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: [email protected]
• 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 [email protected], in the Password box, type Pa$$w0rd, and in the
Confirm Password box, type 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.
4. Close Windows Internet Explorer.
• In the Home Page – Windows Internet Explorer window, click the Close button.
f Task 3: Set the active build configuration
1. In Solution Explorer, click Deployment.
2. On the Solutions Configuration list, click Release.
f Task 4: Specify which files and IIS settings to deploy
1. Open the Project Designer for the Deployment project.
• In Solution Explorer, right-click Deployment, and then select Properties.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 426/449
Lab Answer Key: ASP.NET Deployments 3
2. Select the Package/Publish Web tab.
• In the Deployment window, click Package/Publish Web.
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 isselected.
6. Save the changes.
• Press CTRL+S.
f Task 5: Specify which SQL Server scripts run during deployment
1. Select the Package/Publish SQL tab.
• In the Deployment window, click Package/Publish SQL.
2. Import the database settings from the Web.config file.
a. In the Deployment window, click Import from Web.config.
b. In the Microsoft Visual Studio dialog box, click OK .
3. In the Connection string for destination database box, type DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;IntegratedSecurity=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.
• In the Deployment window, in the Database scripting options list, click Schema and Data.
6. Save the changes.
• Press CTRL+S.
f 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.
• In Solution Explorer, click Deployment, and then click the Show All Files button.
2. Expand the Web.config file.
• In Solution Explorer, expand Web.config.
3. Open the Web.Release.config file.
• In Solution Explorer, double-click Web.Release.config.
4. Examine and delete the block of comments that contains a connectionStrings element.
• In the Web.Release.config window, select the following markup, and then click DELETE.
<!--
In the example below, the "SetAttributes" transform will change the value of"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an atrribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 427/449
4 Lab Answer Key: ASP.NET Deployments
connectionString="Data Source=ReleaseSQLServer;Initial
Catalog=MyReleaseDB;Integrated Security=True"xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
5. Insert the following markup after the opening configuration element.
<connectionStrings><add name="ApplicationServices"
connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;IntegratedSecurity=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.
a. Press CTRL+S.
b. In the Web.Release.config window, click the Close button.
f Task 7: Create a publish profile
1. Open the Publish Web dialog box, by clicking Publish Deployment on the Build menu.
a. In Solution Explorer, click Deployment.
b. In the Deployment – Microsoft Visual Studio window, on the Build menu, click PublishDeployment.
2. Mark the web application as an IIS application on the destination server.
• In the Publish Web dialog box, select the Mark as IIS application on destination check box.
Note: If your hosting company advises you to allow untrusted certificates, select the Allowuntrusted certificate check box.
3. Enter the credentials for the local user admin.
a. In the User name box, type admin, and then in the Password box, type Pa$$w0rd.
b. Select the Save password check box.
4.
Set the service URL to localhost.• In the Service URL box, type localhost.
5. Set the site/application URL to Default Web Site/Deployment.
• In the Site/application box, type Default Web Site/Deployment.
6. Save the profile and close the Publish Web dialog box.
• In the Publish Web dialog box, click Save, and then click Close.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 428/449
Lab Answer Key: ASP.NET Deployments 5
7. Close Visual Studio 2010.
• In the Deployment – Microsoft Visual Studio window, click the Close button.
Exercise 2: Creating a Web Deployment Package
f 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 Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the Deployment solution from the D:\Lab Files\CS\Lab 14\Starter\Exercise 02 or D:\LabFiles\VB\Lab 14\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\Lab14\Starter\Exercise 02\Deployment.sln or D:\Lab Files\VB\Lab 14\Starter\Exercise02\Deployment.sln, and then click Open.
f Task 2: Add an existing database and configure an ASP.NET web application1. 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.
a. In Solution Explorer, right-click App_Data, point to Add, and then click Existing Item.
b. In the Add Existing Item – Deployment dialog box, in the File name box, type D:\LabFiles\CS\Lab 14\Starter\AdventureWorksLT2008R2_Data.mdf or D:\Lab Files\VB\Lab14\Starter\AdventureWorksLT2008R2_Data.mdf , and then click Add.
2. Open the Web.config file.
• In Solution Explorer, double-click Web.config.
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;
Integrated Security=True;Connect Timeout=30;UserInstance=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
• In the Web.config window, in the connectionString element, add the following markup afterthe add element.
<add name="AW"
connectionString="DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AdventureWorksLT2008R2_Data.
mdf;Integrated Security=True;Connect Timeout=30;User
Instance=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 429/449
6 Lab Answer Key: ASP.NET Deployments
4. Save and close the Web.config file.
• In the Web.config window, press CTRL+S, and then click the Close button.
5. Run the application.
• In Solution Explorer, click Deployment, and then press CTRL+F5.
6. Click the Log In link.• In the Home Page – Windows Internet Explorer window, click Log In.
7. Enter credentials for the user student with a password of Pa$$w0rd, and then log in.
• In the Log In – Windows Internet Explorer window, in the Username box, type student, in the
Password box, type Pa$$w0rd, and then click Log In.
8. Close Windows Internet Explorer.
• In the Home Page – Windows Internet Explorer window, click the Close button.
f Task 3: Create a destination database
1. Open Server Explorer.
• In the Deployment – Microsoft Visual Studio window, in the right side, click Server Explorer.
2. In Server Explorer, right-click Data Connections, and then click Create New SQL Server Database.
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
4. In the Create New SQL Server Database dialog box, in the Server name box, type 10264a-gen-dev\SQLEXPRESS, in the New database name box, type DeploymentTest, and then click OK .
f Task 4: Specify deployment packaging settings
1. Open the Project Designer for the Deployment project.
• In Solution Explorer, right-click Deployment, and then select Properties.
2. Select the Package/Publish Web tab.
• In the Deployment window, click Package/Publish Web.
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 (appliesto 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
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 430/449
Lab Answer Key: ASP.NET Deployments 7
4. In the IIS Web site/application name to use on the destination server box, type Default WebSite/Deployment.
5. Save the changes.
• Press CTRL+S.
f Task 5: Specify SQL Server scripts to run during deployment1. Select the Package/Publish SQL tab.
• In the Deployment window, click Package/Publish SQL.
2. Ensure that All Configurations is selected in the Configuration list.
3. Import the database settings from the Web.config file.
a. In the Deployment window, click Import from Web.config.
b. In the Microsoft Visual Studio dialog box, click OK .
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.
a. In the Deployment – Microsoft Visual Studio window, in the right side, click Server Explorer.
b. Under Data Connections, click 10264a-gen-dev\sqlexpress.DeploymentTest.dbo.
7. Copy the value of the Connection String property from the Properties window.
• In the Properties window, in the Connection String box, select all of the text, and then press
CTRL+C.
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;IntegratedSecurity=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.
• In the Deployment window, in the Database scripting options list, click 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, DataSource=10264A-GEN-DEV\SQLEXPRESS;Initial Catalog=DeploymentTest;IntegratedSecurity=True;Pooling=False.
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 DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AdventureWorksLT2008R2_Data.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True.
15. Set the database scripting options to Schema and Data.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 431/449
8 Lab Answer Key: ASP.NET Deployments
• In the Deployment window, in the Database scripting options list, click Schema and Data.
16. Add the D:\Lab Files\CS\Lab 14\Starter\DeploymentGrant.sql or D:\Lab Files\VB\Lab14\Starter\DeploymentGrant.sql script, by clicking Add Script.
• In the Select File dialog box, in the File name box, type D:\Lab Files\CS\Lab14\Starter\DeploymentGrant.sql or D:\Lab Files\VB\Lab 14\Starter\DeploymentGrant.sql
script, and then click Open.17. Save the changes.
• Press CTRL+S.
f 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.
a. On the Start menu of 10264A-GEN-DEV, point to All Programs, click Accessories, and then
click Notepad.
b. In the Untitled – Notepad window, on the File menu, click Open.
c. In the Open dialog box, in the File name box, type D:\Lab Files\CS\Lab 14\Starter\Exercise02\Deployment\Deployment.csproj or the D:\Lab Files\VB\Lab 14\Starter\Exercise02\Deployment\Deployment.vbproj, and then click Open.
2. Open the Replace dialog box.
• In the Deployment.csproj – Notepad or Deployment.vbproj – Notepad window, on the Edit menu, click Replace.
3. In the Replace dialog box, search for Transacted="True" and replace with Transacted="False".
Replace all instances.
a. In the Replace dialog box, in the Find what box, type Transacted="True", in the Replace with
box, type Transacted="False", and then click Replace All.
b.
In the Replace dialog box, click Cancel.4. Save the changes and close the project file.
a. In the Deployment.csproj – Notepad or Deployment.vbproj – Notepad window, on the File
menu, click Save.
b. In the Deployment.csproj – Notepad or Deployment.vbproj – Notepad window, click the
Close button.
5. When Visual Studio asks if you want to reload the project, click the Reload button.
• In the File Modification Detected dialog box, click Reload.
f 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.• In Solution Explorer, click Deployment, and then click the Show All Files button.
2. Expand the Web.config file.
• In Solution Explorer, expand Web.config.
3. Open the Web.Debug.config file.
• In Solution Explorer, double-click Web.Debug.config.
4. Examine and delete the block of comments that contains a connectionStrings element.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 432/449
Lab Answer Key: ASP.NET Deployments 9
• In the Web.Debug.config window, select the following markup, and then click DELETE.
<!--In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an atrribute "name" that has a value of "MyDB".
<connectionStrings><add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;InitialCatalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
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.
a. Press CTRL+S.
b. In the Web.Debug.config window, click the Close button.
f Task 8: Create a package and import it into IIS
1. Build a deployment package by using the Project menu.
• In the Deployment – Microsoft Visual Studio window, on the Project menu, click BuildDeployment Package.
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 scripts—one 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.
• On the Start menu, click Control Panel.
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/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 433/449
10 Lab Answer Key: ASP.NET Deployments
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\Exercise02\Deployment\obj\Debug\Package\Deployment.zip or D:\Lab Files\VB\Lab14\Starter\Exercise 02\Deployment\obj\Debug\Package\Deployment.zip package.
• In the Import Application Package wizard, in the Package path box, type the D:\Lab
Files\CS\Lab 14\Starter\Exercise 02\Deployment\obj\Debug\Package\Deployment.zip orD:\Lab Files\VB\Lab 14\Starter\Exercise02\Deployment\obj\Debug\Package\Deployment.zip, and then click Next.
9. Accept the default selected contents of the package.
• In the Import Application Package wizard, on the Select the Contents of the Package page,
click Next.
10. Accept the default application paths and connection strings.
• In the Import Application Package wizard, on the Enter Application Package Information
page, click Next.
11. Click Finish.
• In the Import Application Package wizard, on the Installation Progress and Summary page,click Finish.
12. Close Internet Information Services (IIS) Manager.
• In the Internet Information Services (IIS) Manager window, click the Close button.
f 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. a. On the Start menu, click Internet Explorer.
b. In the Blank Page - Windows Internet Explorer window, in the address bar, type
http://localhost/Deployment, and then press ENTER.
2. Click the Log In link.
• In the Home Page – Windows Internet Explorer window, click Log In.
3. Enter credentials for the user student with a password of Pa$$w0rd, and then log in.
• In the Log In – Windows Internet Explorer window, in the Username box, type student, in the
Password box, type Pa$$w0rd, and then click 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.
• In the Home Page – Windows Internet Explorer window, click the Close button.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 434/449
Lab Answer Key: ASP.NET Deployments 11
5. Close Visual Studio 2010.
• In the Deployment – Microsoft Visual Studio window, click the Close button.
f 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 .
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.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 435/449
Lab Answer Key: Developing a Web Application by Using Silverlight 1
Module 15
Lab Answer Key: Developing a Web Application by UsingSilverlight
Contents:Exercise 1: Creating a Silverlight Project 2
Exercise 2: Creating a Silverlight WCF Service 3
Exercise 3: Displaying Data by Using Silverlight Controls 5
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 436/449
2 Lab Answer Key: Developing a Web Application by Using Silverlight
Lab 15: Adding Silverlight to a Web ApplicationExercise 1: Creating a 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.
• On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio2010, and then click Microsoft Visual Studio 2010.
3. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 15\Starter\Exercise 01 or D:\LabFiles\VB\Lab 15\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\Lab15\Starter\Exercise 01\AdventureWorks.sln or D:\Lab Files\VB\Lab 15\Starter\Exercise01\AdventureWorks.sln, and then click Open.
Task 2: Add a new Silverlight project
1. Add a new Microsoft® Silverlight® application project named AdventureWorksSL to the solution. The
Silverlight project should be hosted in the AdventureWorks project.
a. In Solution Explorer, right-click Solution 'AdventureWorks' (1 project), point to Add, and then
click New Project.
b. In the Add New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click Silverlight Application, in the Name box, type AdventureWorksSL, and
then click OK .
c. In the New Silverlight Application dialog box, click OK.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 437/449
Lab Answer Key: Developing a Web Application by Using Silverlight 3
2. Build the solution.
• In the AdventureWorks – Microsoft Visual Studio window, press CTRL+SHIFT+B.
3.
Save the solution changes.• In the AdventureWorks – Microsoft Visual Studio window, press CTRL+SHIFT+S.
4. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 2: Creating a Silverlight WCF Service
Task 1: Open an existing solution
1. Open Microsoft® Visual Studio® 2010.
• On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 15\Starter\Exercise 02 or D:\LabFiles\VB\Lab 15\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\Lab15\Starter\Exercise 02\AdventureWorks.sln or D:\Lab Files\VB\Lab 15\Starter\Exercise02\AdventureWorks.sln, and then click Open.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 438/449
4 Lab Answer Key: Developing a Web Application by Using Silverlight
Task 2: Create a Silverlight WCF service
• Add a new Silverlight WCF service named ProductServiceSL to the AdventureWorks project.
a. In Solution Explorer, right-click AdventureWorks, point to Add, and then click New Item.
b. In the Add New Item – AdventureWorks dialog box, in the left pane, click Silverlight, in the
middle pane, Silverlight-enabled WCF Service, in the Name box, type ProductServiceSL.svc,
and then click Add.
Task 3: Create methods that return a list of product categories, and a list of products by
category
1. Delete the stub method DoWork from the code file.
• In the ProductServiceSL.svc.cs or ProductServiceSL.svc.vb window, select the following code, and
then press DELETE.
[Visual C#] [OperationContract] public void DoWork() {
// Add your operation implementation here
return; } // Add more operations here and mark them with [OperationContract]
[Visual Basic] <OperationContract()> Public Sub DoWork()
' Add your operation implementation here End Sub ' Add more operations here and mark them with <OperationContract()>
2. Import the System.Collections.Generic namespace.
• In the ProductServiceSL.svc.cs or ProductServiceSL.svc.vb window, at the top of the file, add the
following code.
[Visual C#] using System.Collections.Generic;
[Visual Basic] Imports System.Collections.Generic
3. Add the following method, which returns a list of product categories, to the ProductServiceSL class.
[Visual C#] [OperationContract] public IEnumerable<ProductCategory> GetProductCategories() {
return DataAccessLayer.Products.GetCategories(); }
[Visual Basic]
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 439/449
Lab Answer Key: Developing a Web Application by Using Silverlight 5
<OperationContract> Public Function GetProductCategories() As IEnumerable(Of ProductCategory)
Return AdventureWorks.DataAccessLayer.Products.GetCategories() End Function
4. Add the following method that returns a list of products by category, to the ProductServiceSL class.
[Visual C#] [OperationContract] public IEnumerable<Product> GetProductsByCategory(int ProductCategoryID) {
return DataAccessLayer.Products.GetProductsByCategory(ProductCategoryID); }
[Visual Basic] <OperationContract> Public Function GetProductsByCategory(ProductCategoryID As Integer) As IEnumerable(Of
Product) Return
AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(ProductCategoryID) End Function
5. Build the solution and fix any errors.
• In the AdventureWorks – Microsoft Visual Studio window, press CTRL+SHIFT+B.
6. Close Visual Studio 2010.
• In the AdventureWorks – Microsoft Visual Studio window, click the Close button.
Exercise 3: Displaying Data by Using Silverlight Controls
Task 1: Open an existing solution
1. Open Microsoft® Visual Studio® 2010.
• On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio2010, and then click Microsoft Visual Studio 2010.
2. Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 15\Starter\Exercise 03 or D:\LabFiles\VB\Lab 15\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\Lab15\Starter\Exercise 03\AdventureWorks.sln or D:\Lab Files\VB\Lab 15\Starter\Exercise03\AdventureWorks.sln, and then click Open.
Task 2: Add a WCF Service reference
1.
Build the solution.• In the AdventureWorks – Microsoft Visual Studio window, press CTRL+SHIFT+B.
2. In the AdventureWorksSL project, add a service reference to the ProductServiceSL.svc WCF service,
with a namespace of AdventureWorks.
a. In Solution Explorer, right-click AdventureWorksSL, and then click Add Service Reference.
b. In the Add Service Reference dialog box, click the Discover button.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 440/449
6 Lab Answer Key: Developing a Web Application by Using Silverlight
c. In the Services list, click ProductServiceSL.svc, in the Namespace box, type AdventureWorks, and then click OK .
Task 3: Create Silverlight controls to display the data
1. Open MainPage.xaml in the Designer.
• In Solution Explorer, under AdventureWorksSL, right-click MainPage.xaml, and then click ViewDesigner.
2. From the Toolbox, drag a Silverlight DataGrid control to the left side of the page.
• In the Toolbox, under Common Silverlight Controls, drag a DataGrid control to the left side of
the page.
3. Change the height and width of the UserControl and the Grid control to the following values.
• Height: 400
• Width: 600
a. In the Designer, select the Grid control, press and hold down CTRL, and then click the
UserControl.
b. In the Properties window, click the Alphabetical button, in the Height box, type 400, in the
Width box, type 600, and then press ENTER.
4. Make the following property changes to the DataGrid control.
• Name: CategoriesDataGrid
• Height: 156
• Width: 100
• AutoGenerateColumns: False
a. In the Designer, select the DataGrid control.
b. In the XAML view, in the opening DataGrid tag, set the value of the Name attribute to
CategoriesDataGrid.
c. In the Properties window, in the Height box, type 156, in the Width box, type 100, and
ensure the AutoGenerateColumns check box is cleared.
5. From the Toolbox, drag a Silverlight DataGrid control to the right of the CategoriesDataGrid control
on the page.
• In the Toolbox, under Common Silverlight Controls, drag a DataGrid control to the right of the
CategoriesDataGrid control on the page.
6. Make the following property changes to the DataGrid control.
• Name: ProductsDataGrid
• Height: 300
• Width: 370
• AutoGenerateColumns: False
a. In the Designer, select the new DataGrid control.
b. In the XAML view, in the opening DataGrid tag, set the value of the Name attribute to
ProductsDataGrid.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 441/449
Lab Answer Key: Developing a Web Application by Using Silverlight 7
c. In the Properties window, in the Height box, type 300, in the Width box, type 370, and
ensure the AutoGenerateColumns check box is cleared.
7. Drag two Silverlight Label controls onto the page. Position them directly above the two DataGrid
controls.
8. Make the following changes to the left-most Labels control.
• Name: CategoryLabel
• Height: 14
• Width: 100
• Content: Categories
a. In the Designer, select the left-most Label control.
b. In the XAML view, in the opening Label tag, set the value of the Name attribute to
CategoryLabel.
c. In the Properties window, in the Height box, type 14, in the Width box, type 100, in the
Content box, type Categories, and then press ENTER.
9. Make the following changes to the right-most Labels control.
• Name: ProductLabel
• Height: 14
• Width: 100
• Content: Products
a. In the Designer, select the right-most Label control.
b. In the XAML view, in the opening Label tag, set the value of the Name attribute to
ProductLabel.
c. In the Properties window, in the Height box, type 14, in the Width box, type 100, in the
Content box, type Products, and then press ENTER.
10. The final result will look something like this:
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 442/449
8 Lab Answer Key: Developing a Web Application by Using Silverlight
11. Examine the markup in XAML view.
<UserControl x:Class="AdventureWorksSL.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
Height="400" Width="600">
<Grid x:Name="LayoutRoot" Background="White" Width="600" Height="400">
<sdk:DataGrid AutoGenerateColumns="False" Height="156"
HorizontalAlignment="Left" Name="CategoriesDataGrid" VerticalAlignment="Top"Width="100" Margin="5,30,0,0" />
<sdk:DataGrid AutoGenerateColumns="False" Height="300"
HorizontalAlignment="Left" Margin="106,30,0,0" Name="ProductsDataGrid"VerticalAlignment="Top" Width="370" />
<sdk:Label Height="14" HorizontalAlignment="Left" Name="CategoryLabel"
VerticalAlignment="Top" Width="100" Margin="6,1,0,0" Content="Categories" /><sdk:Label Height="14" HorizontalAlignment="Left" Margin="106,1,0,0"
Name="ProductLabel" VerticalAlignment="Top" Width="100" Content="Products" />
</Grid>
</UserControl>
12.
Configure the CategoriesDataGrid control to display the necessary columns returned from theGetProductCategories service method, by adding a DataGrid.Columns element to the
CategoriesDataGrid control.
<sdk:DataGrid AutoGenerateColumns="False" Height="156" HorizontalAlignment="Left"Name="CategoriesDataGrid" VerticalAlignment="Top" Width="100" Margin="5,30,0,0">
<sdk:DataGrid.Columns><sdk:DataGridTextColumn Binding="{Binding ProductCategoryID}" Header="ID"
Visibility="Collapsed" />
<sdk:DataGridTextColumn Binding="{Binding Name}" Header="Name" /></sdk:DataGrid.Columns>
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 443/449
Lab Answer Key: Developing a Web Application by Using Silverlight 9
</sdk:DataGrid>
a. In the XAML view, change the self-closing DataGrid element with the Name attribute value of
CategoriesDataGrid, to an opening and closing element.
<sdk:DataGrid AutoGenerateColumns="False" Height="156" HorizontalAlignment="Left"
Name="CategoriesDataGrid" VerticalAlignment="Top" Width="100" Margin="5,30,0,0"> </sdk:DataGrid>
b. In the XAML view, between the opening and closing DataGrid element with the Name attribute
value of CategoriesDataGrid, add the following markup.
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding ProductCategoryID}" Header="ID"Visibility="Collapsed" />
<sdk:DataGridTextColumn Binding="{Binding Name}" Header="Name" />
</sdk:DataGrid.Columns>
13. Configure the ProductsDataGrid control to display the necessary columns returned from the
GetProductByCategory service method, by adding a DataGrid.Columns element to the
ProductsDataGrid control.
<sdk:DataGrid AutoGenerateColumns="False" Height="300" HorizontalAlignment="Left"
Margin="106,30,0,0" Name="ProductsDataGrid" VerticalAlignment="Top" Width="370" /><sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding Name}" Header="Name" />
<sdk:DataGridTextColumn Binding="{Binding ProductNumber}" Header="ProductNumber" />
<sdk:DataGridTextColumn Binding="{Binding Color}" Header="Color" />
<sdk:DataGridTextColumn Binding="{Binding Size}" Header="Size" /></sdk:DataGrid.Columns>
</sdk:DataGrid>
a. In the XAML view, change the self-closing DataGrid element with the Name attribute value of
CategoriesDataGrid, to an opening and closing element.
<sdk:DataGrid AutoGenerateColumns="False" Height="300" HorizontalAlignment="Left"
Margin="106,30,0,0" Name="ProductsDataGrid" VerticalAlignment="Top" Width="370"></sdk:DataGrid>
b. In the XAML view, between the opening and closing DataGrid element with the Name attribute
value of CategoriesDataGrid, add the following markup.
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding Name}" Header="Name" /> <sdk:DataGridTextColumn Binding="{Binding ProductNumber}" Header="Product
Number" />
<sdk:DataGridTextColumn Binding="{Binding Color}" Header="Color" /> <sdk:DataGridTextColumn Binding="{Binding Size}" Header="Size" />
</sdk:DataGrid.Columns>
Task 4: Call the services asynchronously
1. In the Designer, double-click the CategoriesDataGrid control.
Note: This creates an event handler named CategoriesDataGrid_SelectionChanged in the
MainPage.xaml.cs or MainPage.xaml.vb code-behind file.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 444/449
10 Lab Answer Key: Developing a Web Application by Using Silverlight
[Visual C#] private void CategoriesDataGrid_SelectionChanged(object sender,SelectionChangedEventArgs e) { }
[Visual Basic] Private Sub CategoriesDataGrid_SelectionChanged(ByVal sender As System.Object, ByVal
e As System.Windows.Controls.SelectionChangedEventArgs) HandlesCategoriesDataGrid.SelectionChanged
End Sub 2. In the MainPage class, create a protected variable for the ProductServiceSLClient object.
[Visual C#]
public partial class MainPage : UserControl {
protected AdventureWorks.ProductServiceSLClient productService = new
AdventureWorks.ProductServiceSLClient();
...
[Visual Basic]
Public Partial Class MainPage Inherits UserControl
Protected productService As New AdventureWorks.ProductServiceSLClient()
... • In the MainPage.xaml.cs or MainPage.xaml.vb window, add the following code at the top of
the MainPage class.
[Visual C#] protected AdventureWorks.ProductServiceSLClient productService = new
AdventureWorks.ProductServiceSLClient();
[Visual Basic] Protected productService As New AdventureWorks.ProductServiceSLClient()
3. In the MainPage class constructor, wire up event handlers for the two Web service methods.
[Visual C#]
public MainPage() { InitializeComponent();
productService.GetProductCategoriesCompleted += new
EventHandler<AdventureWorks.GetProductCategoriesCompletedEventArgs>(productService_GetProductCategoriesCompleted);
productService.GetProductsByCategoryCompleted += new
EventHandler<AdventureWorks.GetProductsByCategoryCompletedEventArgs>(productService_G
etProductsByCategoryCompleted);}
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 445/449
Lab Answer Key: Developing a Web Application by Using Silverlight 11
[Visual Basic]
Public Sub New() InitializeComponent()
AddHandler productService.GetProductCategoriesCompleted, AddressOf
productService_GetProductCategoriesCompleted
AddHandler productService.GetProductsByCategoryCompleted, AddressOfproductService_GetProductsByCategoryCompletedEnd Sub
• In the MainPage.xaml.cs or MainPage.xaml.vb window, append the following code to the
constructor in the MainPage class.
[Visual C#]
productService.GetProductCategoriesCompleted += new
EventHandler<AdventureWorks.GetProductCategoriesCompletedEventArgs>(productService_GetProductCategoriesCompleted); productService.GetProductsByCategoryCompleted += new
EventHandler<AdventureWorks.GetProductsByCategoryCompletedEventArgs>(productService_GetProductsByCategoryCompleted);
[Visual Basic]
AddHandler productService.GetProductCategoriesCompleted, AddressOfproductService_GetProductCategoriesCompleted
AddHandler productService.GetProductsByCategoryCompleted, AddressOfproductService_GetProductsByCategoryCompleted
4. Each event handler needs a method to execute once the asynchronous call completes.
[Visual C#]
void productService_GetProductsByCategoryCompleted(object sender,
AdventureWorks.GetProductsByCategoryCompletedEventArgs e) { } void productService_GetProductCategoriesCompleted(object sender,
AdventureWorks.GetProductCategoriesCompletedEventArgs e) { }
[Visual Basic]
Private Sub productService_GetProductCategoriesCompleted(ByVal sender As Object,
ByVal e As AdventureWorks.GetProductCategoriesCompletedEventArgs) End Sub Private Sub productService_GetProductsByCategoryCompleted(ByVal sender As Object,
ByVal e As AdventureWorks.GetProductsByCategoryCompletedEventArgs) End Sub
• In the MainPage.xaml.cs or MainPage.xaml.vb window, append the following code to the
MainPage class.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 446/449
12 Lab Answer Key: Developing a Web Application by Using Silverlight
[Visual C#]
void productService_GetProductsByCategoryCompleted(object sender,AdventureWorks.GetProductsByCategoryCompletedEventArgs e)
{
}
void productService_GetProductCategoriesCompleted(object sender,AdventureWorks.GetProductCategoriesCompletedEventArgs e)
{
}
[Visual Basic]
Private Sub productService_GetProductCategoriesCompleted(ByVal sender As Object,
ByVal e As AdventureWorks.GetProductCategoriesCompletedEventArgs)
End Sub
Private Sub productService_GetProductsByCategoryCompleted(ByVal sender As Object,
ByVal e As AdventureWorks.GetProductsByCategoryCompletedEventArgs)
End Sub
5. When the page loads, the CategoriesDataGrid control must be populated. In the class constructor,
add a call to the service method GetProductCategoriesAsync.
[Visual C#]
public MainPage() {
InitializeComponent(); productService.GetProductCategoriesCompleted += new
EventHandler<AdventureWorks.GetProductCategoriesCompletedEventArgs>(productService_Ge
tProductCategoriesCompleted); productService.GetProductsByCategoryCompleted += new
EventHandler<AdventureWorks.GetProductsByCategoryCompletedEventArgs>(productService_GetProductsByCategoryCompleted);
productService.GetProductCategoriesAsync();
}
[Visual Basic]
Public Sub New() InitializeComponent() AddHandler productService.GetProductCategoriesCompleted, AddressOf
productService_GetProductCategoriesCompleted AddHandler productService.GetProductsByCategoryCompleted, AddressOf
productService_GetProductsByCategoryCompleted productService.GetProductCategoriesAsync()
End Sub • In the MainPage.xaml.cs or MainPage.xaml.vb window, append the following code to the
constructor in the MainPage class.
[Visual C#]
productService.GetProductCategoriesAsync();
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 447/449
Lab Answer Key: Developing a Web Application by Using Silverlight 13
[Visual Basic]
productService.GetProductCategoriesAsync()
Task 5: Bind the data returned from the services to the grids
1. The initial call to GetProductCategoriesAsync returns to
productService_GetProductCategoriesCompleted. In theproductService_GetProductCategoriesCompleted method, bind the results using the ItemsSource
property returned by the service to the grid.
[Visual C#] void productService_GetProductCategoriesCompleted(object sender,
AdventureWorks.GetProductCategoriesCompletedEventArgs e)
{CategoriesDataGrid.ItemsSource = e.Result;
}
[Visual Basic]
Sub productService_GetProductCategoriesCompleted(sender As Object, e As
AdventureWorks.GetProductCategoriesCompletedEventArgs)CategoriesDataGrid.ItemsSource = e.Result
End Sub
• In the MainPage.xaml.cs or MainPage.xaml.vb window, add the following code to the
productService_GetProductCategoriesCompleted method in the MainPage class.
[Visual C#]
CategoriesDataGrid.ItemsSource = e.Result;
[Visual Basic]
CategoriesDataGrid.ItemsSource = e.Result
2. In the CategoriesDataGrid_SelectionChanged event handler, get the selected category, and retrieve
the products by category.
[Visual C#]
private void CategoriesDataGrid_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{ AdventureWorks.ProductCategory category = CategoriesDataGrid.SelectedItem as
AdventureWorks.ProductCategory;
productService.GetProductsByCategoryAsync(category.ProductCategoryID);}
[Visual Basic]Private Sub CategoriesDataGrid_SelectionChanged(sender As Object, e As
SelectionChangedEventArgs) Dim category As AdventureWorks.ProductCategory =
TryCast(CategoriesDataGrid.SelectedItem, AdventureWorks.ProductCategory)
productService.GetProductsByCategoryAsync(category.ProductCategoryID)
End Sub • In the MainPage.xaml.cs or MainPage.xaml.vb window, add the following code to the
CategoriesDataGrid_SelectionChanged method in the MainPage class.
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 448/449
14 Lab Answer Key: Developing a Web Application by Using Silverlight
[Visual C#]
AdventureWorks.ProductCategory category = CategoriesDataGrid.SelectedItem asAdventureWorks.ProductCategory;
productService.GetProductsByCategoryAsync(category.ProductCategoryID);
[Visual Basic]Dim category As AdventureWorks.ProductCategory =
TryCast(CategoriesDataGrid.SelectedItem, AdventureWorks.ProductCategory) productService.GetProductsByCategoryAsync(category.ProductCategoryID)
3. The call to GetProductsByCategoryAsync returns to the
productService_GetProductsByCategoryCompleted method, where the results returned by the
service should be bound to the ItemsSource property of the grid.
[Visual C#]
void productService_GetProductsByCategoryCompleted(object sender,AdventureWorks.GetProductsByCategoryCompletedEventArgs e)
{ ProductsDataGrid.ItemsSource = e.Result;
}
[Visual Basic]
Sub productService_GetProductsByCategoryCompleted(sender As Object, e As
AdventureWorks.GetProductsByCategoryCompletedEventArgs) ProductsDataGrid.ItemsSource = e.Result
End Sub • In the MainPage.xaml.cs or MainPage.xaml.vb window, add the following code to the
productService_GetProductsByCategoryCompleted method in the MainPage class.
[Visual C#]
ProductsDataGrid.ItemsSource = e.Result;
[Visual Basic]
ProductsDataGrid.ItemsSource = e.Result
4. The final code should like this.
[Visual C#]
public partial class MainPage : UserControl {
protected AdventureWorks.ProductServiceSLClient productService = new
AdventureWorks.ProductServiceSLClient(); public MainPage() {
InitializeComponent(); productService.GetProductCategoriesCompleted += new
EventHandler<AdventureWorks.GetProductCategoriesCompletedEventArgs>(productService_GetProductCategoriesCompleted);
productService.GetProductsByCategoryCompleted += new
EventHandler<AdventureWorks.GetProductsByCategoryCompletedEventArgs>(productService_GetProductsByCategoryCompleted);
productService.GetProductCategoriesAsync(); }
7/14/2019 10264AD-ENU-LabManual
http://slidepdf.com/reader/full/10264ad-enu-labmanual 449/449
Lab Answer Key: Developing a Web Application by Using Silverlight 15
private void CategoriesDataGrid_SelectionChanged(object sender,SelectionChangedEventArgs e)
{ AdventureWorks.ProductCategory category = CategoriesDataGrid.SelectedItem as
AdventureWorks.ProductCategory; productService.GetProductsByCategoryAsync(category.ProductCategoryID);
} void productService_GetProductsByCategoryCompleted(object sender,
AdventureWorks.GetProductsByCategoryCompletedEventArgs e) {
ProductsDataGrid.ItemsSource = e.Result; } void productService_GetProductCategoriesCompleted(object sender,
AdventureWorks.GetProductCategoriesCompletedEventArgs e) {
CategoriesDataGrid.ItemsSource = e.Result; }
}
[Visual Basic]
Partial Public Class MainPage Inherits UserControl Protected productService As New AdventureWorks.ProductServiceSLClient() Public Sub New()
InitializeComponent() AddHandler productService.GetProductCategoriesCompleted, AddressOf
productService_GetProductCategoriesCompleted AddHandler productService.GetProductsByCategoryCompleted, AddressOf
productService_GetProductsByCategoryCompleted productService.GetProductCategoriesAsync()
End Sub Private Sub CategoriesDataGrid_SelectionChanged(ByVal sender As System.Object,
ByVal e As System.Windows.Controls.SelectionChangedEventArgs)