Developing ASPDynami Data
Developing ASPDynami Data
Table of Contents
Developing ASP.NET Dynamic Data Web Applications .......................................................... 1
Exercise 1 Setup Lab .....................................................................................................................................................2
Exercise 2 Creating a Data-Driven Web Application ....................................................................................................5
Exercise 3 Adding Additional Metadata and Validations to the Model ...................................................................... 16
Exercise 4 Customizing a Dynamic Data Application................................................................................................. 22
Developing ASP.NET Dynamic Data Web Applications
Objectives After completing this lab, you will be better able to:
Create a data-driven web application using ASP.NET Dynamic Data
Add validation to the data model of your application
Customize ASP.NET Dynamic Data rendering
Customize ASP.NET Dynamic Data pages
Customize ASP.NET Dynamic Data fields
Scenario ASP.NET Dynamic Data provides the Web application scaffolding and
templating that enables you to build rich data-driven Web applications. This
scaffolding is a mechanism that enhances the functionality of the existing
ASP.NET framework by adding the ability to dynamically display pages or fields
based on your underlying data model, without having to create pages manually.
Dynamic Data infers the resource to display and the view to create from the URL
of the request. This mechanism is very flexible. It provides a view of the data
based on default templates, while enabling complete customization. You can
customize the display for a specific resource or for the web application as a
whole.
Page 1 of 29
Developing ASP.NET Dynamic Data Web Applications
Exercise 1
Setup Lab
Scenario
You must perform the following steps to prepare your computer for this lab. This consists primarily of creating the
database that will be used in the lab and initializing it with default data.
Page 2 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
b. A dialog box appears warning that the file is not signed; choose Yes to proceed
anyway.
c. When prompted for the location of the snippets, highlight all snippets, click the
check box next to My Code Snippets, and click Next.
Page 3 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
d. Click Finish to install the code snippets.
Page 4 of 29
Developing ASP.NET Dynamic Data Web Applications
Exercise 2
Creating a Data-Driven
Driven Web Application
Scenario
In this exercise you will learn the fundamentals of ASP.NET Dynamic Data applications, their core concepts, how
they work and how to use them. Through the exercise you will build an application from scratch that lets you
navigate through the entities you added to the data model and its relationships, without having to write a single line
of code.
2. Create the Database a. Add a new folder to your project called Model.. To do this, right-click
right the project
Model and click Add > New Folder.. When the folder is added to your project, rename it
to Model
Model.
b. Add the Entity Data Model that will represent the databasese model. To do this,
click the newly created Model folder and then click Add > New Item. On
right-click
the Add New Item dialog, click on ADO.NET Entity Data Model. Model Type
Page 5 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
AdventureWorks.edmx in the Name textbox and click Add.
c. Select the Generate from database option and click the Next button.
d. Add a new database connection. To do this, click the New Connection… button.
e. If Choose Data Source window appears, then choose Microsoft SQL Server and
press Continue.
f. Enter NETSP1LABS for the server name, select the AdventureWorksLT
ventureWorksLT
database, and then click the OK button.
Note: NETSP1LABS is the default alias for the database server installed when the
SetupEx.cmd script was run at the beginning of this lab.
Page 6 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
g. Enter AdventureWorksContext for the name of the connection string for your
Entity Data Model, and click the Next button.
h. Add some tables to your Entity Data Model.. To do this, expand the Tables node
and select the following tables:
Product (SalesLT)
ProductCategory (SalesLT)
ProductModel (SalesLT)
Page 7 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Page 8 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
to enable debugging and click OK.
b. You will be redirected by default to a Default.aspx page of the ASP.NET
Dynamic Data Web Application; this page displays a list that contains
con the entities
that you added to the data model.
Note: The Default.aspx home page is in the project’s root folder. It is created by the
Dynamic Data Entities Web Application template. If you wish to change it, you can
open it up and edit it however you want.
c. Click the Product table to see all the products that are persisted in the database.
The scaffolding feature will generate the entire grid view and will make the
appropriate query to the database to retrieve all the products.
Page 9 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Note: Dynamic data infers that the text to display is the one contained in the first
f text
field found in the foreign key table. So if the foreign key table is not designed in this
Page 10 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
way, unexpected results may occur. This can be solved by customizing Dynamic Data,
a topic which will be covered in the next exercise.
d. You will notice that the Product Categories and Product Models values are
links, so click on ““Road Frames” to navigate to the ProductCategory table with
Road Frames
“Road Frames”” as the selected category. You’ll be taken to a page that displays
that specific category.
e. Go back to the previous page, by clicking the Back button of the browser.
f. At the bottom of the product table you will see paging controls.
controls These controls
appear when the number of rows is large and let you navigate through pages and
select the number of rresults per page to be shown.
Page 11 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Note: Automatic filters are created based on foreign key and boolean fields
field in each
table.
Page 12 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
h. Select the second product by clicking on Details link. The details for that specific
product will be shown at the bottom of the page.
i. Edit the product by clicking the Edit link at the bottom of the details view. Notice
that foreign col
columns
umns are rendered as dropdown lists to improve user experience.
Page 13 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
j. Change the values and then click Update, or click Cancel to cancel the edit
operation.
Note: You can also try Delete and New operations.
k. Close the browser to stop debugging.
5. Adding Metadata to a. Add a Product partial class in order to add metadata attributes related to products.
your Model right-click the Model folder and then click Add New Item.
To do this, right Item On the
Add New Item dialog, click Class. In the Name textbox, enter Product.cs as file
name and click Add.
Page 14 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
e. Associate the ProductMetaData class with the Product class by adding a
MetadataType attribute to the Product class. To do this, add the following code
above the Product class definition.
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
private class ProductMetadata
{
}
}
f. Add a ProductNumber property to the ProductMetaData class.
private class ProductMetadata
{
public object ProductNumber { get; set; }
}
Note: When creating a metadata class for the sole purpose of adding metadata to a
model class, the type of the metadata properties is not important. This is why the
Name property is defined as object type, when in the underlying model class is defined
as a string type.
g. Apply the DisplayName attribute to the ProductNumber property. To do this,
add the following code above the property definition.
[DisplayName("Code")]
private object ProductNumber { get; set; }
Note: This DisplayName attribute specifies that the property will be shown in the web
application with another name, in this case “Code”.
h. Set off scaffolding generation for the following properties: ThumbNailPhoto,
ThumbnailPhotoFileName and ModifiedDate. To do this, add the following
code to the ProductMetadata class.
private class ProductMetadata
{
...
[ScaffoldColumn(false)]
public object ThumbNailPhoto { get; set; }
[ScaffoldColumn(false)]
public object ThumbnailPhotoFileName { get; set; }
[ScaffoldColumn(false)]
public object ModifiedDate { get; set; }
}
Note: The ScaffoldColumn attribute has a Boolean parameter to specify whether to
create scaffolds for the property, in this way properties which have the
ScaffoldColumn attribute set to false are not displayed.
Page 15 of 29
Developing ASP.NET Dynamic Data Web Applications
Exercise 3
Adding Additional Metadata and Validations to the Model
Mode
Scenario
In this exercise you will learn how to customize an ASP.NET Dynamic Data application applying metadata attribute
to the Entities to adapt them to your own rendering and validation needs.
Page 16 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
2. Review Application a. Press F5 to run the ASP.NET Dynamic Data Web Application.
Actual State Issues Note: If the dialog Debugging Not Enabled appears, select Modify the Web.config file
to enable debugging and click OK.
b. You will be redirected by default to the Default.aspx page of the ASP.NET
Dynamic Data Web Site; this page displays a list with the tables that you added to
the data model.
c. Click SalesOrderHeader table to see its data and then click the Customer filter
combo box, you will notice that its values are wrong since Dynamic Data cannot
correctly infer which Customer table field to display as the foreign key text.
Note: When a data field is a foreign key of another table, Dynamic Data displays this
column as a link to the other table. Dynamic Data uses the first column of type string
strin
as the link text when the relationship between the tables is a one
one-to
to-one relationship.
d. Press Esc to close the combo. Notice that the date fields aren’t formatted (are
displaying redundant time data).
Page 17 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Page 18 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Page 19 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
class.
[MetadataType(typeof(SalesOrderHeaderMetadata))]
public partial class SalesOrderHeader
{
private class SalesOrderHeaderMetadata
{
...
}
}
4. Adding Validations a. In Solution Explorer, open the Model folder. Double-click the Product.cs file to
Using Attributes open it up to add validations related to products.
b. Add a Name property to the ProductMetaData class and apply the Required and
StringLength attributes to it. To do this, add the following code in the
ProductMetaData class.
private class ProductMetadata
{
...
[StringLength(30)]
[Required(ErrorMessage = "Product name is required.")]
public object Name { get; set; }
}
Note: The Required attribute specifies that the property value must not be empty and
the StringLength attribute specifies the maximum length allowed for a string. The
ErrorMessage parameters denote what message to display when the property doesn’t
match the constraint.
c. Add a StandardCost property to the ProductMetaData class and apply the
Range attribute to it. To do this, add the following code in the ProductMetaData
class.
private class ProductMetadata
{
...
}
Note: This Range attribute specifies a valid numeric interval for a specific field.The
ErrorMessage parameters denote what message to display when the property isn’t
specified.
All these attributes support the ErrorMessage named parameter that enables you to
specify a message that is displayed when validation fails. The ErrorMessage value
can contain indexed placeholders for the other parameters. For example, the
followings are the possible indexed placeholders’ values that you can use for Range
attribute:
0 - Returns the field name.
1 - Returns the minimum value for the Range attribute
2 - Returns the maximum value for the Range attribute
d. Apply a RegularExpression attribute to the ProductNumber property. To do
this, add the following code shown in bold above the property definition.
[RegularExpression("[A-Z]{2}-[A-Z0-9]{4}(-[A-Z0-
9]{1,2})?", ErrorMessage = "Invalid code.")]
Page 20 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
[DisplayName("Code")]
public object ProductNumber { get; set; }
Note: The RegularExpression attribute specifies a regular expression that will be
used to validate a string. In this case, you are specifying the correct format allowed
for the product number.
5. Adding Validations a. Create the event handler that will be called every time the ListPrice field changes.
Using To do this, open the Product.cs partial class file you have created in the previous
DynamicValidator task and add the partial OnListPriceChanging method. The value to be validated
is passed to the method as a parameter.
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
partial void OnListPriceChanging(decimal value)
{
}
...
}
b. Implement the validation logic. To do this, insert the following code as the
method’s body.
Note: This method checks that the new ListPrice value entered by the user is a positive
number. If the data does not pass validation, the method throws an exception.
partial void OnListPriceChanging(decimal value)
{
if (value < 0)
{
throw new ValidationException("List Price must be
positive");
}
}
Note: The naming convention for the methods used by the object model follows a
specific scheme. The method name starts with On, followed by the field (column)
name, followed by the event verb. For example, if the column name is ListPrice the
method and the event is Changing, name is OnListPriceChanging.
The exception type thrown in our model method was of type ValidationException.
This is a new type added to the System.ComponentModel.DataAnnotations
namespace that is meant to denote an exception as a result to a data validation error.
Page 21 of 29
Developing ASP.NET Dynamic Data Web Applications
Exercise 4
Customizing a Dynamic Data Application
Scenario
In this exercise you will learn how to customize an ASP.NET Dynamic Data application modifying the defaults data
views to adapt them to your own rendering needs.
Tasks Detailed Steps
Complete the following a. Open Microsoft Visual Studio 2008 from Start | All Programs | Microsoft
tasks on: Visual Studio 2008 | Microsoft Visual Studio 2008
2008.. Open the solution file
AspNetDynamicData.sln located in the folder AspNetDynamicData\Ex03-
AspNetDynamicData
VistaOffice07 CustomizingDynamicData
CustomizingDynamicData\begin. Alternatively, you may continue with the
1. Review Application solution created after completing Exercise 3.
Actual State Issues b. Press F5 to run the ASP.NET Dynamic Data Web Application.
Application
c. You will be redirected by default to the Default.aspx page of the ASP.NET
Dynamic Data Web SiteSite.
d. Click SalesOrderHeader table to see its data. You will notice that the boolean
OnlineOrderFlag field is rendered using a checkbox.
Page 22 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
- Details.aspx
Details.aspx: Displays the read-only details for a row in a table.
- Edit.aspx
Edit.aspx: Displays an edit view for a row in a table.
- Insert.aspx
Insert.aspx: Displays an insert view for a row in a table.
- List.aspx
List.aspx: Displays a list of rows from the database.
- ListDetails.aspx
ListDetails.aspx: Displays a list of rows from the databasee along with read-only
read
details for a selected row.
a. Create a Customer folder under the DynamicData\CustomPages
CustomPages folder. To do
this, in Solution Explorer, right-click DynamicData\CustomPages
CustomPages folder, point
to Add and select New Folder. Then enter Customer as the he folder’s name.
Note: The folder’s name must match the name of the table’s view that wants to be
customized.
b. Copy List.aspx under the DynamicData\PageTemplates folder to the newly
created DynamicData\CustomPages\Customer folder.
c. Delete the two code-behind files for List.aspx,, as you’re going to leverage the
code from the existing page template, and change only the HTML.
HTML
Page 23 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
d. Change the page title. Open up the newly copied ListDetails.aspx template and
append the text ““List” to its <h2> element’s content.
<h2><%= table.DisplayName %> List</h2>
e. Define which Customers table columns to display. To do this, switch to
ListDetails design view and find the GridView control used to display the table
data. Click the smart-tag glyph that appears on the side of the control
co to display
the GridView Tasks window. Click Edit Columns to open the Fields window.
Page 24 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
f. Uncheck the Auto-Generate fields option.
g. Specify the columns to display in the table view. To do this, select DynamicField
in the Available Fields list and click Add. Set the DataField value with the table
column name and the HeaderText to a descriptive name. E.g. Set “FirstName” as
the DataField and “First Name” as the HeaderText.
h. Repeat the previous steps for each of the following columns:
FirstName
LastName
CompanyName
SalesPerson
EmailAddress
Phone
Page 25 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Page 26 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Page 27 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Existing Item
Item. In the Add Existing Item dialog box browse to
AspNetDynamicData
AspNetDynamicData\Assets and select SemaphoreGreen.gif and
SemaphoreRed.gif
SemaphoreRed.gif. Click Add.
d. Indicate to the Dynamic Data framework you want to use the BooleanImage
custom control for the Boolean field instead of the default template. To do this,
open the SalesOrderHeader.cs file under the Model folder and add the following
code (shown in bold) within the SalesOrderHeaderMetadata class:
private class SalesOrderHeaderMetadata
{
...
[UIHint("BooleanImage")]
public object OnlineOrderFlag { get; set; }
}
Note: The UIHint attribute specifies what field template to use when a specific column
is rendered. The framework will look for the control in the
DynamicData/FieldTemplatess directory. If the data control is in edit mode it will
look for a control named with the “
“_Edit” suffix.
e. Add a CustomerMetadata class into the Customer partial class in order to
customize the EmailAdress property. To do this, add the following code shown in
bold within the Customer class.
[DisplayColumn("CompanyName", "CompanyName")]
public part
partial class Customer
{
private class CustomerMetadata
{
}
}
f. Associate the CustomerMetadata class with the Customer partial class by adding
a MetadataTypeAttribute to the Customer class.
[MetadataType(typeof(CustomerMetadata))]
Page 28 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
[DisplayColumn("CompanyName", "CompanyName")]
public partial class Customer
{
private class CustomerMetadata
{
}
}
g. Add metadata for the EmailAddress property to use the EmailAddress template.
To do this, create an EmailAddress property in the CustomerMetadata class and
apply the DataType attribute with the DataType.EmailAddress value to it.
[MetadataType(typeof(CustomerMetadata))]
[DisplayColumn("CompanyName", "CompanyName")]
public partial class Customer
{
private class CustomerMetadata
{
[DataType(DataType.EmailAddress)]
public object EmailAddress { get; set; }
}
}
Note: The DataType attribute specifies additional type information associated with a
data field. Dynamic Data will use it to decide which Template located in the
FieldTempaltes folder will be used to render the field.
Page 29 of 29