Av rating:
Total votes: 50
Total comments: 20


Gayani Devapriya
Dynamic Data Templates in ASP.NET 3.5
17 November 2008

Gayani gives an introduction to  Dynamic Data Templates in ASP.NET 3.5 and explains how one can save a great deal of time and effort when building data-driven web sites by using them

Contents

Introduction

Developers regularly waste (or should I say lose) huge amounts of their time when building up data-driven web applications by going through the same repetitive tasks each and every time. Whilst the database varies from one application to the next, the applications themselves share similar features which need to be duplicated, such as querying the database and presenting data. In a bid to help those developers reclaim their hours, Microsoft introduced the Dynamic Data Templates with the release of Visual Studio 2008.

At a high level, Dynamic Data Templates can be seen as a system to very quickly build up a User Interface linked with the relevant data model, immediately enabling you to perform CRUD  operations (Create, Read, Update, Delete) on the database using the specified data source. They provide a powerful method for building up these kinds of applications, and I’m going to focus on an overview of what Dynamic Data Templates actually are, and a few ways of customizing them to suit industry needs.

Creating a Dynamic Data Website

The first step in building your application is applying the Dynamic Data Website template to your ASP.NET application. This makes a set of folders available which contain pages, user controls and templates – everything you’ll need to make the magic happen, as we’ll see in a moment.

(This template uses the LINQ to SQL data model and LINQ datasource. To use the ADO.NET Entity data model you need to add the Dynamic Data Entities template instead. )

Secondly, to formulate the data layer of our ASP.NET application, you’ll need to add a data model (I’ve used AdventureWKS ) using the LINQ to SQL class. The AdventureWKS data model has the following class repres­ent­ations of tables from the Adventure Works database:

To map the templates onto the database, we need to register the data model and specify the routing technique by editing Global.asax as follows.

void Application_Start(object senderEventArgs e)
            
{
            RegisterRoutes
(RouteTable.Routes);
           
}

The RegisterRoutes method uses a MetaModel object to enable the Scaffolding framework, which is what makes the DDT so powerful. This MetaModel object allows the templates to dynamically create the URL patterms which process the CRUD requests. So, in addition to registering the data model, we’ll also need to specify the DataContext type and the ScaffoldAllTables property. This will ensure that the whole data model exhibits the Dynamic Data functionality.

public static void RegisterRoutes(RouteCollection routes)
            
{
            
MetaModel model = new MetaModel();
            
model.RegisterContext(typeof(AdventureWKSDataContext),
                
new ContextConfiguration() { ScaffoldAllTables = true }
            
);

            
routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
                
{
                    Constraints 
= new RouteValueDictionary(new { action "List|Details|Edit|Insert" }),
                    
Model model
                }
);
            
}

Lastly, we need to add a new Route to the routes collection by specifing the URL pattern and the model we just registered.

After these steps, we have a fully-functional application ready to run.

The elements of the data model are now linked, making the CRUD operations possible. It’s also important to appreciate that these relationships are automatically represented correctly, and the controls are all rendered appropriately according to field type. (e.g. Boolean values appear as checkboxes in edit mode).

Not only does this basic setup enable CRUD operations, it also uses foreign key relationships to provide filtering, sorting and paging operations. An easy example of this kind of functionality can be seen by following the ‘View ProductVendors’ link. The application also has customizable field validation functionality which can be seen in the Edit pages, and can be tweaked to control required fields, as well as the format of field content; I’ll come back to this a little later.

Underlying Mechanism

Use of URL Routing and Page Templates

Dynamic Data Templates use the ASP.NET Routing technique to construct URL patterns dynamically, using parameterized information to call appropriate templates and automatically populate them rather than relying on static content.  This centralizes the navigation logic and allows changes to be rapidly deployed globally across the application – all the better to save time with.

routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
                
{
                    Constraints 
= new RouteValueDictionary(new { action "List|Details|Edit|Insert" }),
                    
Model model
                }
);

In our example, to use templated pages for various operations, the DDT processes the requests with the URL pattern:  “{tablename} / {action}” . It maps a Tablename to the requested table in the data model while the action is mappd to a particular template in the Page Templates folder, which contains pages for each possible action. This way, it responds with a fully templated page based on the requested action.

Use of Meta data and Field Templates

DDTs read the Metadata of the data model at run time and identify the type of each field being used. Then, according to the look-up rules, the determine the most appropriate control to be loaded. These rules give priority to the control types described in the UIHint attribute, and without this the template will load a control based on the datatype. These controls are available under the TemplateFields folder, and a control is available for every field type, with a view mode as well an edit mode . In short, you want for nothing.

Extending Functionality

Adding Business Logic

Incorporating business logic into a Dynamic Data Website is the next stage, and there are a few easy techniques to do just that.

The data context we added earlier contains the Extensibility Method Definition for each class representation of the data model. These are methods that execute when controls change their statuses, and so are an ideal place to include the business logic. These classes, as well as the Extensibility Method definitions, are defined as partial; leaving room for customization by intrepid developers.

As an example, I’ll validate the Reorder Point against the SafetyStock Level in the Product class. To do that, I create a Product partial class and define some extensibility methods as follows.:

public partial class Product
            {
               
private short sStockLevel;
              
  public short StockLevel
                {
                    get { 
return sStockLevel}
                    set { sStockLevel 
value}
                }
                partial 
void OnSafetyStockLevelChanging(short value)
                
{
                    StockLevel 
value;
                
}
                partial 
void OnReorderPointChanging(short value)
                
{
                    
if (value StockLevel)
                   
{
                        
throw new ValidationException("Re-order Point exceeds the Safety Stock Level!");
                    
}
                }
            }

And voila, a validation exception is thrown when the ReorderPoint exceeds the SaftyStockLevel. As you can see, it’s a simple matter to keep the business logic separate from the data and presentation layers.

Changing the way fields render

It is essential that fields in the Dynamic Data Templates can be customized and rendered based on various industry needs. These alterations can range from just changing the format of a date to displaying a third party control in place of a default.

To show you just a few things that are possible, I’m going to implement these changes for the ProductReviews edit view:

  • Change the ReviewDate field to the ‘dd MM yyyy’ date format.
  • Validate the EmailAddress field using RegEx.
  • Validate the Rating field with a character length restriction of 1.
  • UnScaffold the ModifiedDate field.
  • Use a 3rd party control (FreeTextBox) for the Comments field.

One way of doing this is to edit the definition of the ProductReview class in AdventureWKS.designer.cs, but this will cause changes in the data model. In order to keep the data model unchanged, and to extend the ProductReview class’s functionality, the more appropriate approach is  to create a partial class specifying the customization, apply the MetadataType attribute to this class and specify its type as ProductReviewMetadata.

MetadataType sits in the System.ComponentModel.DataAnnotations namespace, which has a variety of attributes that can be used to customize field rendering.  Within the ProductReviewMetadata class the initialized properties are populated with the appropriate attributes as shown here:

[MetadataType(typeof(ProductReviewMetadata))]
            
public partial class ProductReview
            {
            }

            
public class ProductReviewMetadata
            {
                
public object ProductReviewID { getset}
                
public object ProductID { getset}
                
public object ReviewerName { getset}
                [DisplayFormat(DataFormatString = "{0: dd MM yyyy}")]
                
public object ReviewDate { getset}
                [RegularExpression(
@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid Email")]


                   public object EmailAddress { get; set; }
                   [Range(0, 2, ErrorMessage = "Invalid Rating")]
                   public object Rating { get; set; }
                   [UIHint("FreeTextBox")]
                   public object Comments { get; set; }
                   [Scaffold(false)]
                   public object ModifiedDate { get; set; }
                }

Just to give you a running commentary, what I’m doing here is:

  • Setting the DisplayFormat attribute in the ReviewDate property to display dates as ‘dd MM yyyy’.
  • Using the RegularExpression attribute to specify the validation expression for the EmailAddress property.
  • Using the Range attribute to specify the range on the Rating property.
  • Setting the UIHint attribute on Comments property to the name of the user control. I’m using the FreeTextBox 3rd party control as this non-default option.
  • Setting the Scaffold attribute to false on ModifiedDate to disable the scaffolding.

And these gloriously simple tweaks produce this:

As you can see, the ReviewDate field format has now changed and the ModifiedDate fields are hidden in the list view, and the 3rd party control and validation functions are all visible. Easy as that.

Dynamic Data Controls

Dynamic Data Templates provide very efficient mechanisms for binding data to templated, data-bound controls using DynamicControl, DynamicField Control and DynamicDataManager controls in the System.Web.DynamicData namespace.

DynamicDataManager is a control that must be included in a page to gain Dynamic Data Support. Both the DynamicControl and DynamicField controls render the appropriate control at run time, based on the field type and provide data validations based on the data model. And these controls can mostly be smoothly and easily brought into play when building custom pages.

DynamicField Control

The DynamicField control allows you to bind a data field (or data fields) when populating templated bind controls. The DataField property lets you specify the fields to be bound, and to show what I mean, I’ll create a custom look for the Adventure Works vendors page; the AutoGeneratedColums is set to false in the GridView control, and the fields to display are specified using DynamicField, as seen here:

asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource" AllowPaging="True"
           AllowSorting="True" CssClass="gridview" AlternatingRowStyle-CssClass="even" AutoGenerateColumns="false">
           <Columns>
              <asp:DynamicField DataField="Name"></asp:DynamicField>
              <asp:DynamicField DataField="CreditRating" DataFormatString="{0:2}" NullDisplayText="na"></asp:DynamicField>
              <asp:DynamicField DataField="ActiveFlag"></asp:DynamicField>
              <asp:DynamicField DataField="AccountNumber"></asp:DynamicField>


And here is what that will look like when we run the application:

Use of DynamicControl

In contrast to the DynamicField control, the DynamicControl lets you specify the display mode being used. For example, to provide inline editing in a templated data-bound control, such as a GridView, we specify one control in ItemTemplate and another in EditItemTemplate. Let’s use a DynamicControl instead. We’ll specify the field to bind in the DataField propety, and mode of display in the Mode property. The Mode property varies as ReadOnly, Edit and Insert.

    <asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource"
AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:DynamicControl ID="dcNameRo" DataField="Name" Mode="ReadOnly" runat="server">
                    </asp:DynamicControl>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DynamicControl ID="dcNameE" DataField="Name" Mode="Edit" runat="server">
                    </asp:DynamicControl>
                </EditItemTemplate>

            </asp:TemplateField>

It’s worth bearing in mind that both controls share some common features, such as DataFormatString (for specifying date formats), NullDisplayText (sets the default text for when field values are null) and ApplyFormatInEditMode (a bool value to indicate whether to apply formatting in the edit mode or not).

Conclusion

With a stabilized model and a well structured solution, the Dynamic Data Templates provide a quick and easy way of building up fully functional data-driven applications in minutes. Even better, you can extending DDTs to suit industry needs with minimal hassle. Unlike other RAD tools, Dynamic Data is much cleaner both in terms of the code and structure. It is simply an elegant way of building up a fully functional data driven application in minutes, and with its templates and routing systems, it provides more functionality with less code.



This article has been viewed 15660 times.
Gayani Devapriya

Author profile: Gayani Devapriya

A Software Engineer with more than 4 years experience in the software development industry. Have specialized on web application technologies and have experience developing many web applications for various clients and domains. Have a strong flair and interest on ASP.NET. Holds MCTS, MCPD, in .NET Framework 2.0 and Web application development and holds the Bachelor of IT from the University of Colombo, Sri Lanka. You can read the blog at http://dilrukshidevapriya.blogspot.com

Search for other articles by Gayani Devapriya

Rate this article:   Avg rating: from a total of 50 votes.


Poor

OK

Good

Great

Must read
 
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.


Subject: this is a great article which covers many features in dynamic data
Posted by: ryan martin (not signed in)
Posted on: Tuesday, November 18, 2008 at 1:50 PM
Message: Could you upload the demo project that accompanies this article for your readers to download.

Subject: Re:
Posted by: NVP (not signed in)
Posted on: Tuesday, November 18, 2008 at 11:17 PM
Message: Nice article
http://www.nisheethpandya.blogspot.com

Subject: Awesome
Posted by: Anonymous (not signed in)
Posted on: Tuesday, November 18, 2008 at 11:18 PM
Message: Awesome

<a href="http://www.nisheethpandya.blogspot.com">http://www.nisheethpandya.blogspot.com</a>

Subject: Code update
Posted by: Chris Massey (view profile)
Posted on: Thursday, November 20, 2008 at 10:00 AM
Message: The code in this article has been changed from screen-grabs to characters - hope you guys find it useful.

Subject: Video Tutorial about Dynamic Data
Posted by: ramil joaquin (not signed in)
Posted on: Friday, November 21, 2008 at 5:58 AM
Message: guys you can follow this link to watch the video tutorial about dynamic data http://developercontainer.blogspot.com/search/label/Dynamic%20Data

Subject: >
Posted by: Anonymous (not signed in)
Posted on: Friday, November 21, 2008 at 5:59 AM
Message: ;gt;

Subject: Web Services
Posted by: Anonymous (not signed in)
Posted on: Wednesday, November 26, 2008 at 4:59 AM
Message: Is it possible to use web services with this method?

Subject: Stored Procedures
Posted by: Jack the DBA (view profile)
Posted on: Wednesday, November 26, 2008 at 3:34 PM
Message: How would you use stored procedures with Dynamic Data?

Subject: Re: Web Services
Posted by: Gayani (not signed in)
Posted on: Thursday, November 27, 2008 at 11:59 AM
Message: Re: Is it possible to use web services with this method?

Yes you can use a webservice. But it depends on the purpose of it and where you want to use it.

Thx,
Gayani

Subject: Re: Stored Procedures
Posted by: Gayani (not signed in)
Posted on: Thursday, November 27, 2008 at 12:06 PM
Message: Re : How would you use stored procedures with Dynamic Data?

The Dynamic Data uses methods with in System.Web.DynamicData which contains almost all the methods defined to support the database activities. The built-in page templates in DDT uses these methods.
But apart from using the in built page templates, you can define your own custom pages and create your own data access classes, over there you can use the stored proceedures with the same DataContext.

Thx,
Gayani

Subject: More security stuff would be interesting..
Posted by: Peter Gfader (not signed in)
Posted on: Monday, December 01, 2008 at 6:41 AM
Message: Like how to restrict some users/roles from viewing/editing a table.

Subject: Re: More security stuff would be interesting..
Posted by: Gayani (not signed in)
Posted on: Monday, December 01, 2008 at 11:39 AM
Message: Re: Like how to restrict some users/roles from viewing/editing a table.

It is posible to implement the ASP.NET Role based security model in to the web application using the WAST (Web Site Administration Tool). To apply the access rules on to a particular table, it’s better to develop it as a custom page and give access rights to the particular folder (ex: Custom Pagers-> Vendor), for the required user/role.

Thx,
Gayani

Subject: MVC?
Posted by: Daniel Penrod (view profile)
Posted on: Wednesday, December 03, 2008 at 2:23 PM
Message: Is this Microsoft's way of implementing a type of the Model View Controller (MVC) Framework? It seems to me like the same idea. Am I wrong to think that?

Subject: its a boring article
Posted by: Anonymous (not signed in)
Posted on: Thursday, December 04, 2008 at 8:01 AM
Message: its a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring article

Subject: MAJID
Posted by: MAJID (view profile)
Posted on: Thursday, December 04, 2008 at 8:03 AM
Message: MY NAME IS MAJID ALI I LOVE YOU MY NAME IS MAJID ALI I LOVE YOU MY NAME IS MAJID ALI I LOVE YOU

Subject: Re: MVC?
Posted by: Gayani (not signed in)
Posted on: Saturday, December 06, 2008 at 11:19 AM
Message: Re: Is this Microsoft's way of implementing a type of the Model View Controller (MVC) Framework? It seems to me like the same idea. Am I wrong to think that?

Well, the Dynamic Data Templates, use a similar technique used in MVC Frameworks URL Routing system, so you can consider this as one such instance where a similar routing technique is used.

Thank you,
Gayani

Subject: gfgfgfgf
Posted by: Landing Page Templates (not signed in)
Posted on: Sunday, December 07, 2008 at 5:38 AM
Message: The Dynamic Data uses methods with in System.Web.DynamicData which contains almost all the methods defined to support the database activities.

Subject: Ho to selectively display one or more tables in the default.aspx page?
Posted by: piyush_varma (view profile)
Posted on: Friday, December 12, 2008 at 5:22 PM
Message: What do I need to modify to list only one table in a web page? I need to direct individual users to the selected table only.

Or how do I call to display individual table?

Thank you,

Piyush Varma

Subject: Ho to selectively display one or more tables in the default.aspx page?
Posted by: piyush_varma (view profile)
Posted on: Friday, December 12, 2008 at 6:55 PM
Message: What do I need to modify to list only one table in a web page? I need to direct individual users to the selected table only.

Or how do I call to display individual table?

Thank you,

Piyush Varma

Subject: Adding Page Templates
Posted by: klca (view profile)
Posted on: Friday, January 22, 2010 at 11:18 AM
Message: Dear Gayani Devapriya,

My name is Carlos Porras. I am from El Salvador.

Currently I am fcing the following problem:

I have been trying to customize an inventory system that I had alredy elaborated like 20 years ago in FoxPro. It works fine, doesn't really need any major change in its logic or business rules but unfortunately FoxPro is not web based so I am working in migrating it to ASP.Net/C#.

I decided to try using Dynamic Data but I have a problem in how to redirect URL properly as to use a single customized template page for all of my 52 "reference tables" such as: type of customer, type of account, type of product, type of address, and so on.

I know that if I create 52 different folders inside the Dynamic Data\Custom Folders I will get the job done but it seems quite embarrassing for me doing that if I know for sure that there must be a way of doing this by means uf using a single template instead of 52.

I also need to eliminate the "FilterRepeater" (currently I have just added the visible equals to false) because I will need to display a GridView by using a Session parameter (company_code) that I will be gathering from login time. In doing this I don't need the user to select any other company but his.

The only problem is that by setting that parameter to "false" you don't really avoid the program in building behind the scenes all of the foreign keys that are not going to be displayed anyway. That’s a waste of time and obviously of the server resources.

It's a shame that there is not enough "digestible" information about the Dynamic Data framework and is really hard trying to accomplish this without proper support from MS. (that's what I think: all of this should be easier)

Can you help me .... desperately .... PLEASE !!!!



 






recommended site pinvoke

PInvoke.net is a user-driven wiki which provides .NET developers with native method signatures, so they don't have to spend time writing them from scratch.




Has .NET Reflector Saved Your Bacon?
 We think Reflector is a fantastic tool, and we know you do too. We'd love to hear about the times... Read more...

The Managed Heap
 Because Red-Gate's .NET team works closely with the users of their products in order to try to fit the... Read more...

Using Three Flavors of LINQ To Populate a TreeView
 LINQ is a valuable technology. LINQ to XML, LINQ to Objects and LINQ to XSD, in particular, can save... Read more...

How to build a Query Template Explorer
 Having introduced his cross-platform Query Template solution, Michael now gives us the technical... Read more...

How to Create Event Receivers for Windows SharePoint Services 3.0
 You'll be surprised how often that you'll use event receivers instead of Workflow in order to implement... Read more...

A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Web Parts in ASP.NET 2.0
 Most Web Parts implementations allow users to create a single portal page where they can personalize... Read more...

Configuring Forms Authentication in SharePoint 2007
 Damon Armstrong provides a step-by-step guide to the processes, quirks and pitfalls of setting up... Read more...

Over 150,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.

Join Simple Talk