My first channel 9 video!

Wow, I haven't blogged in a while...but that will end soon. Watch me talk about the QueryExtender control. It's a new control we added in ASP.NET 4.0 to make Linq queries even simpler. The new control works with LinqDataSource and EntityDataSource. We also built all of the new DynamicData filters on top of this new control.

Check it out here
Posted by davidfowl with 4 comment(s)
Filed under:

Dynamic Data in Regular Websites/Web Applications

Today I'm excited to share that we've released DynamicData Preview 4 on codeplex. Check out the latest bits here.

This release is particularly interesting not only for people that have been using Dynamic Data for a while now, but anyone that has an existing application today who wants to use some of the niceties Dynamic Data offers without having to take all the junk associated. Take a look at the SimpleDynamicData project for examples.

Existing Sites

Here are 2 good reasons to use Dynamic Data:

  • Rich model validation
  • Rich templating support via FieldTemplates  

If you've ever written a data driven app in webforms using our data controls, you would have realized that we are lacking a lot when it comes to validation. You can enable all of this goodness with a magic extension method.

protected void Page_Init() {
    GridView1.EnableDynamicData(your type here);
}

Note: The method requires that you pass in the type that may have annotations in order for us to read Metadata. If you're not familiar with the way annotations work in Dynamic Data then watch the videos here.

This method call enables DynamicControl/DynamicField to work within any of the data controls which makes use of FieldTemplates, and enables the rich validation support.

Making it work

So we know about this magic method call and somehow calling it with a type makes it all just work. Let's walk through an example of how we would use this. Here is my model:

public class Student {
    [Required]
    [Range(0, 100)]
    public int Age { get; set; }
 
    [Range(0.0, 4.0)]
    public double GPA { get; set; }
 
    [Required]
    public string FirstName { get; set; }
 
    [Required]
    public string LastName { get; set; }
 
    [DisplayFormat(DataFormatString = "{0:d/M/yyyy}")]
    public DateTime BirthDate { get; set; }
}

This is the type we are going to use for metadata. Using the attributes from System.ComponentModel.DataAnnotations we can add useful annotations to our model that will be used for validation and display formatting. Adding these attributes allows Dynamic Data to enable the appropriate validator. i.e RangeValidator, RequiredFieldValidator etc.

Now we're going to enable this on our GridView using the same method call as above in conjunction with an ObjectDataSource to complete our application:

protected void Page_Init() {
    GridView1.EnableDynamicData(typeof(Student));            
}

Markup

<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" AutoGenerateEditButton="true">        
    </asp:GridView>
    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
        DataObjectTypeName="Student" DeleteMethod="DeleteStudent" 
        InsertMethod="InsertStudent" SelectMethod="GetStudents" 
        TypeName="StudentsRepository" UpdateMethod="UpdateStudent">
    </asp:ObjectDataSource>

Note: Dynamic Data takes care of the Metadata not the data. You still need databind the data control against some data source/data source control.

Here are the results when we are editing:

As you can see, the attributes we specified on our Student class directly affect the grid and validation is enabled.

There's more cool stuff to talk about but I'll mention those in upcoming posts. For now, download the preview and read up on Dynamic Data!

Posted by davidfowl with 13 comment(s)

External ITemplates and Hierarchical Databinding

Ever wish you could declare a template outside of the control you were defining the template for? We always get requests to have FormView's InsertItem template fall back on the EditItemTemplate and vice versa. That would be easy if we could do what was mentioned above.

Consider:

<asp:FormView ID="myFormView" runat="server" DefaultMode="Edit" 
    EditItemTemplate="editTemplate" 
    InsertItemTemplate="editTemplate">
</asp:FormView>
 
<asp:Template runat="server" ID="editTemplate">
    Name : <asp:TextBox runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
    Age : <asp:TextBox runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
</asp:Template>

Then you could do things like hierarchical databinding pretty easily; just define the template in terms of itself. Today, properties typed as ITemplate are treated specially by the ASP.NET parser, and what is written above will not work.

How would you do this with what asp.net offers now? Well check out this sample:

<cc:SpecialRepeater runat="server" ItemTemplateID="folderTemplate" DataSource='<%# GetDirectories() %>' />        
<cc:Template runat="server" ID="folderTemplate">
    <ItemTemplate>
        <ul>
            <li>
                <%# Eval("Name") %>
                <cc:SpecialRepeater runat="server" DataSource='<%# GetDirectories((string)Eval("FullName")) %>' ItemTemplateID="folderTemplate" />
                <ul>
                    <cc:SpecialRepeater runat="server" DataSource='<%# GetFiles((string)Eval("FullName")) %>' ItemTemplateID="fileTemplate" />
                </ul>
            </li>
        </ul>
    </ItemTemplate>
</cc:Template>
 
<cc:Template runat="server" ID="fileTemplate">
    <ItemTemplate>
        <li> <%# Eval("Name") %>
        </li>
    </ItemTemplate>
</cc:Template>

We have a SpecialRepeater that understands how to hookup template properties through their ID (it's just FindControl) and a Template control that defines our file template and folder template. We define the folder template in terms of itself. Can you think of any more uses for something like this?

Get the code here.

What do you think?

Posted by davidfowl with 6 comment(s)

Invalid postback or callback argument

I'm sure many of you have seen this error message when developing your web application:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

I'm going to discuss this in the context of the data controls. This happens when a control that isn't registered for event validation causes a postback, but surely that can't be the case.. right?

Let's look at a small repro:

Markup:

<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button runat="server" Text="Button" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code behind:

public partial class _Default : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        GridView1.DataSource = Enumerable.Range(0, 5);
        GridView1.DataBind();
    }
}

Now click on the button and see the dreaded error message. Why does this happen? EventValidation was added in ASP.NET to ensure that controls causing the postback came from the same page being rendered. Take a look at __EVENTVALIDATION hidden field on the page. It is a serialized version of all of the controls registered for postbacks(read more here). You might be wondering how they got in there and why is the button inside of a GridView a special case. It's not a special case, in fact, Button registers itself with the current page.

The reason this happens is because we rebind the data control in Page_Load every time which means that we will lose all of the posted data and viewstate. As a result, the ID of the button is different and when the event is validated there will be no matching unique id and hence event validation will fail. We are acutally raising an event for a button that is no longer in the control tree.

You can work around this by wrapping that code in if (!IsPostBack). This is a good proof of why you should use DataSource controls.

Hope this helps

Posted by davidfowl with 9 comment(s)
Filed under: ,

A new way to DataBind()

The Problem 

I've been thinking alot recently about the problems with data binding (and they're alot). There are some patterns that play well with ASP.NET (and are repeated everywhere) and some that don't quite fit the model. One of those patterns that don't mesh well is, setting the DataSource property of any of the DataControls. Before ASP.NET 2.0 and DataSource controls we'd have to set the DataSource property and manually call DataBind.

What's wrong with this you may ask? When are you supposed to DataBind? Page_Load ? Page_Init? Page_PreRender? I'm sure anyone that has had to manually data bind has had the problem of figuring out which code goes in and out of the IsPostBack block.

Whats the solution?

I'm looking at an alternative approach to this problem. Event handlers are nice because we all feel confident that the author of the event knows when that event should be raised. No need to figure out the postback logic because the control author already thought about that. All you have to worry about is handling the event.

I propose a new hypothetical event OnDataRetrieveing, that would be on all DataControls in conjunction with a new flag AutoBind to enable it.

Let's take a look at a sample implementation of a derived GridView control that has this new behavior. First the markup:

<custom:AutoGridView 
    OnDataRetrieving="OnDataRetrieving"
    OnPageIndexChanging="OnGridViewPageIndexChanging"
    OnRowEditing="OnGridViewRowEditing"
    OnRowCancelingEdit="OnGridViewRowCancelingEdit"
    AllowPaging="true" 
    runat="server" 
    ID="GridView1" 
    AutoGenerateEditButton="true"
    AutoBind="true">
</custom:AutoGridView>

Looks pretty similar to the regular GridView besides the AutoBind="true" flag and OnDataRetrieving event.

And the code behind

protected void OnGridViewRowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
    GridView1.EditIndex = -1;
}
 
protected void OnGridViewPageIndexChanging(object sender, GridViewPageEventArgs e) {
    GridView1.PageIndex = e.NewPageIndex;
}
 
protected void OnGridViewRowEditing(object sender, GridViewEditEventArgs e) {
    GridView1.EditIndex = e.NewEditIndex;
}
 
protected void OnDataRetrieving(object sender, DataBindingEventArgs e) {
    NorthwindDataContext db = new NorthwindDataContext();
    e.DataSource = db.Products;
}

We write code as we normally would if we'd been binding manually, but instead, we assign our data to the DataSource property in the DataBindingEventArgs (Which gets called at the "right" time).

So what is the right time to Databind and why does this control do it better than you? I'm not sure :) but let's look at the source of this control.

public override object DataSource {
    get {
        return base.DataSource;
    }
    set {
        if (!_settingDataSource && AutoBind) {
            throw new InvalidOperationException("When AutoBind is enabled, setting the DataSource property explicitly is not allowed.");
        }
        base.DataSource = value;
    }
}
 
protected override void PerformSelect() {
    if (AutoBind) {                
        DataBindingEventArgs args = new DataBindingEventArgs();
        OnDataRetrieving(args); 
        _settingDataSource = true;
        DataSource = args.DataSource;
        _settingDataSource = false;
    }
    base.PerformSelect();
}
 
protected override void EnsureDataBound() {
    if (RequiresDataBinding && (AutoBind || IsBoundUsingDataSourceID)) {
        DataBind();
    }
}

The most interesting method is EnsureDataBound. This method is called from PreRender and the original condition for making the control DataBind is:

if (this.RequiresDataBinding && ((this.DataSourceID.Length > 0) || this._requiresBindToNull)) {
    this.DataBind();
    this._requiresBindToNull = false;
}

In the case of manually binding this would never be called unless _requiresBindToNull is true. Our AutoGridView control changes this logic by detecting the AutoBind flag and continues to data bind as usual in PreRender.

If you interested in when the event gets called you can put some break points in the control's code. What do you think about this alternative?

Here is a link to the source.

Posted by davidfowl with 12 comment(s)

Client side devevelopment in ASP.NET

We ASP.NET developers know how much of a pain it is writing javascript in any app we have today because of naming container madness! You've probably done something like this:

function DoSomeThingCool() {
    var textBox = document.getElementById('ct100_contentplaceholder1_TextBox1');
}

or something not so hardcoded

function DoSomeThingCool() {
    var textBox = document.getElementById('<%= TextBox1.ClientID %>');
}

Matthew Osborn, QA on the ASP.NET team has a great post on a new ASP.NET 4.0 feature that gives developers more control over how ClientIDs are generated.

Posted by davidfowl with 13 comment(s)
Filed under: , ,

Follow me on twitter!

I've finally got sucked into twitter after avoiding it for many months. Check me out:

http://twitter.com/davidfowl/

Since my name is so common it really annoys me when I sign up for any new service because I have to get accept some partially mangled version of my name (i.e. davidfowl).

Anyways, stay tuned!

Posted by davidfowl with no comments
Filed under: ,

Dynamic ListView LayoutTemplate

There are times when you want to let the user change layout dynamically. You can use css to do this but lets look at what the ListView control offers. To get started with the ListView you need a LayoutTemplate and ItemTemplate.

<asp:ListView runat="server" ID="listView">       

    <LayoutTemplate>

        <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>

    </LayoutTemplate>

    <ItemTemplate>

        <%# Eval("CategoryName") %>

    </ItemTemplate>

</asp:ListView>

The ListView replaces the control with ID="itemPlaceholder" with the zero or more instances of the Selected/Alternating/ItemTemplate.

There is a method on TemplateControl (LoadTemplate) which allows users to dynamically load a user control as a ITemplate. Lets use this to load our LayoutTemplate from a user control.

User Control:


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FlowLayout.ascx.cs" Inherits="ListViewLayouts.FlowLayout" %>

 

<div id="flow">

    <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>

</div>

Code Behind:

protected void Page_Init(object sender, EventArgs e) {

    listView.LayoutTemplate = LoadTemplate("~/ListViewLayouts/FlowLayout.ascx");

}

When we run the page we get the following exception:

An item placeholder must be specified on ListView 'listView'. Specify an item placeholder by setting a control's ID property to "itemPlaceholder". The item placeholder control must also specify runat="server".

The problem here is that user controls are naming containers and when the ListView internally tries to find the control with ID="itemPlaceholder" it fails. So what is the id of the itemPlaceholder? We'll we could start guessing that it might be something like ctl001$itemPlaceholder, but that doesn't seem like a good solution. Instead we can create our own template that will allow us to specify the ID of the user control so that the itemPlaceholderID is more predictable.

public class CustomTemplate : ITemplate {

    private string _virtualPath;

    private string _controlID;

 

    public CustomTemplate(string virtualPath, string controlID) {

        _virtualPath = virtualPath;

        _controlID = controlID;

    }

 

    public void InstantiateIn(Control container) {           

        Control control = (Control)BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(Control));

        control.ID = _controlID;

        container.Controls.Add(control);

    }

}


This template gives us the opportunity to specify a controlID for the user control we are going to load. Now we instantiate a new CustomTemplate and specify the control ID as well as path to the user control.

protected void Page_Load(object sender, EventArgs e) {

    listView.LayoutTemplate = new CustomTemplate("~/ListViewLayouts/FlowLayout.ascx", "flowLayout");           

}

Don't forget to set the ItemPlaceHolderID proprety on the ListView.

<asp:ListView runat="server" ID="listView" ItemPlaceholderID="flowLayout$itemPlaceholder">

        <ItemTemplate>

            <%# Eval("CategoryName") %>

        </ItemTemplate>

</asp:ListView>

Now we can load the LayoutTemplate at runtime.

Posted by davidfowl with 3 comment(s)

AutoFieldGenerators

In 3.5 SP1 we added new properties to GridView and DetailsView which allows the page developer to change the way AutoGenerateColumns creates its columns. This feature is well know in Dynamic Data, but it is not tied to this technology. Dynamic Data takes advantage of this by looking at the meta data that users set on properties to generate columns.

You too can roll your own IAutoFieldGenerator. Lets look at the interface:

public interface IAutoFieldGenerator {

    ICollection GenerateFields(Control control);

}

The interface itself is pretty weird but it gets the job done. GenerateFields takes the control that we're generating the fields for, and expects to get some ICollection of stuff back. If we had the chance to redo this interface we'd probaby rewrite it to be like this:

public interface IAutoFieldGenerator {

    IEnumerable<DataControlField> GenerateFields(Control control);

}

Now it's clear what we expect to get back, but thats besides the point. Lets implement our own.

public class ColumnGenerator : IAutoFieldGenerator {

private IEnumerable<string> _columns;

public ColumnGenerator(IEnumerable<string> columns) {

    _columns = columns ?? Enumerable.Empty<string>();

}

 

public ICollection GenerateFields(Control control) {

    return (from column in _columns

            select new BoundField {

                SortExpression = column,

                HeaderText = column,

                DataField = column

            }).ToArray();

    }

}


We're going to pass a set of column names to our generator that just creates bound fields with the column's name. To make use of our new generator we can just set it like this:

GridView

gridView1.ColumnsGenerator = new ColumnGenerator(Columns);

DetailsView

detailsView1.RowsGenerator = new ColumnGenerator(Columns);

You can do alot of cool things with these generators. Some things I can think of off the top of my head:

  • Hide/Show columns dynamically based on metadata (like what we do with dynamic data)
  • Hide/Show columns based on permissions
  • Create a configurable UI that allows users to hide or show columns based on their preferences.

I've written a sample that allows you to hide or show columns based on a selectable UI. You can download it here:

AutoFieldGenerator.zip

Here is a screen shot of it running.

Posted by davidfowl with 6 comment(s)

How <%# Bind %> Works

In my last post I spoke about 2-way databinding and how it can be used to extract values from control properties. How does this all work? Lets take a look at a page with 2-way databinding:

<asp:LinqDataSource ID="productsSource"

    runat="server"

    ContextTypeName="FowlerSamples.NorthwindDataContext"

    EnableDelete="True"

    EnableInsert="True"

    EnableUpdate="True" TableName="Products">

</asp:LinqDataSource>       

<asp:GridView ID="products"

    DataKeyNames="ProductID,CategoryID"

    AutoGenerateColumns="False"

    runat="server" DataSourceID="productsSource">

    <Columns>

        <asp:CommandField ShowEditButton="True" />               

        <asp:BoundField DataField="ProductName" />

        <asp:TemplateField>

            <EditItemTemplate>

                <asp:LinqDataSource

                    ID="categoriesSource"

                    runat="server"

                    ContextTypeName="FowlerSamples.NorthwindDataContext"

                    TableName="Categories" AutoGenerateWhereClause="true">

                </asp:LinqDataSource>

                <asp:DropDownList

                    runat="server"

                    ID="categories"

                    DataSourceID="categoriesSource"

                    DataTextField="CategoryName"

                    DataValueField="CategoryID"

                    SelectedValue='<%# Bind("CategoryID") %>'>                           

                </asp:DropDownList>                       

            </EditItemTemplate>                   

        </asp:TemplateField>

    </Columns>

</asp:GridView>

 In the above example, the GridView has a template field with an EditItemTemplate that has a DropDownList that is 2-way databound. We're going to introduce a small error in the page in order to see what the generated code looks like:

<EditItemTemplate>

     <asp:LinqDataSource

         ID="categoriesSource"

         runat="server"

         ContextTypeName="FowlerSamples.NorthwindDataContext"

         TableName="Categories" AutoGenerateWhereClause="true">

     </asp:LinqDataSource>

     <asp:DropDownList

        runat="server"

        ID="categories"

        DataSourceID="categoriesSource"

        DataTextField="CategoryName"

        DataValueField="CategoryID"

        SelectedValue='<%# Bind("CategoryID") %>'>                           

    </asp:DropDownList>

    <%# Eval(3) %>

</EditItemTemplate>


When we try to run this page we'll get a compile error and the famous ASP.NET YSOD(Yellow Screen of Death):



Click on Show Complete Compilation Source, if your curious about how ASP.NET converts your the markup to code.

When examining the source, we see a rather interesting method:

[System.Diagnostics.DebuggerNonUserCodeAttribute()]

public System.Collections.Specialized.IOrderedDictionary @__ExtractValues__control8(System.Web.UI.Control @__container) {

    System.Collections.Specialized.OrderedDictionary @__table;

    System.Web.UI.WebControls.DropDownList categories;

 

    categories = ((System.Web.UI.WebControls.DropDownList)(@__container.FindControl("categories")));

 

    @__table = new System.Collections.Specialized.OrderedDictionary();

 

    if ((categories != null)) {

        @__table["CategoryID"] = categories.SelectedValue;

    }

 

    return @__table;

}


As you can see in the above method, an OrderedDictionary is created and the SelectedValue property of the DropDownList is pushed into the "CategoryID" field. But how does this get all the way to the data control? Each control has a BuildControl method associated with it, if we examine the BuildControl method for the TemplateField it becomes a bit more clear how things get hooked up.

 

[System.Diagnostics.DebuggerNonUserCodeAttribute()]

private global::System.Web.UI.WebControls.TemplateField @__BuildControl__control7() {

    global::System.Web.UI.WebControls.TemplateField @__ctrl;

 

    @__ctrl = new global::System.Web.UI.WebControls.TemplateField();

 

    @__ctrl.EditItemTemplate = new System.Web.UI.CompiledBindableTemplateBuilder(new System.Web.UI.BuildTemplateMethod(this.@__BuildControl__control8), new System.Web.UI.ExtractTemplateValuesMethod(this.@__ExtractValues__control8));

 

    return @__ctrl;

}

The EditItemTemplate property is of type ITemplate. CompiledBindableTemplate implements both ITemplate and IBindableTempalte.

public interface IBindableTemplate : ITemplate {           

    IOrderedDictionary ExtractValues(Control container);

}

It's slowly coming together. So lets put together what we're learnt so far:

  1. Code Gen creates ExtractValues method that returns the dictionary of values for each ITemplate that has a Bind expression.
  2. The BuildControl method for the ITemplate's container (TemplateField in this case) assigns a new CompiledBindableTemplate to an ITemplate (EditItemTemplate in this case)
  3. CompiledBindableTemplate implements IBindableTemplate, which has a method, ExtractValues which returns the dictionary given a container.

It almost all makes sense now. Each data control uses this mechanism to extract values from template fields with 2-way databinding expressions.
What can you do with your new found knowledge?

<asp:FormView

    runat="server"

    ID="formView"

    DefaultMode="Edit">

    <EditItemTemplate>

        <asp:TextBox ID="textBox" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>

        <asp:TextBox ID="textBox1" runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>

        <asp:Button runat="server" ID="updateButton" CommandName="Update" Text="Update" />

    </EditItemTemplate>

</asp:FormView>


And the code behind:

 

class Person {

    public string Name { get; set; }

    public int Age { get; set; }

}

 

protected void Page_Load() {

    formView.ItemUpdating += formView_ItemUpdating;

    if (!IsPostBack) {

        formView.DataSource = new Person[] { new Person { Name = "David", Age = 22 } };

        formView.DataBind();

    }

}

 

protected void formView_ItemUpdating(object sender, FormViewUpdateEventArgs e) {

    IBindableTemplate template = formView.EditItemTemplate as IBindableTemplate;

    if (template != null) {

        IOrderedDictionary values = template.ExtractValues(formView);

        Response.Write(values["Name"]);

        Response.Write(values["Age"]);

    }

}


How cool is that? :)
Posted by davidfowl with 2 comment(s)
More Posts Next page »