10264A Developing Web Applications With Microsoft Visual Studio 2010
10264A Developing Web Applications With Microsoft Visual Studio 2010
M I C R O S O F T
L E A R N I N G
P R O D U C T
10264A
Developing Web Applications with
Microsoft Visual Studio 2010
Companion Content
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
2010 Microsoft Corporation. All rights reserved.
Microsoft and the trademarks listed at
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks
of the Microsoft group of companies. All other marks are property of their respective owners.
Module 1
Overview of Web Application Architecture and Design
Contents:
Lesson 1: Overview of IIS 7.0
10
14
1-1
1-2
Lesson 1
1-3
1-4
Authentication
Permissions
Connection strings
Application settings
On the Start menu, point to Administrative Tools, right-click Internet Information Services
(IIS) Manager, and then click Run as administrator.
In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and
then click Yes.
2.
In Internet Information Services (IIS) Manager, expand 10264A-GEN-DEV (10264A-GENDEV\Admin), and then expand Sites.
3.
4.
In the Add Web Site dialog box, specify the settings as shown in the following sample. You will
need to create the demo subfolder in the C:\inetpub\ folder.
5.
Click OK.
Change authentication
1.
2.
3.
In the Authentication pane, right-click Basic Authentication, and then click Enable.
Edit permissions
1.
2.
3.
4.
Click Edit.
5.
6.
In the Select Users or Groups dialog box, in the Enter the object names to select box, type
IIS_IUSRS, click Check Names, and then click OK.
7.
8.
In the Connections pane, click Default Web Site, and then click Demo.
2.
In the Demo Home pane, in the ASP.NET section, double-click Connection Strings.
3.
1-5
1-6
4.
In the Add Connection String dialog box, specify the settings as shown in the following
illustration.
5.
Click OK.
6.
7.
8.
9.
In the Connections pane, click Default Web Site, and then click Demo.
2.
3.
In the Demo Home pane, in the ASP.NET section, double-click Application Settings.
4.
5.
In the Add Application Setting dialog box, specify the settings per the following.
6.
Click OK.
7.
8.
9.
In the Connections pane, click Default Web Site, and then click Demo.
2.
2.
In the Application Pools pane, click DefaultAppPool, and then in the Actions pane, in the
Application Pool Tasks section, click Recycle.
3.
1-7
1-8
Lesson 2
1-9
1-10
Lesson 3
11
12
1-11
1-12
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.
b.
In the New Project dialog box, in the left pane, in the Installed Templates section,
expand Visual C# or Visual Basic, and then click Web.
c.
In the New Project dialog box, in the middle pane, click ASP.NET MVC 2 Web
Application.
d.
In the New Project dialog box, in the middle pane, in the Name box, type
DemoMvcApplication, in the Location box, type D:\Demofiles\Module 01\Demo 02,
and then click OK.
3.
In the Create Unit Test dialog box, select the No, do not create a unit test project option, and
then click OK.
4.
Note: Observe that the code files all have the suffix Controller.
5.
6.
b.
c.
Note: The model code file contains the data structures for this web application and classes that
control logic for working with the data store.
d.
7.
Note: Several folders share their name with the names of the controllers in the Controllers
folder.
8.
1-13
Note: The Shared folder contains master pages, user controls, and pages shared across the
MVC web application.
9.
In the DemoMvcApplication - Microsoft Visual Studio 2010 window, click the Close
button.
1-14
Lesson 4
15
1-15
Module 2
Designing a Web Application
Contents:
Lesson 1: Web Applications: Case Studies
2-1
2-2
Lesson 1
2-3
2-4
Lesson 2
2-5
Guidelines for Determining When to Use Web Forms and When to Use
MVC
Question: What solutions in your experience may have benefited from implementation using MVC?
Answer: Will Vary.
Question: What key features of Web Forms that you use frequently might you miss when developing
with MVC?
Answer: Will Vary.
2-6
Lesson 3
Enterprise Library
Question: What benefits can you see to using the Enterprise Library as a consistent interface for
common tasks that your applications require?
Answer: Will vary.
2-7
Module 3
Developing MVC Models
Contents:
Lesson 1: Exploring Ways to Create MVC Models
3-1
3-2
Lesson 1
3-3
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.
Create a new ASP.NET MVC 2 Web Application project, with an associated Unit Test project.
a.
b.
c.
In the Start Page Microsoft Visual Studio window, on the File menu, click New Project, or
press CTRL+SHIFT+N.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the middle
pane, click ASP.NET MVC 2 Web Application, in the Location box, type D:\Demofiles\CS or
D:\Demofiles\VB, and then click OK.
In the Create Unit Test Project dialog box, ensure the Yes, create a unit test project check box
is selected, and then click OK.
In Solution Explorer, right-click Models, point to Add and then click New Item, or press
CTRL+SHIFT+A.
In the Add New Item MvcApplication1 dialog box, in the left pane, click Visual C# or Visual
Basic, in the middle pane, click Class, in the Name box, type Blog, and then click Add.
[Visual C#]
public class Blog
{
public string Title { get; set; }
public string Description { get; set; }
}
[Visual Basic]
Public Class Blog
Private Property Title As String
Private Property Description As String
End Class
In the MvcApplication1 Microsoft Visual Studio window, on the Build menu, click Build
Solution, or press CTRL+SHIFT+B.
In the MvcApplication1 Microsoft Visual Studio window, click the Close button.
Best Practices: Model should not be concerned about saving itself to the persistent medium,
and the data access responsibility should be kept separate from the model.
3-4
Lesson 2
3-5
3-6
Lesson 3
3-7
3-8
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Programming Language
Location
Visual C#
D:\Demofiles\CS\MvcApplication1
Visual Basic
D:\Demofiles\VB\MvcApplication1
3.
4.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project, or press CTRL+SHIFT+O.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\MvcApplication1\MvcApplication1.sln or
D:\Demofiles\VB\MvcApplication1\MvcApplication1.sln and then click Open.
Add a new ADO.NET Entity Data Model named MyModel.edmx to the project, and generate the
model from database. The model must be added to the Models folder.
a.
In Solution Explorer, right-click Models, point to Add, and then click New Item.
b.
In the Add New Item MvcApplication1 dialog box, in the left pane, click Data.
c.
In the middle pane, click ADO.NET Entity Data Model, in the Name box, type
MyModel.edmx, and then click Add.
d.
In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate
from database, and then click Next.
In the Entity Data Model Wizard, on the Choose Your Data Connection page, if the Which data
connection should your application use to connect to the database? list, is empty, click New
Connection, and create a new connection to the AdventureWorksLT2008R2 database on the
.\SQLExpress SQL Server instance.
a.
In the Choose Data Source dialog box, in the Data source list, click Microsoft SQL
Server, and then click OK.
b.
In the Connection Properties dialog box, in the Server name box, type .\SQLExpress,
in the Select or enter a database name list, click AdventureWorksLT2008R2, and
then click Continue.
5.
In the Entity Data Model Wizard, on the Choose Your Data Connection page, if the Which data
connection should your application use to connect to the database? list, click 10264a-gendev\sqlexpress.AdventureWorksLT2008R2.Sales(LT), and then click Next.
6.
3-9
7.
On the Choose Your Database Objects page, in the Which database objects do you want to
include in your model list, expand Tables, select the Blog and Blogger check boxes, and then
click Finish.
8.
Add a new data repository class named BlogRepository to the Models folder.
9.
a.
In Solution Explorer, right-click Models, point to Add, and then click New Item.
b.
In the Add New Item MvcApplication1 dialog box, in the left pane, click Visual C# or
Visual Basic.
c.
In the middle pane, click Class, in the Name box, type BlogRepository, and then click
Add.
[Visual C#]
private AdventureWorksLT2008R2Entities db = new AdventureWorksLT2008R2Entities();
public IQueryable<MvcApplication1.Models.Blog> GetAllBlogs()
{
return db.Blogs;
}
[Visual Basic]
Private db As New AdventureWorksLT2008R2Entities()
Public Function GetAllBlogs() As IQueryable(Of MvcApplication1.Blog)
Return db.Blogs
End Function
[Visual C#]
private AdventureWorksLT2008R2Entities db = new AdventureWorksLT2008R2Entities();
public IQueryable<MvcApplication1.Models.Blog> GetAllBlogs()
{
3-10
return db.Blogs;
}
[Visual Basic]
Private AdventureWorksLT2008R2Entities db As New AdventureWorksLT2008R2Entities()
Public Function GetAllBlogs() As IQueryable(Of MvcApplication1.Blog)
Return db.Blogs
End Function
10. Append the Save method to the BlogRepository class, which is responsible for persisting the
Blog object into the database.
[Visual C#]
public static void Save(MvcApplication1.Models.Blog blog)
{
using (var db = new AdventureWorksLT2008R2Entities ())
{
if (blog.BloggerID == 0)
{
db.AddToBlogs(blog);
db.SaveChanges();
}
}
}
[Visual Basic]
Public Shared Sub Save(ByVal blog As MvcApplication1.Blog)
Using db As New AdventureWorksLT2008R2Entities()
If blog.BloggerID = 0 Then
db.AddToBlogs(blog)
db.SaveChanges()
End If
End Using
End Sub
[Visual Basic]
Public Shared Sub Save(ByVal blog As MvcApplication1.Blog)
Using db As New AdventureWorksLT2008R2Entities()
If blog.BloggerID = 0 Then
db.AddToBlogs(blog)
3-11
db.SaveChanges()
End If
End Using
End Sub
In Solution Explorer, in the Models folder, right-click Blog.cs or Blog.vb, and then click
Delete.
b.
Module 4
Developing MVC Controllers
Contents:
Lesson 1: Implementing MVC Controllers
4-1
4-2
Lesson 1
Additional Reading
4-3
"Anti-image-leeching," to prevent images from being loaded in pages that are not on your site.
Web crawler filtering, to change application behavior based on the browser user agent.
Authorization
Action
Result
Exception
4-4
2.
3.
4.
Create a new ASP.NET MVC 2 Web Application project, with an associated Unit Test project.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET MVC 2 Web Application, in the Location box, type
D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.
c.
In the Create Unit Test Project dialog box, ensure that Yes, create a unit test project
is selected, and then click OK.
Create a controller named BlogController in the Controllers folder. The controller should
include action methods for create, update, delete, and details scenarios.
a.
In Solution Explorer, right-click Controllers, point to Add and then click Controller.
b.
In the Add Controller dialog box, in the Controller Name box, type BlogController,
select the Add action methods for Create, Update, Delete, and Details scenarios
check box, and then click Add.
5.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the MvcApplication1 Microsoft Visual Studio window, on the Build menu, click
Build Solution, or press CTRL+SHIFT+B.
In the MvcApplication1 Microsoft Visual Studio window, click the Close button.
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Programming Language
Location
Visual C#
D:\Demofiles\CS\MvcApplication1
Visual Basic
D:\Demofiles\VB\MvcApplication1
3.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project,
or press CTRL+SHIFT+O.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\MvcApplication1\MvcApplication1.sln or
D:\Demofiles\VB\MvcApplication1\MvcApplication1.sln and then click Open.
4.
[Visual C#]
[HandleError(ExceptionType=typeof(Exception))]
public ActionResult About()
{
throw new Exception();
}
[Visual Basic]
<HandleError(ExceptionType:=GetType(Exception))>
Public Function About() As ActionResult
Throw New Exception()
End Function
5.
6.
<system.web>
<customErrors mode="On" />
</system.web>
7.
8.
In the MvcApplication1 Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.
Note: The error message, which is part of the Error.aspx page or view, located in the
Views\Shared folder, is displayed.
9.
4-5
In the MvcApplication1 Microsoft Visual Studio window, click the Close button.
4-6
Additional Reading
What Is an MVC Controller?
For more information about MVC controllers, see Controller Class.
For more information about routing, see Understanding the MVC Application Execution
Process.
Lesson 2
10
Additional Reading
13
4-7
4-8
Must be public.
Cannot be static.
Cannot be overloaded based on parameters unless they are disambiguated with attributes
such as NonActionAttribute or AcceptVerbsAttribute.
Question: How do you prevent a public method of a controller from being treated like an action
method?
Answer: By default, ASP.NET MVC treats all public methods of a controller class as action methods. If
your controller class contains a public method and you do not want it to be an action method, you
must decorate that method with the NonActionAttribute attribute.
Question: What is the shortest attribute you can use to designate that an action method should
respond only to an HTTP Post?
Answer: The shortest attribute you can use to designate that an action method should only respond
to an HTTP Post is the HttpPostAttribute attribute.
ContentResult
EmptyResult
FileResult
JavaScriptResult
JsonResult
PartialViewResult
RedirectResult
RedirectToRouteResult
ViewResult
Question: What are the three ways that the ViewResult class can pass data to the view?
Answer: The three ways covered in this lesson are:
ViewData
TempData
View property
4-9
4-10
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Programming Language
Location
Visual C#
D:\Demofiles\CS
Visual Basic
D:\Demofiles\VB
3.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project,
or press CTRL+SHIFT+O.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DemoHello.sln or D:\Demofiles\VB\DemoHello.sln and then click Open.
b.
c.
Append the following text to the URL in the address bar, and then press ENTER.
/RouteDataDemo/World
Note: The value of the id key, retrieved from the RouteData.Values key/value pair collection,
(World) is displayed.
d.
4.
b.
c.
Append the following text to the URL in the address bar, and then press ENTER.
/QueryStringDemo?id=World
Note: The value of the id key, retrieved from the Request object key/value pair collection,
(World) is displayed.
d.
5.
Replace the content of the Content2 Content control in the Index.aspx page file in the
Views\Hello folder with the following markup.
[Visual C#]
<% Html.BeginForm(); %>
Enter Your Name: <%: Html.TextBox("id") %>
<input id="Submit1" type="submit" value="Submit" />
<h2><%: ViewData["Message"] %></h2>
<% Html.EndForm(); %>
[Visual Basic]
<% Html.BeginForm() %>
Enter Your Name: <%: Html.TextBox("id") %>
<input id="Submit1" type="submit" value="Submit" />
<h2><%: ViewData("Message") %></h2>
<% Html.EndForm() %>
b.
c.
d.
e.
Append the following text to the URL in the address bar, and then press ENTER.
/TextBoxDemo
f.
In the Enter Your Name box, type your name, and then click Submit.
4-11
[Visual C#]
public ActionResult FormCollectionDemo(FormCollection collection)
{
ViewData["Message"] = "Hello " + collection["id"];
return View("Index");
}
[Visual Basic]
Function FormCollectionDemo(ByVal collection As FormCollection) As ActionResult
ViewData("Message") = "Hello " & collection("id")
Return View("Index")
End Function
b.
c.
4-12
d.
Append the following text to the URL in the address bar, and then press ENTER.
/FormCollectionDemo
e.
In the Enter Your Name box, type your name, and then click Submit.
f.
Note: The value entered in the text box, retrieved from the FormCollection object, is displayed.
g.
h.
Additional Reading
Calling an MVC View
For more information about the ActionResult class, see ActionResult Class.
For more information about the ViewResult class, see ViewResult Class.
4-13
Module 5
Developing MVC Views
Contents:
Lesson 1: Implementing MVC Views
13
5-1
5-2
Lesson 1
Additional Reading
5-3
MvcForm Extensions
Input Extensions
Label Extensions
Link Extensions
Select Extensions
TextArea Extensions
Validation Extensions
5-4
2.
3.
4.
5.
Create a new ASP.NET MVC 2 Web Application project, without an associated Unit Test project.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET MVC 2 Web Application, in the Location box, type
D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.
c.
In the Create Unit Test Project dialog box, ensure No, do not create a unit test
project is selected, and then click OK.
In Solution Explorer, expand Views, expand Home, right-click About.aspx, and then
click Delete.
b.
In Solution Explorer, right-click Home, point to Add and then click View.
b.
In the Add View dialog box, in the View name box, type About, clear the Create a
strongly-typed view check box, and then click Add.
6.
7.
In the MvcApplication1 Microsoft Visual Studio window, on the Build menu, click
Build Solution, or press CTRL+SHIFT+B.
b.
In the MvcApplication1 Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.
c.
8.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the About Windows Internet Explorer window, click the Close button.
In the MvcApplication1 Microsoft Visual Studio window, click the Close button.
Additional Reading
What Is an MVC View?
For more information about the ViewPage class, see ViewPage Class.
For more information about the ViewDataDictionary class, see ViewDataDictionary Class.
For more information about the TempDataDictionary class, see TempDataDictionary Class.
For more information about rendering a view using HTML helpers, see Rendering a Form in
ASP.NET MVC Using HTML Helpers.
5-5
5-6
Lesson 2
Additional Reading
12
5-7
5-8
2.
3.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Create a new ASP.NET MVC 2 Web Application project, without an associated Unit Test project.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET MVC 2 Web Application, in the Name box, type
StronglyTypedView, in the Location box, type D:\Demofiles\CS or D:\Demofiles\VB,
and then click OK.
c.
In the Create Unit Test Project dialog box, ensure No, do not create a unit test
project is selected, and then click OK.
[Visual C#]
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Gender { get; set; }
}
[Visual Basic]
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Public Class Person
<Required()>
<DisplayName("First Name")>
Public Property FirstName As String
<Required()>
<DisplayName("Last Name")>
Public Property LastName As String
<Required()>
Public Property Age As Integer
<Required()>
Public Property Gender As String
End Class
a.
In Solution Explorer, right-click Models, point to Add, and then click Class.
b.
In the Add New Item dialog box, in the Name box, type Person.cs or Person.vb, and
then click Add.
c.
In the Person.cs or Person.vb window, replace the content with the following code.
5-9
[Visual C#]
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Gender { get; set; }
}
[Visual Basic]
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Public Class Person
<Required()>
<DisplayName("First Name")>
Public Property FirstName As String
<Required()>
<DisplayName("Last Name")>
Public Property LastName As String
<Required()>
Public Property Age As Integer
<Required()>
Public Property Gender As String
End Class
4.
5.
6.
Create a strongly-typed view named Person in the Views\Home folder. The view should include
default content for the Create operation.
a.
In Solution Explorer, expand Views, right-click Home, point to Add and then click View.
b.
[Visual C#] In the Add View dialog box, in the View name box, type Person, select the
Create a strongly-typed view check box, in the View data class list, click Person, in
the View content list, click Create, and then click Add.
c.
[Visual Basic] In the Add View dialog box, in the View name box, type Person, select
the Create a strongly-typed view check box, in the View data class list, click
StronglyTypedView.Person, in the View content list, click Create, and then click Add.
Change the TextBox for displaying the Gender property for the model to a DropDownList.
5-10
a.
[Visual C#]
<%: Html.TextBoxFor(model => model.Gender) %>
[Visual Basic]
<%: Html.TextBoxFor(Function(model) model.Gender) %>
b.
[Visual C#]
<%: Html.DropDownListFor(model => model.Gender,
(SelectList)ViewData["Gender"]) %>
[Visual Basic]
<%: Html.DropDownListFor(Function(model) model.Gender,
CType(ViewData("Gender"), SelectList)) %>
7.
Add an action method named Person to the HomeController controller in the Controllers
folder.
[Visual C#]
public ActionResult Person()
{
ViewData["Gender"] = new SelectList(new[] { "", "Female",
return View();
}
"Male" });
[Visual Basic]
Public Function Person() As ActionResult
ViewData("Gender") = New SelectList({"", "Female", "Male"})
Return View()
End Function
a.
b.
[Visual C#]
public ActionResult Person()
{
ViewData["Gender"] = new SelectList(new[] { "", "Female",
return View();
}
[Visual Basic]
Public Function Person() As ActionResult
ViewData("Gender") = New SelectList({"", "Female", "Male"})
Return View()
"Male" });
5-11
End Function
8.
9.
b.
In the Home Page Windows Internet Explorer window, in the address bar, append
the following URL, and then press ENTER.
Home/Person
In the Person Windows Internet Explorer window, click the Close button.
In the StronglyTypedView Microsoft Visual Studio window, click the Close button.
5-12
Additional Reading
What Is a Strongly-typed View?
For more information about the HtmlHelper(TModel) class, see HtmlHelper(TModel) Class.
Lesson 3
14
15
5-13
5-14
5-15
2.
3.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project, or press CTRL+SHIFT+O.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\StronglyTypedView\StronglyTypedView.sln or
D:\Demofiles\VB\StronglyTypedView\StronglyTypedView.sln and then click Open.
Add a strongly-typed partial view named Partial to the Views\Home folder, by using the Add
View dialog box. The view must contain default content for a Create view, and the view should
be based on the Person class.
a.
In Solution Explorer, expand Views, right-click Home, point to Add, and then click
View.
b.
[Visual C#] In the Add View dialog box, in the View name box, type Partial, select the
Create a partial view (.ascx) and Create a strongly-typed view check boxes, in the
View data class list, click Person, in the View content list, click Create, and then click
Add.
or-
c.
4.
5.
[Visual Basic] In the Add View dialog box, in the View name box, type Partial, select
the Create a partial view (.ascx) and Create a strongly-typed view check boxes, in
the View data class list, click StronglyTypedView.Person, in the View content list,
click Create, and then click Add.
Add an empty view named Create to the Views\Home folder, by using the Add View dialog
box.
a.
In Solution Explorer, expand Views, right-click Home, point to Add, and then click
View.
b.
In the Add View dialog box, in the View name box, type Create, clear the Create a
partial view (.ascx) and Create a strongly-typed view check boxes, and then click
Add.
Incorporate the Partial view in the Create view as part of the Content2 Content control, by
using the Html.RenderPartial method.
[Visual C#]
<% Html.RenderPartial("Partial"); %>
5-16
[Visual Basic]
<% Html.RenderPartial("Partial") %>
Add the following code to the Create view, in the Content2 Content control,
immediately after the h2 element.
[Visual C#]
<% Html.RenderPartial("Partial"); %>
[Visual Basic]
<% Html.RenderPartial("Partial") %>
6.
7.
b.
In the Home Page Windows Internet Explorer window, in the address bar, append
the following URL, and then press ENTER.
Home/Person
8.
9.
In the Person Windows Internet Explorer window, click the Close button.
In the StronglyTypedView Microsoft Visual Studio window, click the Close button.
Module 6
Designing for Discoverability
Contents:
Lesson 1: Search Engine Optimization
12
6-1
6-2
Lesson 1
6-3
6-4
On the Start menu, point to All Programs, expand IIS 7.0 Extensions, right-click Search Engine
Optimization (SEO) Toolkit 1.0, and then click Run as Administrator.
b.
In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then click
Yes.
2.
In Internet Information Services (IIS) Manager, in the right pane, in the Site Analysis section, click
Create a new analysis.
3.
In the New Analysis dialog box, in the Name box, type Default Web Site analysis, in the Start URL
box, type http://localhost, and then click OK.
Note: It is possible to crawl any website that is publicly accessible on the Internet.
6-5
2.
3.
On the Start menu, point to All Programs, expand IIS 7.0 Extensions, right-click Search Engine
Optimization (SEO) Toolkit, and then click Run as Administrator.
b.
In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then click
Yes.
In Internet Information Services (IIS) Manager, in the right pane, in the Site Analysis section, click
View existing reports.
In the Site Analysis pane, you can double-click any of the reports listed.
Note: In the Site Analysis Report section, you can use the vertically placed tabs on the left of
the Dashboard to get to the following information.
Summary Page
The site analysis summary page provides an overview of all SEO-related violations and problems found on
the analyzed website. In addition, it contains a large set of pre-built reports about your site content and
structure.
You can drill down into each individual item in the report by double-clicking it, or by using the View
Group Details command in the context menu. To open a particular report in a separate query page, use
the Open Query context menu command.
Query Page
Opening any of the pre-built reports from the summary page will result in a new query page.
The query page is used to issue queries against the site analysis data that was collected during the crawl
of the website. In the preceding screenshot, the query is used to get all the pages that reference images
without specifying an alt attribute within the img HTML element.
You can perform a set of actions, accessible from the context menu, for each item within the query results
pane. The following actions are as follows:
6-6
View Details: This option opens a dialog box, which can be used to obtain detailed information about the
item. Specifically, you can see the violation details and suggested corrective actions.
In addition, the actual response data is available if you need to investigate the causes of the reported
violation further. For example, if you want to find out where in the response HTML this violation occurred,
choose the Content tab. This opens the response content with the offending section of the markup
highlighted.
View in Browser: If you right-click a URL, you can select View in Browser from the context menu to show
the URL in the browser.
View Pages Linking to This Page: If you right-click a URL, you can also select View Pages Linking to
This Page. This option opens a new query page that shows all the pages on the site that reference the
URL for the selected item. This kind of report is useful when you want to find out which pages may be
affected if you change a particular URL on your site.
View Pages Linked by This Page: This option opens a new query page that shows all the URLs and
resources that the HTML markup for the currently selected URL references.
View Violations in This Page: This option opens a new query page that shows all the violations found on
the page of the selected URL.
View in Hierarchy: This option opens a hierarchy view page that consists of the following parts:
URLs of all the resources and pages referenced by the selected page.
View Routes to this Page: This option opens a new page that displays the 5 shortest unique routes from
the analysis start page to the currently selected page.
Each route is shown with the start page at the bottom and each subsequent page above, with the selected
page on top. This report can be used to analyze how visitors can get to a particular page on your website,
and whether there any unnecessary pages that can be eliminated for users to discover the selected page
more easily.
Word Analysis: This feature can be used to get an idea of the most commonly used words in a pages
content. These can be used as keywords for accurately describing the web page content for search
engines.
The most often used words within a page will be displayed, which can give you an idea of which keywords
to choose for this page. In addition, the texts of links that reference this page are listed at the bottom of
the dialog box. This helps you to check whether the anchor text used within those links accurately
describes the content of the page.
Lesson 2
Discoverability Files
Contents:
Questions and Answers
6-7
6-8
6-9
b.
In Control Panel, click System and Security, and then click Administrative Tools.
c.
Right-click Internet Information Services (IIS) Manager, and then click Run as administrator.
2.
In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then press
ENTER.
3.
4.
5.
In the Search Engine Optimization pane, in the Robots Exclusion section, click View existing
rules.
In the Actions pane, in the Sitemap Locations section, click Add Sitemaps.
b.
In the Add Sitemaps dialog box, in the URL Paths list, select the Default Web Site, and then
click OK.
Note: Currently there are is no sitemap file, but this action will create the robots.txt file.
7.
In the Actions pane, in the Robots section, click Open Robots.txt File.
Note: The robots.txt file is opened in Notepad. Currently, it holds only a reference to the
sitemap at the default location for the default website.
Following are examples of what you can add to a robots.txt file.
This example disallows all web spiders for the entire site:
# Make changes for all web spiders
User-agent: *
6-10
Disallow: /
The following example disallows a robot named WebSpider from the virtual paths /marketing and
/sales:
# Tell "WebSpider" where it can't go
User-agent: WebSpider
Disallow: /marketing
Disallow: /sales
# Allow all other robots to browse everywhere
User-agent: *
Disallow:
This example allows only a web spider named SpiderOne into a site, while denying all other spiders:
# Allow "SpiderOne" in the site
User-agent: SpiderOne
Disallow:
# Deny all other spiders
User-agent: *
Disallow: /
This last example disallows FrontPage-related paths in the root of your website:
# Ignore FrontPage files
User-agent: *
Disallow: /_borders
Disallow: /_derived
Disallow: /_fpclass
Disallow: /_overlay
Disallow: /_private
Disallow: /_themes
Disallow: /_vti_bin
Disallow: /_vti_cnf
Disallow: /_vti_log
Disallow: /_vti_map
Disallow: /_vti_pvt
Disallow: /_vti_txt
8.
Close Notepad.
9.
In the Control Panel\System and Security\Administrative Tools window, click the Close
button.
In the Control Panel\System and Security window, click the Close button.
6-11
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.
6.
7.
Create a new sitemap for the default website, in a file named Sitemap.xml. Set the change frequency
to daily, do not record the last modified date and time, and set the priority to 1.
a.
In the Search Engine Optimization pane, in the Sitemaps and Sitemap Indexes section, click
Create a new sitemap.
b.
In the Choose Site dialog box, in the Site list, click Default Web Site, and then click OK.
c.
In the Add Sitemap dialog box, in the File Name box, type Sitemap.xml, and then click OK.
d.
In the Add URLs dialog box, in the URL Paths list, click Default Web Site, and then click OK.
8.
In the Internet Information Services (IIS) Manager window, click the Close button.
9.
In the right pane, in the Management Group section, double-click Search Engine
Optimization.
In the Control Panel\System and Security\Administrative Tools window, click the Close
button.
In the Control Panel\System and Security window, click the Close button.
6-12
Lesson 3
13
14
6-13
6-14
2.
3.
4.
Location
Visual C#
D:\Demofiles\CS
Visual Basic
D:\Demofiles\VB
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project, or
press CTRL+SHIFT+O.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\WebFormsRouting.sln or D:\Demofiles\VB\WebFormsRouting.sln and
then click Open.
b.
c.
5.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.
At the top of the Global.asax.cs or Global.asax.vb code file, add the following code.
[Visual C#]
using System.Web.Routing;
[Visual Basic]
Imports System.Web.Routing
6.
[Visual Basic]
Sub RegisterRoutes(ByVal routes As RouteCollection)
' Route name
' URL with parameters
' Web forms page to handle it
routes.MapPageRoute("SearchRoute", "search/{searchterm}", "~/Search.aspx")
End Sub
In the Global.asax.cs or Global.asax.vb window, in the Global class, add the following code.
[Visual C#]
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"SearchRoute",
// Route name
"search/{searchterm}", // URL with parameters
"~/Search.aspx"
// Web forms page to handle it
);
}
[Visual Basic]
Private Sub RegisterRoutes(ByVal routes As RouteCollection)
' Route name
' URL with parameters
' Web forms page to handle it
routes.MapPageRoute("SearchRoute", "search/{searchterm}", "~/Search.aspx")
End Sub
7.
[Visual Basic]
Private Sub Application_Start()
RegisterRoutes(RouteTable.Routes)
End Sub
8.
9.
6-15
6-16
SearchTermLabel.Text = searchTerm;
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim searchTerm As String = "No Search Term specified."
If Not RouteData.Values("searchterm") Is Nothing Then
searchTerm = "You searched for '" &
RouteData.Values("searchterm").ToString() & "'"
End If
SearchTermLabel.Text = searchTerm
End If
End Sub
b.
In the AdventureWorks Microsoft Visual Studio window, on the Debug menu, click Start
Without Debugging, or press CTRL+F5.
11. Navigate directly to the Search page by using the following route.
search/My Search Term
In the Home Page Windows Internet Explorer window, in the address bar, append the
following text.
search/My Search Term
In the RouteConstraints Microsoft Visual Studio window, click the Close button.
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.
3.
Create a new ASP.NET MVC 2 web application named Routes in the D:\Demofiles\CS\Module06 or
D:\Demofiles\VB\Module06 folder, by using the ASP.NET MVC 2 Web Application template.
a.
b.
In the Installed Templates section, expand Visual Basic or Visual C#, and then click Web.
c.
d.
e.
f.
In the Create Unit Test Project dialog box, select the No, do not create a unit test project
option, and then click OK.
4.
6-17
[Visual Basic]
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"} _
)
[Visual Basic]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"} _
)
6-18
[Visual Basic]
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
5.
6.
In the Solution Explorer window, right-click Controllers, point to Add, and then click Controller.
b.
In the Add Controller dialog box, in the Controller Name box, type AddressController, and
then click Add.
return View();
[Visual Basic]
Function List(ByVal houseNumber As Integer) As ActionResult
ViewData("HouseNumber") = houseNumber.ToString()
Return View()
End Function
7.
8.
In the Solution Explorer window, right-click Views, point to Add, and then click New Folder.
b.
c.
In the Solution Explorer window, right-click Address, point to Add, and then click View.
d.
In the Add View dialog box, in the View name box, type List, and then click Add.
Replace the default content of the Content2 Content control in the List view with the following
markup and code, to display the house number requested.
[Visual C#]
<h2>
List</h2>
<h3>
List of houses with number
<%: ViewData["houseNumber"]%></h3>
[Visual Basic]
6-19
<h2>
List</h2>
<h3>
List of houses with number
<%: ViewData("houseNumber")%></h3>
9.
b.
In the Routes Microsoft Visual Studio window, on the Debug menu, click Start Without
Debugging, or press CTRL+F5.
10. Navigate directly to the Address/List view by using the following route.
Address/123
In the Home Page Windows Internet Explorer window, in the address bar, append the
following text, and then press Enter.
Address/123
Note: A message stating List of houses with number 123 is now shown.
11. Navigate directly to the Address/List view by using the following route.
Address/twentyseven
In the List Windows Internet Explorer window, in the address bar, replace Address/123 with
the following text.
Address/twentyseven
In the window The parameters dictionary contains a null entry for parameter
'houseNumber' of non-nullable type Windows Internet Explorer, click the Close button.
6-20
Modify the Address route in Global.asax as shown to add an integer constraint to the
houseNumber parameter.
[Visual C#]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
new {controller="Address", action="List"},
new {houseNumber = @"\d+"}
);
[Visual Basic]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"}, _
New With {.houseNumber = "\d+"} _
)
a.
b.
[Visual Basic]
, _
New With {.houseNumber = "\d+"} _
At this location
[Visual C#]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
new {controller="Address", action="List"} <Insert Code Here>
);
[Visual Basic]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"} <Insert Code Here>
6-21
2.
3.
b.
In the Routes Microsoft Visual Studio window, on the Debug menu, click Start Without
Debugging, or press CTRL+F5.
In the Home Page Windows Internet Explorer window, in the address bar, append the
following text , and then press Enter.
Address/twentyseven
5.
In the window The resource cannot be found. Windows Internet Explorer, click the Close
button.
In the Routes Microsoft Visual Studio window, click the Close button.
6-22
In the Home Page Windows Internet Explorer window, in the address bar, append
the following text.
blog/12-25-2010
7.
8.
In the Blog Archive Windows Internet Explorer window, click the Close button.
In the RouteConstraints Microsoft Visual Studio window, click the Close button.
Module 7
Writing Server-Side Code for Web Forms
Contents:
Lesson 3: Localizing a Web Application
7-1
7-2
Lesson 3
7-3
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Programming Language
Location
Visual C#
D:\Demofiles\CS
Visual Basic
D:\Demofiles\VB
3.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project, or press CTRL+SHIFT+O.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Localization.sln or D:\Demofiles\VB\Localization.sln and then
click Open.
Open Default.aspx.
4.
Add a Label server control after the h2 element, with the following attributes.
Attribute
Value
ID
HelloLabel
Text
Hello in English
a.
b.
5.
6.
Generate local resources by using the Generate Local Resource command on the Tools menu.
7.
In the Localization Microsoft Visual Studio window, on the Tools menu, click
Generate Local Resource.
8.
Notice the newly added attributes, meta:resourcekey, for both the page and the Label server
control.
7-4
9.
10. Add a new string resource named HeaderText.Text with the value Localization.
In the bottom row of the Resource Editor, in the Name box, type HeaderText.Text, and
in the Value box, type Localization.
11. Add a new string resource named DescriptionText with the value ASP.NET Localization.
In the bottom row of the Resource Editor, in the Name box, type DescriptionText, and
in the Value box, type ASP.NET Localization.
b.
b.
c.
d.
15. Localize the string resource named HeaderText.Text with a new value of Lokalisierung.
In the Resource Editor, in the row with a value in the Name column of
HeaderText.Text, in the Value box, type Lokalisierung.
16. Localize the string resource named HelloLabelResource1.Text with a new value of Hallo in
Deutsch.
In the Resource Editor, in the row with a value in the Name column of
HelloLabelResource1.Text, in the Value box, type Hallo in Deutsch.
17. Localize the string resource named PageResource1.Title with a new value of Startseite.
In the Resource Editor, in the row with a value in the Name column of
PageResource1.Title, in the Value box, type Startseite.
18. Localize the string resource named DescriptionText with a new value of ASP.NET
Lokalisierung.
In the Resource Editor, in the row with a value in the Name column of DescriptionText,
in the Value box, type ASP.NET Lokalisierung.
a.
b.
7-5
20. In Default.aspx, localize the hard-coded Localization text implicitly, by adding a Localize server
control within the h2 element, with the following attributes.
Attribute
Value
ID
HeaderText
meta:resourcekey
HeaderText
a.
Place the cursor within the h2 element, just before the text Localization.
b.
c.
b.
<br/><br/>
c.
d.
23. Make the Literal control explicitly localizable, by adding the following text to the Text property.
<%$ Resources: DescriptionText %>
24. Add a new global resource file named WebResources.resx to the App_GlobalResources folder.
a.
b.
c.
In the Add New Item dialog box, in the middle pane, click Resources File, in the Name
box, type WebResources.resx, and then click Add.
Note: The name of the file is the same as the class that will be generated in the Resources
namespace.
25. Add a new string resource named FooterText with the value This is the footer....
7-6
In the bottom row of the Resource Editor, in the Name box, type FooterText, in the
Value box, type This is the footer....
b.
b.
c.
d.
e.
28. Localize the string resource named FooterText with a new value of Dies ist der Fuzeile....
In the Resource Editor, in the row with a value in the Name column of FooterText, in
the Value box, type Dies ist der Fuzeile....
b.
30. Add an h3 element, and within the h3 element, a Label server control named FooterLabel, after
the DescriptionLiteral server control.
a.
b.
<h3></h3>
c.
d.
e.
31. Modify the Label control, by adding the following text to the Text property.
7-7
a.
b.
In the Localization Microsoft Visual Studio window, on the Debug menu, click Start
Without Debugging, or press CTRL+F5.
In the Home Page - Windows Internet Explorer window, on the Tools menu, click
Internet Options.
b.
c.
d.
In the Add Language dialog box, in the Language list, click German (Germany) [deDE], and then click OK.
e.
In the Language Preference dialog box, in the Language list, click German (Germany)
[de-DE], and then click Move up.
In the Home Page Windows Internet Explorer window, click the Close button.
In the Localization Microsoft Visual Studio window, click the Close button.
Module 8
Optimizing Data Management for Web Forms
Contents:
Lesson 1: Managing Data by Using LINQ to Entities
11
8-1
8-2
Lesson 1
Additional Reading
8-3
8-4
2.
3.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type D:\Demofiles\VB\EDM.sln
or D:\Demofiles\CS\EDM.sln, and then click Open.
In Solution Explorer, right-click EDM, point to Add, and then click New Item.
b.
In the Add New Item - EDM dialog box, in the left pane, click Data, and then in the
middle pane, click ADO.NET Entity data Model.
c.
d.
In the Entity Data Model Wizard, on the Choose Model Contents page, click
Generate from database, and then click Next.
e.
f.
If the Choose Data Source dialog box opens, in the Data source list, click Microsoft
SQL Server, and then click Continue.
g.
In the Connection Properties dialog box, in the Server name box, type 10264A-GENDEV\SQLEXPRESS, in the Select or enter a database name box, type
AdventureWorksLT2008R2, and then click OK.
h.
In the Entity Data Model Wizard, on the Choose Your Data Connection page, view
the updated settings, derived from the selected database, and then click Next.
i.
On the Choose Your Database Objects page, in the Which database objects do you
want to include in your model? list, expand Tables, select the Tables check box, clear
the BuildVersion (dbo) check box, and then click Finish.
Note: If the Pluralize or singularize generated object names check box is selected, the wizard
uses English-language rules for singulars and plurals and does the following: makes all
EntityType names singular and all EntitySet names plural; and for NavigationProperty, for
each that returns at most one entity, makes the name singular, and for each that returns more
than one entity, makes the name plural.
If the Include foreign key columns in the model check box is selected, the wizard generates
properties on entity types that correspond to foreign key columns in the database.
j.
4.
In the AdventureWorks.edmx window, click the Customer entity, and then show the
Properties window.
8-5
Notice how Entity Set Name property is plural (Customers), and the Name property is singular
(Customer).
5.
a.
b.
In the AdventureWorks.edmx window, click and possibly expand the Mapping Details
- Customer window.
c.
Under Column Mappings, in particular, observe how the NameStyle SQL Server bit
column is mapped to a .NET Framework Boolean/bool data type.
6.
In the EDM Microsoft Visual Studio window, click the Close button.
b.
8-6
Additional Reading
Overview of LINQ to Entities
For more information about the ADO.NET Entity Framework, see ADO.NET Entity Framework.
For more information about the self-tracking entities, see Working with Self-Tracking Entities
(Entity Framework).
For more information about Entity SQL, see Entity SQL Overview.
Lesson 2
Additional Reading
8-7
8-8
8-9
Additional Reading
Types of Data Source Controls
For more information about the AccessDataSource control, see AccessDataSource Web Server
Control Overview.
For more information about the ObjectDataSource control, see ObjectDataSource Web Server
Control Overview.
For more information about the SiteMapDataSource control, see SiteMapDataSource Web
Server Control Overview.
For more information about the SqlDataSource control, see SqlDataSource Web Server Control
Overview.
For more information about the XmlDataSource control, see XmlDataSource Web Server Control
Overview.
For more information about sorting by using data source controls, see Sorting Data with Data
Source Controls.
For more information about filtering by using data source controls, see Filtering Data Using
Data Source Controls.
For more information about filtering by using the XmlDataSource control, see Filtering Data
Using the XmlDataSource Control.
For information on the types of parameters that can be used in the FilterParameters collection,
see Using Parameters with Data Source Controls.
8-10
For more information about the DetailsView control, see DetailsView Web Server Control
Overview.
Lesson 3
12
13
Additional Reading
16
8-11
8-12
8-13
2.
3.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
b.
In the New Project dialog box, in the left pane, click Visual Basic or Visual C#.
c.
In the middle pane, click ASP.NET Dynamic Data Entities Web Application.
d.
In the Name box, type DDWebApp, in the Location box, type D:\Demofiles\VB or
D:\Demofiles\CS, and then click OK.
In Solution Explorer, right-click DDWebApp, point to Add, and then click New Item.
b.
In the Add New Item - DDWebApp dialog box, in the left pane, click Data, and then in
the middle pane, click ADO.NET Entity data Model.
c.
4.
In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate from
database, and then click Next.
5.
6.
In the Connection Properties dialog box, in the Server name box, type 10264A-GENDEV\SQLEXPRESS, in the Select or enter a database name box, type
AdventureWorksLT2008R2, and then click OK.
7.
In the Entity Data Model Wizard, on the Choose Your Data Connection page, click Next.
8.
On the Choose Your Database Objects page, in the Which database objects do you want to
include in your model? list, expand Tables, select the Tables check box, clear the BuildVersion
(dbo) check box, and then click Finish.
9.
b.
10. In the Global.asax.vb or Global.asax.cs file, add context registration to the RegisterRoutes
procedure.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008R2Entities),
New ContextConfiguration() With {.ScaffoldAllTables = True})
8-14
[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008R2Entities), new
ContextConfiguration()
{
ScaffoldAllTables = true
});
In the Global.asax.vb or Global.asax.cs window, add the following code at the top of to
the RegisterRoutes procedure.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008R2Entities),
New ContextConfiguration() With {.ScaffoldAllTables = True})
[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008R2Entities), new
ContextConfiguration()
{
ScaffoldAllTables = true
});
Note: Point out that this will register the Entity Data model object context for use by using the
Dynamic Data field, and enable the automatic scaffolding of the data model.
11. Save and close the Global.asax.vb or Global.asax.cs file.
a.
On the File menu of Visual Studio 2010, click Save Global.asax.vb or Save
Global.asax.cs.
b.
On the Debug menu of Visual Studio 2010, click Start Without Debugging.
The page displayed in the browser displays a list of the tables you added to the data
model.
13. Test the web application for the Dynamic Data functionality and view some of the dynamically
generated pages.
a.
In the Dynamic Data Site Windows Internet Explorer window, click Addresses.
The page displays the List view that contains the data from the Addresses table.
b.
In the Addresses - Windows Internet Explorer window, click Details, to the left of an
address.
The page displays the Details view that contains the data for the selected row from the
Addresses table.
c.
In the Addresses - Windows Internet Explorer window, click Show all items, and then
click PostalCode.
The page displays the List view that contains the data of addresses, sorted by postal
code.
d.
In the Addresses - Windows Internet Explorer window, in the first row, under
CustomerAddresses, click View CustomerAddresses.
The page displays the List view that contains the data of customer addresses.
e.
f.
g.
h.
i.
In the DDWebApp Microsoft Visual Studio window, click the Close button.
8-15
8-16
Additional Reading
What Is ASP.NET Dynamic Data?
For more information about how the data model represents the information in a database and
how the objects in the database are related to each other, see ASP.NET Dynamic Data Model
Overview.
For more information about the DynamicControl control, see DynamicControl Class.
For more information about the DynamicField control, see the DynamicField Class.
For more information about how the ContextConfiguration class provides information for a
data-context instance to allow customization, see ContextConfiguration Class.
For more information about how the MetadataTypeAttribute class specifies the metadata class
to associate with a data model class, see MetadataTypeAttribute Class.
For more information about page template customization, see How to: Customize the Layout of
an Individual Table By Using a Custom Page Template.
For more information about entity template customization, see Walkthrough: Customizing Table
Layout Using Entity Templates.
For more information about field template customization, see How to: Customize ASP.NET
Dynamic Data Default Field Templates.
For more information about filter template customization, see Walkthrough: Filtering Rows in
Tables That Have a Parent-Child Relationship.
Module 9
Ensuring Quality by Debugging, Unit Testing, and
Refactoring
Contents:
Lesson 1: Debugging and Refactoring Code
12
9-1
9-2
Lesson 1
What Is Refactoring?
Question: What problems have you encountered by refactoring code without the use of a tool?
Answer: Will vary, but maybe not all instances of an object have been renamed.
Question: What percentage of your development time do you spend refactoring code?
Answer: Will vary, but developers who practice TDD, will generally refactor more.
Question: What third-party tools have you used to accomplish refactoring?
Answer: Will vary.
9-3
9-4
2.
3.
Create a new ASP.NET web application by using the New Project dialog box.
a.
b.
In the New Project dialog box, in the left pane, click Visual Basic or Visual C#.
c.
d.
In the Name box, type DebugWebApp, in the Location box, type D:\Demofiles\VB or
D:\Demofiles\CS, and then click OK.
4.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click b, and then click
Microsoft Visual Studio 2010.
In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click
Build DebugWebApp.
5.
Navigate to the self-closing system.web element and notice the attributes and values in the
compilation tag.
6.
7.
8.
9.
In the DebugWebApp - Microsoft Visual Studio window, click the Close button.
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
3.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.
4.
9-5
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
var i = 1;
var j = 2;
var answer = i + j;
}
5.
6.
Right-click the selection, point to Refactor, and then click Extract Method.
7.
In the Extract Method dialog box, in the New method name box, type Add, and then click OK.
Note: The code has been extracted into a new method, and the function has been called in its
place.
8.
9.
In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click Build
DebugWebApp.
In the DebugWebApp - Microsoft Visual Studio window, click the Close button.
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.
3.
In Solution Explorer, right-click DebugWebApp, point to Add, and then click Class.
4.
In the Add New Item DebugWebApp dialog box, in the Name box, type Person, and then
click Add.
9-6
5.
Create a single private variable named name, by adding the following code
[Visual C#]
public class Person
{
private string name;
}
6.
In the Person.cs window, right-click name, point to Refactor, and then click Encapsulate Field.
7.
8.
In the Preview Reference Changes - Encapsulate Field dialog box, click Apply.
Note: The new property with accessors has been created.
9.
In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click
Build DebugWebApp.
In the DebugWebApp - Microsoft Visual Studio window, click the Close button.
2.
3.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.
4.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Add the age member variable, Age property, and Hire method to the Person class.
[Visual C#]
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public void Hire()
{
// implementation Code
}
}
In the Person.cs window, in the Person class, append the following code.
[Visual C#]
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public void Hire()
{
// implementation Code
}
5.
6.
In the Extract Interface dialog box, select the Age, Hire(), and Name check boxes, and then
click OK.
Note: The new interface is now created in a new file.
7.
Display the Person.cs file, and notice how the class now implements the new interface.
8.
9.
In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click
Build DebugWebApp.
In the DebugWebApp - Microsoft Visual Studio window, click the Close button.
9-7
9-8
Lesson 2
10
9-9
9-10
2.
3.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\UnitTest.sln or D:\Demofiles\VB\UnitTest.sln, and then click Open.
4.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
[Visual C#]
public int Age
{
get { return personAge; }
set
{
if (value < 21)
throw new Exception("Age must be greater than 21");
personAge = value;
}
}
[Visual Basic]
Public Property Age As Integer
Get
Return personAge
End Get
Set(ByVal value As Integer)
If value < 21 Then
Throw New Exception("Age must be greater than 21")
End If
personAge = value
End Set
End Property
5.
Right-click anywhere in the code for the Age property, and then click Create Unit Tests.
6.
In the Create Unit Tests dialog box, ensure the Age check box is selected, and then click OK.
7.
8.
In the open PersonTest.cs or PersonTest.vb file, review the AgeTest test method.
9.
Change the declaration code for the expected local variable as follows.
[Visual C#]
int expected = 25;
[Visual Basic]
Dim expected As Integer = 25
[Visual C#]
Assert.Inconclusive("Verify the correctness of this test method.");
[Visual Basic]
Assert.Inconclusive("Verify the correctness of this test method.")
11. Right-click the AgeTest method declaration, and then click Run Tests.
Note: In the Test Results window, notice the AgeTest test passed.
12. Change the declaration code for the expected local variable as follows.
[Visual C#]
int expected = 2;
[Visual Basic]
Dim expected As Integer = 2
13. Right-click the AgeTest method declaration, and then click Run Tests.
Note: In the Test Results window, notice the AgeTest test failed.
14. Close Microsoft Visual Studio 2010.
In the UnitTest - Microsoft Visual Studio window, click the Close button.
9-11
9-12
Lesson 4
Test-Driven Development
Contents:
Question and Answers
13
9-13
Module 10
Securing a Web Application
Contents:
Lesson 1: Configuring Authentication
10
10-1
10-2
Lesson 1
Configuring Authentication
Contents:
Question and Answers
10-3
10-4
b.
In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and
then click Yes.
2.
In Internet Information Services (IIS) Manager, in the left pane, expand 10264-GEN-DEV (10264GEN-DEV\Admin), and then expand Sites.
3.
Click Default Web Site, and notice the available options in the right pane.
2.
Right-click Anonymous Authentication and then click Enable or Disable to enable or disable
anonymous authentication for the selected web application.
3.
Right-click Anonymous Authentication and then click Edit to edit the credentials used with
anonymous authentication.
4.
2.
Right-click Basic Authentication and then click Enable or Disable to enable or disable basic
authentication for the selected web application.
3.
Right-click Basic Authentication and then click Edit to edit the default domain or realm used
with basic authentication. The default domain is used to specify the domain against which users
are authenticated by default. The realm, a DNS domain name or address, uses the credentials that
have been authenticated against as the default domain.
4.
2.
Right-click Digest Authentication and then click Enable or Disable to enable or disable Digest
authentication for the selected web application.
Note: The 10264A-GEN-DEV machine is not joined to a domain, so it is not possible to enable
Digest authentication.
3.
Right-click Digest Authentication and then click Edit to edit the realm used with Digest
authentication. The realm, a DNS domain name or address, uses the credentials that have been
authenticated against as the internal Windows domain.
4.
Click Cancel in the Edit Digest Basic Authentication Settings dialog box.
10-5
2.
Right-click Windows Authentication and then click Enable or Disable to enable or disable
Windows authentication for the selected web application.
3.
Right-click Windows Authentication and then click Advanced Settings to configure Extended
Protection and enable or disable kernel-mode authentication. Extended Protection enhances the
protection and handling of credentials when authenticating network connections by using
Windows authentication.
4.
10-6
Lesson 2
10-7
10-8
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET Web Application, in the Name box, type Module10, in the
Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.
3.
4.
5.
6.
In the Web Site Administration Tool, on the Home page, click Security.
Note: On the Security page, you find the following options.
7.
8.
In the Create User section, in the User Name box, type student, in the Password box, type
Pa$$w0rd, in the Confirm Password box, type Pa$$w0rd, in the E-mail box, type
[email protected], and then click Create User.
9.
In the ASP.NET Web Site Administration Tool window, click the Close button.
10. Open the App_Data folder in Windows Explorer, by using Solution Explorer.
In Solution Explorer, right-click App_Data, and then click Open Folder in Windows
Explorer.
11. Notice the new database, ASPNETDB.MDF, and the corresponding log file, aspnetdb_log.ldf,
have been created in the App_Data folder.
12. Close Windows Explorer.
In the D:\Demofiles\CS\Module10\App_Data or
D:\Demofiles\VB\Module10\App_Data window, click the Close button.
In the Module10 Microsoft Visual Studio window, click the Close button.
10-9
10-10
Lesson 3
11
12
10-11
10-12
2.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module10\Module10.sln or
D:\Demofiles\VB\Module10\Module10.sln, and then click Open.
3.
4.
5.
6.
In the Web Site Administration Tool, on the Home page, click Security.
7.
8.
9.
In the New role name box, type admin, and then click Add Role.
In the ASP.NET Web Site Administration Tool window, click the Close button.
In the Module10 Microsoft Visual Studio window, click the Close button.
Module 11
Applying Master Pages and CSS
Contents:
Lesson 1: Applying Master Pages
11-1
11-2
Lesson 1
11-3
Demonstration: Using a Master Page in Web Forms and MVC View Pages
Question: What ideas came to mind during this demonstration on using master pages?
Answer: May vary.
11-4
2.
3.
4.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET Web Application, in the Name box, type
NewMasterPage, in the Location box, type D:\Demofiles\CS or D:\Demofiles\VB,
and then click OK.
In Solution Explorer, right-click NewMasterPage, point to Add, and then click New
Item.
b.
In the Add New Item NewMasterPage dialog box, in the middle pane, click Master
Page, in the Name box, type SingleColumn.Master, and then click Add.
5.
Set the value of the ID attribute of the existing ContentPlaceHolder in the form element to
MainContentPlaceHolder.
<asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
6.
In the form element, and before the opening div tag, create a new div element with an ID
attribute value of header.
11-5
7.
In the new div element, add a new ContentPlaceHolder control and set the ID attribute value to
HeadContentPlaceHolder.
<div id="header">
<asp:ContentPlaceHolder ID="HeadContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
</div>
8.
9.
In the NewMasterPage Microsoft Visual Studio window, click the Close button.
b.
Demonstration: Using a Master Page in Web Forms and MVC View Pages
Using master page in a new Web Forms page
1.
2.
3.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module11\AdventureWorks.sln or
D:\Demofiles\VB\Module11\AdventureWorks.sln, and then click Open.
Add a new Web Form named UsingMasterPage based on the Site.Master master page to the
project.
a.
In Solution Explorer, right-click AdventureWorks, point to Add, and then click New
Item.
b.
In the Add New Item AdventureWorks dialog box, in the middle pane, click Web
Form using Master Page, in the Name box, type UsingMasterPage, and then click
Add.
c.
In the Select a Master Page dialog box, in the Contents of folder list, click
Site.Master, and then click OK.
11-6
4.
5.
6.
7.
In the AdventureWorks Microsoft Visual Studio window, on the File menu, click
Close Solution.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module11\AdventureWorksMvc.sln or
D:\Demofiles\VB\Module11\AdventureWorksMvc.sln, and then click Open.
2.
11-7
Add a new View named UsingMasterPage.aspx based on the Site.Master master page to the
project. The view should be rendered by the Home controller, and saved to the Views\Home
folder.
a.
In Solution Explorer, expand Views, right-click Home, point to Add, and then click
View.
b.
In the Add View dialog box, in the View name box, type UsingMasterPage.aspx,
ensure the Select master page check box is selected, ensure the box below the Select
master page check box contains ~/Views/Shared/Site.Master, and then click Add.
3.
4.
5.
Test your view page, by appending the following route to the existing URL, and then press
ENTER.
Home/UsingMasterPage
6.
7.
11-8
8.
In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.
Lesson 2
10
11
11-9
11-10
11-11
2.
3.
4.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module11\AdventureWorks.sln or
D:\Demofiles\VB\Module11\AdventureWorks.sln, and then click Open.
In Solution Explorer, right-click Styles, point to Add, and then click New Item.
b.
In the Add New Item - AdventureWorks dialog box, in the middle pane, click Style
Sheet, in the File name box, type Demo.css, and then click Add.
5.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
.demo-bg-1 { background-color:Lime; }
.demo-bg-2 { background-color:Fuchsia; }
.demo-bold { font-weight:bold; }
.demo-text-maroon { color:Maroon; }
6.
7.
Add the following markup to the head element, to link to the new CSS file.
<link href="~/Styles/Demo.css" rel="Stylesheet" type="text/css" />
In the Site.Master window, in the head element, below the existing link element, type
the following markup.
11-12
8.
Edit the div element with the class attribute of main, to apply the main, demo-bg-1, and
demo-text-maroon styles.
<div class="main demo-bg-1 demo-text-maroon">
In the Site.Master window, the div element with the class attribute of main, append
the following markup to the class attribute.
demo-bg-1 demo-text-maroon
9.
Edit the div element with the class attribute of footer, to apply the footer, demo-bg-2, and the
demo-bold styles.
<div class="footer demo-bg-2 demo-bold">
In the Site.Master window, the div element with the class attribute of footer, append
the following markup to the class attribute.
demo-bg-2 demo-bold
In the Home Page Windows Internet Explorer window, click the Close button.
In the AdventureWorks Microsoft Visual Studio window, click the Close button.
Module 12
Developing Client-side Scripts and Services
Contents:
Lesson 1: Developing Client-side Scripts
10
12-1
12-2
Lesson 1
12-3
12-4
2.
3.
In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET Web Application, in the Name box, type Script, in the
Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.
4.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Append the following markup and code after the closing html tag.
<script type="text/JavaScript">
function inlineGreet()
{
alert('Hello World (inline)');
}
</script>
2.
In Solution Explorer, right-click Scripts, point to Add, and then click New Item.
b.
In the Add New Item Script dialog box, in the middle pane, click JScript File, in the
Name box, type Site.js, and then click Add.
3.
4.
5.
In the Site.Master window, append the following markup to the head element.
2.
Call the inlineGreet function from the onload event of the body element.
<body onload="inlineGreet()">
3.
4.
5.
Press CTRL+F5.
Note: The alert box is displayed with the greeting from the inline script.
6.
In the Home Page - Windows Internet Explorer window, click Greet (external).
Note: The alert box is displayed with the greeting from the external script file.
7.
8.
In the Home Page Windows Internet Explorer window, click the Close button.
In the Script Microsoft Visual Studio window, click the Close button.
12-5
12-6
Lesson 2
Implementing Ajax
Contents:
Detailed Demo Steps
12-7
2.
3.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\PartialUpdates.sln or D:\Demofiles\VB\PartialUpdates.sln, and then
click Open.
4.
9.
Open the Toolbox, expand Data, and then drag a GridView control to the UpdatePanel
control.
Add a SqlDataSource control to the Default.aspx Web Form, in the BodyContent control.
8.
Open the Toolbox, expand AJAX Extensions, and then double-click UpdatePanel.
Add a GridView control to the Default.aspx Web Form, in the UpdatePanel control.
7.
Open the Toolbox, expand AJAX Extensions, and then double-click ScriptManager.
Add an UpdatePanel control to the Default.aspx Web Form, in the BodyContent control.
6.
Add a ScriptManager control to the Default.aspx Web Form, in the BodyContent control.
5.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Open the Toolbox, expand Data, and then drag a SqlDataSource control to the
BodyContent control.
Set the DataSourceID property of the GridView control to the ID of the SqlDataSource control.
a.
b.
On the GridView control, click the Smart Tag in the GridView Tasks pane, and then in
the Choose Data Source list, click SqlDataSource1.
Set the GridView control to allow paging, by using the Smart Tag and the GridView Tasks
pane.
On the GridView control, click the Smart Tag, and then in the GridView Tasks pane,
select Enable Paging check box.
10. Configure the Data Source for the SqlDataSource control to use the existing
AdventureWorks2008R2ConnectionString, by using the Start Tag and the SqlDataSource
Tasks pane. The CustomerID, Title, FirstName, MiddleName, LastName, CompanyName,
SalesPerson, and Phone columns of the Customer table should be used.
a.
On the SqlDataSource control, click the Smart Tag, and then in the SqlDataSource
Tasks pane, click Configure Data Source.
12-8
b.
In the Configure Data Source SqlDataSource1 wizard, on the Choose Your Data
Connection page, in the Which data connection should your application use to
connect to your database? list, click AdventureWorks2008R2ConnectionString, and
then click Next.
c.
On the Configure the Select Statement page, ensure the Specify columns from a
table or view check box is selected, in the Name list, click Customer, in the Columns
list, select the CustomerID, Title, FirstName, MiddleName, LastName,
CompanyName, SalesPerson, and Phone check boxes, and then click Next.
d.
Click Finish.
Press CTRL+F5.
At the bottom of the GridView control, click different page numbers 4-5 times.
In the Home Page Windows Internet Explorer window, click the Close button.
In the Script Microsoft Visual Studio window, click the Close button.
12-9
12-10
Lesson 3
Creating Services
Contents:
Detailed Demo Steps
11
12-11
2.
3.
4.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Script\Script.sln or D:\Demofiles\VB\Script\Script.sln, and then
click Open.
In Solution Explorer, right-click Script, point to Add, and then click New Item.
b.
In the Add New Item - Script dialog box, in the middle pane, click Ajax-enabled WCF
Service, in the Name box, type GreetingsService.svc, and then click Add.
Remove the default DoWork method and comments from the service class.
[Visual C#]
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is
WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
// Add more operations here and mark them with [OperationContract]
[Visual Basic]
' To use HTTP GET, add <WebGet()> attribute. (Default ResponseFormat is
WebMessageFormat.Json)
' To create an operation that returns XML,
' add <WebGet(ResponseFormat:=WebMessageFormat.Xml)>,
' and include the following line in the operation body:
' WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"
<OperationContract()>
Public Sub DoWork()
' Add your operation implementation here
End Sub
' Add more operations here and mark them with <OperationContract()>
In the GreetingsService.svc window, select the following code, and then press DELETE.
12-12
[Visual C#]
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is
WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
// Add more operations here and mark them with [OperationContract]
[Visual Basic]
' To use HTTP GET, add <WebGet()> attribute. (Default ResponseFormat is
WebMessageFormat.Json)
' To create an operation that returns XML,
' add <WebGet(ResponseFormat:=WebMessageFormat.Xml)>,
' and include the following line in the operation body:
' WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"
<OperationContract()>
Public Sub DoWork()
' Add your operation implementation here
End Sub
' Add more operations here and mark them with <OperationContract()>
5.
[Visual C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace Script
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class GreetingsService
{
[OperationContract]
public string Greet()
{
return "Hello World";
}
}
}
[Visual Basic]
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
12-13
<ServiceContract(Namespace:="")>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirement
sMode.Allowed)>
Public Class Greeting
<OperationContract()>
Public Function Greet() As String
Return "Hello World"
End Function
End Class
6.
7.
In the Script Microsoft Visual Studio window, click the Close button.
2.
3.
In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.
b.
In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Script\Script.sln or D:\Demofiles\VB\Script\Script.sln, and then
click Open.
4.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Remove the onload attribute and value from the opening body tag.
<body onload="inlineGreet()">
5.
6.
7.
In the Default.aspx window, select the markup within the opening and closing Content
tags for the Content control with an ID attribute value of BodyContent, and then press
DELETE.
Add the following markup to register the WCF service using the ScriptManager control. Add the
markup in the empty Content control with an ID attribute value of BodyContent.
<asp:ScriptManager id="ScriptManager1" runat="server">
<services>
<asp:ServiceReference path="~/GreetingsService.svc" />
</services>
12-14
</asp:ScriptManager>
8.
Add the following code to the Default.aspx page in the empty Content control with an ID
attribute value of BodyContent.
<script type="text/JavaScript">
function greetUser() {
GreetingsService.Greet(onSuccess);
}
function onSuccess(result) {
alert(result);
}
</script>
9.
Add the following markup to the Default.aspx page in the empty Content control with an ID
attribute value of BodyContent.
<input type="button" value="Invoke Service" onclick="greetUser()" />
Press CTRL+F5.
In the Home Page Windows Internet Explorer window, click the Close button.
In the Script Microsoft Visual Studio window, click the Close button.
Module 13
Implementing Advanced Ajax in a Web Application
Contents:
Lesson 3: Working with jQuery and Ajax Events
13-1
13-2
Lesson 3
13-3
2.
3.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.
Create a new ASP.NET MVC 2 web application named jQueryEventHandlers in the D:\Demofiles\CS
or D:\Demofiles\VB folder.
a.
In the Start Page Microsoft Visual Studio window, on the File menu, click New Project.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the middle
pane, click ASP.NET MVC 2 Web Application, in the Name box, type jQueryEventHandlers, in
the Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.
c.
In the Create Unit Test Project dialog box, select the No, do not create a unit test project
check box, and then click OK.
[Visual C#]
public string ServerTime(string message)
{
if (message == "ex")
throw new ArgumentException();
}
return "You said " + message + ", and the time is " + DateTime.Now;
[Visual Basic]
Function ServerTime(ByVal message As String) As String
If message = "ex" Then
Throw New ArgumentException()
End If
Return "You said " & message & ", and the time is " & DateTime.Now
End Function
13-4
[Visual Basic]
Function ServerTime(ByVal message As String) As String
If message = "ex" Then
Throw New ArgumentException()
End If
Return "You said " & message & ", and the time is " & DateTime.Now
End Function
Note: If you pass in the string ex, the method will throw an exception on the server.
4.
In the Views/Home/Index view, replace the current content of the Content2 or indexContent
Content control with a text box, a button, a div for logging the Ajax messages, and a div element
for displaying some of the results from the Ajax call.
<h2>
ServerTime</h2>
<input id="yourtext" type="text" name="message" /><input id="submit" type="button"
value="Load Data" />
<div id="log">
</div>
<p id="results">
</p>
a.
In Solution Explorer, expand Views, expand Home, and then double-click Index.aspx.
b.
Select the markup in the Content2 or indexContent Content control, and then press DELETE.
c.
5.
Create and enable event handlers for the .ajaxSend(), .ajaxComplete(), and .ajaxError() events, by
adding the following markup and code to the Index view.
});
$("#log").ajaxError(function () {
alert("error");
});
});
</script>
In the Index.aspx window, type the following markup at the bottom of the Content2 or
indexContent Content control.
<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#log").ajaxSend(function () {
$(this).slideDown("fast").text("Loading...");
});
$("#log").ajaxComplete(function () {
$(this).slideUp("slow", function () { $(this).text(""); });
});
});
$('#submit').click(function () {
var msg = $("#yourtext").val();
$("#results").load('<%= Url.Action("ServerTime") %>', { message: msg
});
$("#log").ajaxError(function () {
alert("error");
});
});
</script>
6.
7.
8.
In Windows Internet Explorer, in the text box, type This is a test, and then click Load Data.
Note: When the call to the controller method is made, the text Loading... is displayed below
the text box. When the call completes, a message similar to You said This is a test, and the
time is 9/16/2010 12:00:46 AM, is displayed.
9.
In Windows Internet Explorer, in the text box, type ex, and then click Load Data.
Note: When the call to the controller method is made, the text Loading... is displayed below
the text box. When the call completes, a message box is displayed, containing the text error.
13-5
13-6
In the Home Page Windows Internet Explorer window, click the Close button.
In the jQueryEventHandlers Microsoft Visual Studio window, click the Close button.
ASP.NET Deployments
Module 14
ASP.NET Deployments
Contents:
Lesson 1: Overview of Web Application Deployments
14-1
14-2
Lesson 1
ASP.NET Deployments
14-3
One-Click Publish
Question: In which scenarios have you used One-Click publishing? What were the advantages? What
were the disadvantages?
Answer: Will vary.
Enterprise Scenarios
Question: How many intermediate environments have you seen in an enterprise scenario? Did you
ever encounter a scenario where no intermediate environments were used?
Answer: Will vary.
14-4
Lesson 2
ASP.NET Deployments
14-5
Module 15
Developing a Web Application by Using Silverlight
Contents:
Lesson 3: Create a Silverlight Application
15-1
15-2
Lesson 3
15-3
15-4
2.
3.
4.
In the Start Page Microsoft Visual Studio window, on the File menu, click New Project.
b.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click Silverlight Application, in the Name box, type SilverlightApp , in the
Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.
c.
In the New Silverlight Application dialog box, verify the following, and then click OK.
d.
Verify that Host the Silverlight Application in a new Web site is selected (the default).
e.
f.
Specify the new web project type as ASP.Net Web Application Project.
The App.xaml file is used by the application to declare shared resources. Also, its codebehind file is used to handle global application level events like Startup and Exit, similar
to Global.asax in an ASP.NET application.
MainPage.xaml is the default Silverlight page in the application. This project is built
into a XAP file, and used by the Silverlight plug-in to download and run the application
in the users browser. The XAP file contains the compressed assemblies and resources
that are necessary to run the application.
SilverlightApp.Web is the hosting project. This project contains the web pages
which will host the Silverlight Application.
5.
On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual
Studio 2010, and then click Microsoft Visual Studio 2010.
Open SilverlightAppTestPage.aspx.
Switch to Source view. The object element is the container for the Silverlight application
SilverlightApp. It contains references to the Silverlight runtime, including a link to
download it, if it is not already installed in the users browser.
R-1
Note Not all training products will have a Knowledge Base article if that is the case, please ask your
instructor whether or not there are existing error log entries.
Courseware Feedback
Send all courseware feedback to [email protected]. We truly appreciate your time and effort.
We review every e-mail received and forward the information on to the appropriate team. Unfortunately,
because of volume, we are unable to provide a response but we may use your feedback to improve your
future experience with Microsoft Learning products.
Reporting Errors
When providing feedback, include the training product name and number in the subject line of your email. When you provide comments or report bugs, please include the following:
Please provide any details that are necessary to help us verify the issue.
Important All errors and suggestions are evaluated, but only those that are validated are added to the
product Knowledge Base article.