Top Banner
OFFICIAL MICROSOFT LEARNING PRODUCT 10264A Lab Instructions and Lab Answer Key: Developing Web Applications with Microsoft ® Visual Studio ® 2010
450
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 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 with Microsoft Visual Studio 2010

  • Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

    Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

    The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein.

    2010 Microsoft Corporation. All rights reserved.

    Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

    All other trademarks are property of their respective owners.

    Product Number: 10264A

    Part Number: X17-47398

    Released: 11/2010

  • Lab Instructions: Overview of Web Application Architecture and Design 1

    Module 1 Lab Instructions: Overview of Web Application Architecture and Design

    Contents: Exercise 1: Exploring the Adventure Works Website 4

    Exercise 2: Comparing Web Forms and MVC 7

    Exercise 3: Working with the Request Life Cycle 8

  • 2 Lab Instructions: Overvieew of Web Applicatioon Architecture and DDesign

    LLab 1: Exxploringg the AAdventu

    O In

    InFuap

    Fi

    Objectives: Describe th

    Explain cod

    Describe th

    ntroduction

    n this lab, you wurthermore, yopplication dev

    nally, you will

    he Adventure W

    de differences

    he request life

    n

    will review theou will comparvelopment by u

    explore how t

    Works website

    between Web

    cycle for both

    e existing Advere how applicausing the MVC

    to create contr

    re Works Webbsite

    e.

    b Forms and MVC.

    Web Forms and MVC.

    enture Works wation developmC framework.

    website and bement by using

    ecome familiaWeb Forms d

    r with its desigiffers from

    gn.

    rols dynamicallly by adding aan advertisemeent on the pagge.

  • Lab Instrucctions: Overview of WWeb Application Architecture and Design 3

    L

    Ahaacenpr

    Lab Scen

    s a web develoave limited exccomplish the nd, you want trogramming m

    nario

    oper at Advenperience with goals set by m

    to examine themodel.

    ture Works, yoASP.NET 4.0. Y

    management fe MVC framew

    ou have workeYou need to fuor the new Ad

    work and unde

    ed extensively urther explore dventure Workerstand how it

    with ASP.NET the features o

    ks website. As acompares with

    2.0. However, of ASP.NET 4.0a first step towh the Web For

    you to

    ward this rms

  • 4 Lab Instructions: Overview of Web Application Architecture and Design

    Exercise 1: Exploring the Adventure Works Website The main tasks for this exercise are as follows:

    1. Open the AdventureWorks solution in Visual Studio 2010.

    2. Start the web application.

    3. Browse the products list.

    4. Add products to the shopping cart.

    5. Place an order.

    6. Explore the life cycle of a Web Forms page.

    7. Open the AdventureWorksMvc solution in Visual Studio 2010.

    8. Explore the life cycle of an MVC request.

    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 Mens 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.

  • 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.

  • 6 Lab Instructions: Overview of Web Application Architecture and Design

    Results: After completing this exercise, you should have reviewed the Adventure Works website by adding products to your shopping cart and checking out. You should also have reviewed the Page and MVC request life cycles by placing breakpoints in methods that execute during the life cycle.

  • Lab Instructions: Overview of Web Application Architecture and Design 7

    Exercise 2: Comparing Web Forms and MVC The main tasks for this exercise are as follows:

    1. View the AdventureWorks solution in Visual Studio 2010.

    2. Examine the markup and code found in the Default.aspx Web Forms page.

    3. View AdventureWorksMvc solution in Visual Studio 2010.

    1. Examine the markup and code used for rendering the default MVC page.

    2. Discuss as a group the differences in the way Web Forms and MVC responds and delivers content to a request.

    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.

  • 8 Lab Instructions: Overview of Web Application Architecture and Design

    Exercise 3: Working with the Request Life Cycle The main tasks for this exercise are as follows:

    1. Exploring the life cycle of a Web Forms page.

    2. Exploring the life cycle of a MVC request.

    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.

    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.

    5. View the code-behind file for the Default Web Form.

    6. In the Page_Load method, add the following code at the beginning of the method.

    [Visual C#]

    lblAdvertisement.Text = "My advertisement here";

    [Visual Basic]

    lblAdvertisement.Text = "My advertisement here"

    7. Run the web application and view the rendered Default.aspx page.

    Note: During the pages Load event, the text is added to the lblAdvertisement Label control.

    8. Close Windows Internet Explorer.

    9. Close Visual Studio 2010.

    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#]

    [Visual Basic]

    5. Open the file Controllers\HomeController.cs or Controllers\HomeController.vb.

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

    6. Locate the Index method in the file.

    7. Add the following code at the beginning of the Index method.

    [Visual C#]

  • Lab Instructions: Overview of Web Application Architecture and Design 9

    ViewData["Advertisement"] = "My advertisement here";

    [Visual Basic]

    ViewData("Advertisement") = "My advertisement here"

    8. Run the web application and view the rendered Index.aspx view.

    Note: During the controllers Index action method, the text is added to Index view by using the ViewData.

    9. Close Windows Internet Explorer.

    10. Close Visual Studio 2010.

    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.

  • Lab Instructions: Designing a Web Application 1

    Module 2 Lab Instructions: Designing a Web Application

    Contents: Exercise 1: Reviewing the Adventure Works Website Structure 4

    Exercise 2: Redesigning the Adventure Works Website 5

    Exercise 3: Adding MVC Capabilities to the Adventure Works Website 7

  • 2 Lab Instructions: Designiing a Web Applicatioon

    LLab 2: Redesignning the

    N

    O

    A

    InIndimMth

    Note: Tasks in t

    Objectives:

    fter completin

    Draw diagr

    Identify whbusiness re

    Add MVC c

    ntroductionn this lab, you wiagramming it

    management, aMVC. You will ahat you can ge

    this lab will be

    ng this lab, you

    rams showing t

    hich pages of tquirements.

    capabilities to

    n will first captuts overall archiand recommenalso do the groet started as so

    e Advennture WWorks WWebsite

    e the same reg

    u will be able t

    the overall arc

    he website wil

    the existing w

    re your undertecture and pa

    nd which pageoundwork neceoon as Manage

    ardless of the

    to:

    chitecture and

    l use Web For

    ebsite.

    standing of thage flow. You es of the websiessary for addement approva

    programming

    page flow of t

    rms, and which

    e current Advewill then reviete will use Weing MVC capaal comes throu

    g language youur solution is uusing.

    the Adventuree Works websitte.

    h pages will use MVC, based on

    enture Works ew the busineseb Forms, and abilities to the ugh.

    website by s requirementwhich pages wexisting websi

    ts set by will use te so

  • Lab Instructions: Designingg a Web Application 3

    L

    NMdethrecoen

    Lab Scen

    ow that you hMVC to develop

    etailing recomhe current webedesigned webosts and benefnumerate the

    nario

    have a better up some pages

    mmendations fobsite and recombsite. Keep in mfits of your decrationale unde

    understanding of the Adventor redesigningmmend an appmind that you cisions before erlying your re

    of Web Formsture Works weg the website. Ypropriate progare operatingmaking recom

    ecommendatio

    s and MVC, yoebsite. Your nexYour proposalgramming mod on a tight bu

    mmendations. ons to help ma

    ou can see the xt task is to cre needs to descdel for develodget, so you nThe proposal

    anagement ass

    benefits of useate a proposacribe the strucping the page

    need to considshould also sess them.

    ing al

    cture of es of the der the

  • 4 Lab Instructions: Designing a Web Application

    Exercise 1: Reviewing the Adventure Works Website Structure The main tasks for this exercise are as follows:

    Open the AdventureWorks solution in Visual Studio 2010. Examine the code and markup location and purpose. Draw a diagram showing the overall architecture. Draw a diagram showing the page flow. Discuss your findings with the class.

    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.

  • Lab Instructions: Designing a Web Application 5

    Exercise 2: Redesigning the Adventure Works Website The 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 the

    database

    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

  • 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 the Adventure 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.

  • Lab Instructions: Designing a Web Application 7

    Exercise 3: Adding MVC Capabilities to the Adventure Works Website The 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:

    ... ... ...

  • 8 Lab Instructions: Designing a Web Application

    3. Save the Web.config file.

    The final Web.config file should appear as follows

    [Visual C#]

  • Lab Instructions: Designing a Web Application 9

    [Visual Basic]

  • 10 Lab Instructions: Designing a Web Application

    Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />

  • Lab Instructions: Designing a Web Application 11

    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.Mvc Imports 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 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}", 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) {

  • 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#] {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}

    [Visual Basic]

  • 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.

  • 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

  • 2 Lab Instructions: Developping MVC Models

    LLab 3: Creating

    O

    A

    InInan

    Objectives:

    fter completin

    Work with

    Use Entity F

    Implement

    ntroductionn this lab, you wn Entity Frame

    g MVC MModels

    ng this lab, you

    the Adventure

    Framework da

    data validatio

    n will create rela

    ework data mo

    u will be able t

    eWorks databa

    ta model.

    on for the MVC

    ationships betwodel, add a dat

    to:

    ase.

    C models.

    ween databaseta repository, a

    e tables by usiand implemen

    ng the Databant data model v

    ase Designer, cvalidation.

    create

  • Laab Instructions: Developing MVC Models 3

    L

    Lab Scennario

  • 4 Lab Instructions: Developing MVC Models

    Exercise 1: Exploring the AdventureWorks Database The 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.

  • 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.

  • 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.

  • Lab Instructions: Developing MVC Models 7

    Exercise 2: Adding an ADO.NET Entity Data Model The 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.

  • 8 Lab Instructions: Developing MVC Models

    3. Select the Blog and Blogger tables from the database and name the model namespace AdventureWorksModel.

  • 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 GetAllBlogs() { return db.Blogs; }

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

  • 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 GetAllBlogs(int id) { return from blog in db.Blogs where 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 blog End 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 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 = 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 == id select blogger.Name).FirstOrDefault(); return bloggerName; }

    [Visual Basic] Public Function GetBloggerName(ByVal id As Integer) As String Dim 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); }

  • 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 the existing AdventureWorks database. You also added a repository class and implemented list, select, insert, update, and delete operations in the class.

  • 12 Lab Instructions: Developing MVC Models

    Exercise 3: Model Data Validation The 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; }

  • Lab Instructions: Developing MVC Models 13

    [Required] [DisplayName("Blog Entry")] public object BlogEntry { get; set; } }

    [Visual Basic] Public Class Blog_MetaData _ Public Property BlogID As Object _ _ Public Property DatePosted As Object _ Public Property Title As Object _ 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] 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.

  • 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

  • 2 Lab Instructions: Developping MVC Controllerrs

    LLab 4: DDeveloping MV

    NBa

    O

    A

    In

    Inde

    Note: You can asic as your p

    Objectives

    fter completin

    Create an M

    List the exis

    Create a ne

    Edit a blog

    Delete a blo

    ntroduction

    n this lab, you welete (CRUD) o

    perform the taprogramming

    ng this lab, you

    MVC controlle

    sting blog entr

    ew blog entry.

    entry.

    og entry.

    n

    will create an operations.

    VC Controllers

    asks in this lablanguage.

    u will be able t

    r.

    ries.

    MVC controlle

    b by using eithe

    to:

    er and add cod

    er Microsoft V

    de to it to perf

    Visual C# or MMicrosoft Visuaal

    form create, reead, update, annd

  • Lab Innstructions: Developing MVC Controllers 3

    L

    BadeAop

    Lab Scen

    ased on your reveloped by uDO.NET Entityperations.

    nario

    recommendatusing MVC. Youy Data Model.

    ions for redesiu have alreadyNext, you nee

    gning the Advy built your MVed to develop a

    ventureWorks VC model clasan MVC contro

    website, the bses by leveragoller to handle

    blog pages neeging an existinge the database

    ed to be g e

  • 4 Lab Instructions: Developing MVC Controllers

    Exercise 1: Creating an MVC Controller The main tasks for this exercise are as follows:

    Open the AdventureWorksMvc solution in Visual Studio 2010. Create a controller named BlogController.

    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 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 BlogController 1. Create a controller named BlogController in the Controllers folder. The controller should not

    include action methods for create, update, delete, and details scenarios.

    2. Add the HandleErrorAttribute attribute to the BlogController class.

    [Visual C#] [HandleError]

    [Visual Basic]

    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 Public Class BlogController Inherits System.Web.Mvc.Controller '

  • Lab Instructions: Developing MVC Controllers 5

    ' GET: /Blog Function Index() As ActionResult Return View() End Function End Class End Namespace

    4. Build the solution, and fix any errors.

    5. Close Visual Studio 2010.

    Results: After this exercise, you should have created a new controller named BlogController that is decorated with the HandleErrorAttribute attribute.

  • 6 Lab Instructions: Developing MVC Controllers

    Exercise 2: Adding code to list the existing blog entries The main tasks for this exercise are as follows:

    1. Open the AdventureWorksMvc solution in Visual Studio 2010.

    2. Add a blogRepository object.

    3. Add code to the Index action method.

    4. Create a Blogger action method.

    5. Create a Details action method.

    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();

  • 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 ActionResult End Function

    2. Add code to the Blogger action method to return only the blog entries for the indicated blogger to the view.

    [Visual C#] var blogs = blogRepository.GetAllBlogs(id); return View(blogs);

    [Visual Basic] Dim blogs = blogRepository.GetAllBlogs(id) Return View(blogs)

    3. Verify that the final Blogger action method matches the following code.

    [Visual C#] public ActionResult Blogger(int id) { var blogs = blogRepository.GetAllBlogs(id); return View(blogs); }

    [Visual Basic] Function Blogger(ByVal id As Integer) As ActionResult Dim blogs = blogRepository.GetAllBlogs(id) Return View(blogs) End Function

    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

  • 8 Lab Instructions: Developing MVC Controllers

    End Function

    2. Add code to the Details action method to return only the indicated blog entry, to the view. However, if the blog entry no longer exists, redirect the user to the Index view.

    [Visual C#] var blogEntry = blogRepository.GetBlog(id); if (blogEntry == null) return RedirectToAction("Index"); return View(blogEntry);

    [Visual Basic] Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry)

    3. Verify that the final Details action method matches the following code.

    [Visual C#] public ActionResult Details(int id) { var blogEntry = blogRepository.GetBlog(id); if (blogEntry == null) return RedirectToAction("Index"); return View(blogEntry); }

    [Visual Basic] Function Details(ByVal id As Integer) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry) End Function

    4. Build the solution, and fix any errors.

    5. Close Visual Studio 2010.

    Results: After this exercise, you should have created a BlogRepository and action methods that allow you to view all of the blog entries, to view just the blog entries for a particular blogger, and to view a particular blog entry.

  • Lab Instructions: Developing MVC Controllers 9

    Exercise 3: Adding code to create a new blog entry The main tasks for this exercise are as follows:

    1. Open the AdventureWorksMvc solution in Visual Studio 2010. 2. Create a Create action method. 3. Create a Create action method that accepts an HTTP Post.

    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 ActionResult Return 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]

  • 10 Lab Instructions: Developing MVC Controllers

    public ActionResult Create(Blog blog) { }

    [Visual Basic]

    Function Create(ByVal blg As Blog) As ActionResult End Function

    2. Add code to the Create action method to save the new Blog object and redirect the user to the Index view. However, if the call to the Save method fails, return the user to the Create view.

    [Visual C#]

    if (!ModelState.IsValid) return View(blog); try { blog.DatePosted = DateTime.Now; blogRepository.AddBlog(blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been added."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); };

    [Visual Basic]

    If ModelState.IsValid Then Try blg.DatePosted = DateTime.Now blogRepository.AddBlog(blg) blogRepository.Save() TempData("ConfirmationMessage") = blg.Title & " has been added" Return RedirectToAction("Index") Catch Return View(blg) End Try End If Return View(blg)

    3. Verify that the final Create action method that for the HTTP Post request matches the following code.

    [Visual C#]

    [HttpPost] public ActionResult Create(Blog blog) { if (!ModelState.IsValid) return View(blog); try { blog.DatePosted = DateTime.Now; blogRepository.AddBlog(blog); blogRepository.Save();

  • Lab Instructions: Developing MVC Controllers 11

    TempData["ConfirmationMessage"] = blog.Title + " has been added."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); }; }

    [Visual Basic]

    Function Create(ByVal blg As Blog) As ActionResult If ModelState.IsValid Then Try blg.DatePosted = DateTime.Now blogRepository.AddBlog(blg) blogRepository.Save() TempData("ConfirmationMessage") = blg.Title & " has been added" Return RedirectToAction("Index") Catch Return View(blg) End Try End If Return View(blg) End Function

    4. Build the solution, and fix any errors.

    5. Close Visual Studio 2010.

    Results: After this exercise, you should have created two action methods for creating new blog entries. One of the action methods accepts HTTP Get requests and the other action method accepts HTTP Post requests.

  • 12 Lab Instructions: Developing MVC Controllers

    Exercise 4: Adding code to edit a blog entry The main tasks for this exercise are as follows:

    1. Open the AdventureWorksMvc solution in Visual Studio 2010.

    2. Create an Edit action method.

    3. Create an Edit action method for an HTTP Post request.

    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 ActionResult End Function

    2. Add code to the Edit action method to return the indicated Blog entry, to the view. However, if the blog entry no longer exists, redirect the user to the Index view.

    [Visual C#]

    var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); return View(blog);

    [Visual Basic]

    Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry)

    3. Verify that the final Edit action method matches the following code.

    [Visual C#]

    public ActionResult Edit(int id) { var blog = blogRepository.GetBlog(id);

  • Lab Instructions: Developing MVC Controllers 13

    if (blog == null) return RedirectToAction("Index"); return View(blog); }

    [Visual Basic]

    Function Edit(ByVal id As Integer) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry) End Function

    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]

    Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult End Function

    2. Add code to the Edit action method to save the blog entry and redirect the user to the Index view. However, if the call to the Save method fails, return the user to the Edit view. Also, if the blog entry no longer exists, redirect the user to the Index view.

    [Visual C#]

    var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); try { UpdateModel(blog, collection.ToValueProvider()); blogRepository.UpdateBlog(blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been updated."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); };

    [Visual Basic]

    Dim blogEntry = blogRepository.GetBlog(id)

  • 14 Lab Instructions: Developing MVC Controllers

    If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Try UpdateModel(blogEntry, collection.ToValueProvider()) blogRepository.UpdateBlog(CType(blogEntry, Blog)) blogRepository.Save() TempData("ConfirmationMessage") = blogEntry.Title & " has been updated" Return RedirectToAction("Index") Catch Return View(blogEntry) End Try

    3. Verify that the final Edit action method for an HTTP Post request matches the following code.

    [Visual C#]

    [HttpPost] public ActionResult Edit(int id, FormCollection collection) { var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); try { UpdateModel(blog, collection.ToValueProvider()); blogRepository.UpdateBlog(blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been updated."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); }; }

    [Visual Basic]

    Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Try UpdateModel(blogEntry, collection.ToValueProvider()) blogRepository.UpdateBlog(CType(blogEntry, Blog)) blogRepository.Save() TempData("ConfirmationMessage") = blogEntry.Title & " has been updated" Return RedirectToAction("Index") Catch Return View(blogEntry) End Try End Function

  • Lab Instructions: Developing MVC Controllers 15

    4. Build the solution, and fix any errors.

    5. Close Visual Studio 2010.

    Results: After this exercise, you should have created two action methods for editing blog entries. One of the action methods accepts HTTP Get requests and the other action method accepts HTTP Post requests.

  • 16 Lab Instructions: Developing MVC Controllers

    Exercise 5: Adding code to delete a blog entry The main tasks for this exercise are as follows:

    1. Open the AdventureWorksMvc solution in Visual Studio 2010.

    2. Create a Delete action method.

    3. Create a Delete action method for an HTTP Post request

    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 ActionResult End Function

    2. Add code to the Delete action method to redirect to the Index view.

    [Visual C#]

    var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); return View(blog);

    [Visual Basic]

    Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry)

    3. Verify that the final Delete action method matches the following code.

    [Visual C#]

    public ActionResult Delete(int id) { var blog = blogRepository.GetBlog(id);

  • Lab Instructions: Developing MVC Controllers 17

    if (blog == null) return RedirectToAction("Index"); return View(blog); }

    [Visual Basic]

    Function Delete(ByVal id As Integer) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry) End Function

    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]

    Function Delete(ByVal id As Integer, ByVal confirmation As String) As ActionResult End Function

    2. Add code to the Delete action method to delete the blog entry and redirect the user to the Index view.

    [Visual C#]

    var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); blogRepository.DeleteBlog((Blog) blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been deleted."; return RedirectToAction("Index");

    [Visual Basic]

    Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If blogRepository.DeleteBlog(CType(blogEntry, Blog)) blogRepository.Save() TempData("ConfirmationMessage") = blogEntry.Title & " has been deleted." Return RedirectToAction("Index")

  • 18 Lab Instructions: Developing MVC Controllers

    3. Verify that the final Delete action method for an HTTP Post request matches the following code.

    [Visual C#]

    [HttpPost] public ActionResult Delete(int id, string confirmation) { var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); blogRepository.DeleteBlog((Blog) blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been deleted."; return RedirectToAction("Index"); }

    [Visual Basic]

    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. One of the action methods accepts HTTP Gets and the other action method accepts HTTP Posts.

  • Lab Instructions: Developing MVC Views 1

    Module 5 Lab Instructions: Developing MVC Views

    Contents: Exercise 1: Develop a List MVC View 4

    Exercise 2: Develop a Details MVC view 7

    Exercise 3: Develop a Create MVC view 9

    Exercise 4: Develop an Edit MVC view 15

    Exercise 5: Develop a Delete MVC view 19

  • 2 Lab Instructions: Developing MVC Views

    Lab 5: Developing MVC Views

    Note: You can perform the tasks in this lab by using either Microsoft Visual C# or Microsoft Visual Basic 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.

  • 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.

  • 4 Lab Instructions: Developing MVC Views

    Exercise 1: Develop a List MVC View The 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#]

    [Visual Basic]

    3. Verify that the ul element matches the following markup.

    [Visual C#]

    /ul>

    [Visual Basic]

    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 or System.Web.Mvc.ViewPage(Of IEnumerable (Of AdventureWorksMvc.Blog)).

  • 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#]

    -

    [Visual Basic]

    -

    5. Verify that the markup and code in the Index view matches the following.

    [Visual C#]

    Index Index -

    [Visual Basic]

    Index Index

  • 6 Lab Instructions: Developing MVC Views

    -

    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.

  • Lab Instructions: Developing MVC Views 7

    Exercise 2: Develop a Details MVC view The 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: DatePosted:

    3. Verify that the markup and code in the Details view matches the following.

    [Visual C#]

    Details Details Blogger: DatePosted:

    [Visual Basic]

  • 8 Lab Instructions: Developing MVC Views

    Details Details Blogger: DatePosted:

    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.

  • Lab Instructions: Developing MVC Views 9

    Exercise 3: Develop a Create MVC view The 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 [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#]

    - [Visual Basic]

    -

  • 10 Lab Instructions: Developing MVC Views

    Verify that the markup and code in the Blogger view matches the following. [Visual C#]

    Blogger Blogger - [Visual Basic]

    Blogger Blogger -

    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.

  • 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#]

    Fields model.Title) %> model.Title) %> model.Title) %> model.BlogEntry) %> model.BlogEntry, new { cols = "85" })%> model.BlogEntry) %> [Visual Basic]

    Fields

    3. Verify that the markup and code in the Create view matches the following.

    [Visual C#]

  • 12 Lab Instructions: Developing MVC Views

    Create Create Fields model.Title) %> model.Title) %> model.Title) %> model.BlogEntry) %> model.BlogEntry, new { cols = "85" })%> model.BlogEntry) %> [Visual Basic]

    Create Create Fields

  • Lab Instructions: Developing MVC Views 13

    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#]

    [Visual Basic]

    3. Verify that the markup and code in the Index view matches the following.

    [Visual C#]

    Index Index -

  • 14 Lab Instructions: Developing MVC Views

    Index Index -

    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.

  • Lab Instructions: Developing MVC Views 15

    Exercise 4: Develop an Edit MVC view The 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#]

    Fields model.Title) %> model.Title) %> model.Title) %> model.BlogEntry) %> model.BlogEntry, new { cols = "85" })%> model.BlogEntry) %>

    [Visual Basic]

    Fields

  • 16 Lab Instructions: Developing MVC Views

    3. Verify that the markup and code in the partial Blog view matches the following.

    [Visual C#]

    Fields model.Title) %> model.Title) %> model.Title) %> model.BlogEntry) %> model.BlogEntry, new { cols = "85" })%> model.BlogEntry) %> [Visual Basic]

    Fields

  • Lab Instructions: Developing MVC Views 17

    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#]

    [Visual Basic]

    3. Verify that the markup and code in the Edit view matches the following.

    [Visual C#]

    Edit Edit

    [Visual Basic]

    Edit Edit

    Task 4: Edit a blog entry 1. Run the application.

    2. Navigate directly to the Blogger view by using the following route.

  • 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#]

    [Visual Basic]

    2. Verify that the markup and code in the Create view matches the following.

    [Visual C#]

    Create Create

    [Visual Basic]

    Create Create

    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.

  • Lab Instructions: Developing MVC Views 19

    Exercise 5: Develop a Delete MVC view The 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 box 1. 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.

    4. Verify that the markup and code in the Delete view matches the following.

    [Visual C#]

    Delete Delete Are you sure you want to delete this? Fields BlogID BloggerID DatePosted Title

  • 20 Lab Instructions: Developing MVC Views

    BlogEntry |

    [Visual Basic]

    Delete Delete Are you sure you want to delete this? Fields BlogID BloggerID DatePosted Title BlogEntry |

    Task 3: Delete a blog entry 1. Run the application.

  • 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.

  • Lab Instructions: Designing for Discoverability 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

  • 2 Lab Instructions: Designiing for Discoverabilitty

    LLab 6: DDesigninng for D

    OA

    In

    Incaanto

    Objectives fter completin

    Map URLs o

    Create a sit

    Build an ap

    ntroduction

    n this lab, you ategory, and dn inclusion to to the applicatio

    ng this lab, you

    of Web Forms

    temap file.

    pplication infra

    n

    map URLs of Wdetails for a spethe newly creaon.

    Discoverrability

    u will be able t

    pages.

    astructure.

    Web Forms paecific product ated sitemap f

    to:

    ges to use ASPID. You also c

    file for the Def

    P.NET URL mareate a sitemafault Web Site

    pping for listinp, as well as a e in IIS, and ad

    ng products byrobots.txt file

    dd navigation

    y e with controls

  • Lab Innstructions: Designingg for Discoverability 3

    L

    YoSeto

    Usit

    Lab Scen

    ou are developearch engines o send in emai

    sing the routintemap page, a

    nario

    ping an appliccan find your ls.

    ation that will site easily. As

    be used for exwell, you want

    xternal customt to use URLs t

    mers, and you wthat are easy f

    want to ensurefor your salesp

    e that people

    ng features of and complete

    ASP.NET 4.0, ybuilding the a

    you will map tpplication infr

    the URLs of a Wrastructure.

    Web Forms page. You will crreate a

  • 4 Lab Instructions: Designing for Discoverability

    Exercise 1: Mapping URLs of Web Forms Pages The 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.

    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 06\Starter\Exercise 01

    Visual Basic D:\Lab Files\VB\Lab 06\Starter\Exercise 01

    f 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.

    f 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 it routes.MapPageRoute("products-browse", "products/{category}", "~/Products.aspx") End Sub

  • Lab Instructions: Designing for Discoverability 5

    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

    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 Then Dim 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

  • 6 Lab Instructions: Designing for Discoverability

    f Task 4: Test the pages 1. Run the application.

    2. Navigate directly to the Products page by using the following route.

    products/1

    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.

    f Task 5: Add a second route to map a URL to a product ID 1. 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 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

    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} URL

  • Lab Instructions: Designing for Discoverability 7

    productId = Page.RouteData.Values["id"].ToString(); var data = DataAccessLayer.Products.GetProduct(int.Parse(productId)); lblName.Text = data.Name; lblId.Text = data.ProductID.ToString(); lblColor.Text = data.Color; lblSize.Text = data.Size; lblWeight.Text = data.Weight.ToString(); lblListPrice.Text = data.ListPrice.ToString(); hdnProductId.Value = data.ProductID.ToString(); hdnProductName.Value = data.Name; hdnListPrice.Value = data.ListPrice.ToString(); } }

    [Visual Basic]

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim productID As String = Nothing ' Retrieve id param from /Products/{Id} URL productID = Page.RouteData.Values("id").ToString() Dim data = AdventureWorks.DataAccessLayer.Products.GetProduct(Integer.Parse(productID)) lblName.Text = data.Name lblId.Text = data.ProductID.ToString() lblColor.Text = data.Color lblSize.Text = data.Size lblWeight.Text = data.Weight.ToString() lblListPrice.Text = data.ListPrice.ToString() hdnProductId.Value = data.ProductID.ToString() hdnProductName.Value = data.Name hdnListPrice.Value = data.ListPrice.ToString() End If End Sub

    f 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 the System.Web.Routing assembly, and modified the Global.asax file to use ASP.NET URL mapping to list products by category and details for a specific product ID.

  • 8 Lab Instructions: Designing for Discoverability

    Exercise 2: Creating a Sitemap File The 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.

    f Task 1: Create a sitemap file to list products 1. 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.

    f Task 2: Modify the robots.txt file to include the sitemap 1. Select the Default 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 file with an inclusion to the newly created sitemap file for the default website in IIS.

  • Lab Instructions: Designing for Discoverability 9

    Exercise 3: Building the Application Infrastructure The 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.

    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 06\Starter\Exercise 03

    Visual Basic D:\Lab Files\VB\Lab 06\Starter\Exercise 03

    f 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.

    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.

    6. Replace the content of the div element with a class attribute value of clear hideSkiplink, with the following markup.

    7. Save and close the Site.Ma