Showing posts with label Cascading Filters. Show all posts
Showing posts with label Cascading Filters. Show all posts

Sunday, 6 June 2010

Part 3 – A Cascading Hierarchical Field Template & Filter for Dynamic Data

This would have been the final part of the series of articles, however I realised that we will need a final article that covers the more complex action of the CascadingHierarchicalFilter, this where at each level of selection we filter the list.

Cascading Hierarchical Filter

Figure 1 – Cascading Hierarchical Filter.

e.g. in Figure 1 the CascadingHierarchicalFilter (the basic version) no selection occurs until we select a value from the final list control, however in the complex CascadingHierarchicalFilter we will filter at each level and so we will hold that over until we have completed the basic version of the CascadingHierarchicalFilter.

And so to the basic version, first we will need a starting place so copy the ForeignKey filter and rename it to CascadingHierarchical and the class name to CascadingHierarchicalFilter. Next we remove the content of the aspx page so it looks like Listing 1.

<%@ Control 
    Language="C#" 
    CodeBehind="CascadeHierarchical.ascx.cs" 
    Inherits="CascadeHierarchicalFieldTemplate.CascadeHierarchicalFilter" %>

Listing 1 – CascadingHierarchical.aspx page

Then we start on the code behind by adding our member variables, adjusting the two properties and replacing the default Page_Init with ours, which is very similar to the Edit templates Page_Init see Listing 2.

#region member variables
private const string NullValueString = "[null]";
// hold the current data context to access the model
private object context;
// hold the list of filters
private SortedList<int, HierachicalListControl> filters = new SortedList<int, HierachicalListControl>();
// hold the attribute
private CascadeHierarchicalAttribute cascadeHierarchicalAttribute;
#endregion

private new MetaForeignKeyColumn Column
{
    get { return (MetaForeignKeyColumn)base.Column; }
}

public override Control FilterControl
{
    get
    {
        if (filters[0] != null && filters[0].ListControl != null)
            return filters[0].ListControl;
        else
            return null;
    }
}

protected void Page_Init(object sender, EventArgs e)
{
    //if (!Column.IsRequired)
    // check we have a cascade hierarchical attribute if not throw error
    cascadeHierarchicalAttribute = Column.GetAttribute<CascadeHierarchicalAttribute>();
    if (cascadeHierarchicalAttribute == null)
        throw new InvalidOperationException("Was expecting a CascadeFilterAttribute.");

    // check we have correct column type if not throw error
    if (!(Column is MetaForeignKeyColumn))
        throw new InvalidOperationException(String.Format("Column {0} must be a foreign key column navigation property", Column.Name));

    // get current context
    context = Column.Table.CreateContext();

    // get hierarchical cascade columns
    var parentColumns = new SortedList<int, String>();
    for (int i = 0; i < cascadeHierarchicalAttribute.Parameters.Length; i++)
        parentColumns.Add(i, cascadeHierarchicalAttribute.Parameters[i]);

    // add extra column to represent this column itself
    parentColumns.Add(cascadeHierarchicalAttribute.Parameters.Length, String.Empty);

    //get current column into a local variable
    MetaForeignKeyColumn currentColumn = Column;

    // setup list of filter definitions
    for (int i = 0; i < parentColumns.Count; i++)
    {
        // get parent column name
        var parentColumnName = parentColumns[i];

        // create dropdown list
        var ddl = new DropDownList()
        {
            ID = String.Format("ListControl{0}", i),
            Enabled = false,
            AutoPostBack = true
        };

        // create filter
        var filter = new HierachicalListControl(ddl) { Column = currentColumn };

        // check for last parent filter
        if (!String.IsNullOrEmpty(parentColumnName))
        {
            // set parent column from parent table
            filter.ParentColumn = (MetaForeignKeyColumn)currentColumn.ParentTable.GetColumn(parentColumnName);

            // set current column to parent column
            currentColumn = filter.ParentColumn;
        }
        else
        {
            // this is the last parent and has
            // no parent itself so set to null
            filter.ParentColumn = null;
            currentColumn = null;
        }
        // add filter to list of filters
        filters.Add(i, filter);
    }

    // add dropdown list to page in correct order 2, 1, 0
    // last parent, parent<N>, child
    for (int i = parentColumns.Count - 1; i >= 0; i--)
    {
        // setup dropdown list
        filters[i].ListControl.Items.Clear();
        filters[i].ListControl.Items.Add(new ListItem("------", String.Empty));

        // add parent list controls event handler
        if (i > 0)
            filters[i].ListControl.SelectedIndexChanged += ListControls_SelectedIndexChanged;
        else
            filters[i].ListControl.SelectedIndexChanged += ListControl0_SelectedIndexChanged;

        // add control to place holder
        this.Controls.Add(filters[i].ListControl);
    }

    if (DefaultValue != null)
        PopulateAllListControls(DefaultValue);
    else
    {
        // fill last parent filter
        var lastParentIndex = filters.Count - 1;
        var parentTable = filters[lastParentIndex].Column.ParentTable;
        var parentQuery = parentTable.GetQuery(context);

        // set next descendant list control
        PopulateListControl(lastParentIndex, parentQuery);
    }
}

Listing 2 – Member variables and Page_Init

Now we add the following Listings 3 & 4 these are virtually the same as from the Edit template and so I am thinking in the next revision they may all be removed to the class library.

/// <summary>
/// Sets the default values.
/// </summary>
/// <param name="fieldValue">The value.</param>
private void PopulateAllListControls(object fieldValue)
{
    var displayStrings = new SortedList<int, String>();

    #region Get list of propert values
    // get property values
    var propertyValues = new SortedList<int, Object>();
    propertyValues.Add(0, fieldValue);
    for (int i = 0; i < filters.Count - 1; i++)
    {
        var parentName = filters[i].ParentColumn.Name;
        object pv = propertyValues[i].GetPropertyValue(parentName);
        propertyValues.Add(i + 1, pv);
    }
    #endregion

    // stating at the first filter and work way up to the last filter
    for (int i = 0; i < filters.Count; i++)
    {
        var parentTable = filters[i].Column.ParentTable;
        var parentQuery = parentTable.GetQuery(context);
        IQueryable listItemsQuery;
        if (i == cascadeHierarchicalAttribute.Parameters.Length)
        {
            listItemsQuery = parentQuery.GetQueryOrdered(parentTable);
        }
        else
        {
            var pcol = filters[i + 1].Column;
            var selectedValue = filters[i].ParentColumn.GetForeignKeyString(propertyValues[i]);
            listItemsQuery = parentQuery.GetQueryFilteredFkColumn(pcol, selectedValue);
        }

        // set next descendant list control
        PopulateListControl(i, listItemsQuery);

        // set initial values
        var selectedValueString = filters[i].Column.Table.GetPrimaryKeyString(propertyValues[i]);
        ListItem item = filters[i].ListControl.Items.FindByValue(selectedValueString);
        if (item != null)
            filters[i].ListControl.SelectedValue = selectedValueString;
    }
}

Listing 3 – PopulateAllListControls

/// <summary>
/// Handles the SelectedIndexChanged event of the parentListControls control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">
/// The <see cref="System.EventArgs"/> instance containing the event data.
/// </param>
/// <summary>
/// Setups the parent list control.
/// </summary>
/// <param name="table">The table.</param>
/// <param name="filterIndex">The parent id.</param>
/// <param name="items">The items.</param>
public void PopulateListControl(int filterIndex, IQueryable items)
{
    // clear the list controls list property
    filters[filterIndex].ListControl.Items.Clear();
    // enable list control
    filters[filterIndex].ListControl.Enabled = true;

    // add unselected value showing the column name
    // [Styles]
    filters[filterIndex].ListControl.Items.Add(
        new ListItem(String.Format("[{0}]",
            filters[filterIndex].Column.DisplayName), NullValueString));

    foreach (var row in items)
    {
        // populate each item with the display string and key value
        filters[filterIndex].ListControl.Items.Add(
            new ListItem(filters[filterIndex].Column.ParentTable.GetDisplayString(row),
            filters[filterIndex].Column.ParentTable.GetPrimaryKeyString(row)));
    }
}

/// <summary>
/// Resets all descendant list controls.
/// </summary>
/// <param name="startFrom">The start from.</param>
private void ResetAllDescendantListControls(int startFrom)
{
    for (int i = startFrom - 1; i >= 0; i--)
    {
        filters[i].ListControl.Items.Clear();
        filters[i].ListControl.Items.Add(new ListItem("----", String.Empty));
        filters[i].ListControl.Enabled = false;
    }
}

Listing 4 – PopulateListControl and ResetAllDescendantListControls

Listing 5 is again virtually the same as the Edit templates but I kept it separate as it is an event handler and may make more sense to keep it in the template.

/// <summary>
/// Handles the SelectedIndexChanged event for each List control, 
/// and populates the next list control in the hierarchy.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">
/// The <see cref="System.EventArgs"/> instance containing the event data.
/// </param>
void ListControls_SelectedIndexChanged(object sender, EventArgs e)
{
    // get list control
    var listControl = (ListControl)sender;

    // get the sending list controls id as an int
    var id = ((Control)sender).ID;

    // use regular expression to find list control index
    var regEx = new Regex(@"\d+");
    var parentIndex = int.Parse(regEx.Match(id).Value);

    if (listControl.SelectedValue != NullValueString)
    {
        if (parentIndex > 0)
        {
            // set child index
            var childIndex = parentIndex - 1;

            // get parent table
            var parentTable = filters[childIndex].Column.ParentTable;

            // get query from table
            var query = parentTable.GetQuery(context);

            // get items for list control
            var itemQuery = query.GetQueryFilteredFkColumn(
                filters[parentIndex].Column,
                listControl.SelectedValue);

            // populate list control
            PopulateListControl(childIndex, itemQuery);

            // reset all descendant list controls
            ResetAllDescendantListControls(childIndex);
        }
    }
    else
    {
        // reset all descendant list controls
        ResetAllDescendantListControls(parentIndex);
    }
}

Listing 5 – ListControls_SelectedIndexChanged

Next we replace the DropDownList1_SelectedIndexChanged with ListControl0_SelectedIndexChanged Listing 6 really only a name change to make the code read clearly.

protected void ListControl0_SelectedIndexChanged(object sender, EventArgs e)
{
    OnFilterChanged();
}

Listing 6 – ListControl0_SelectedIndexChanged

Finally we need to change the GetQueryable method to replace DropDownList1 with filters[0].ListControl.

Download

Happy coding

Note: With a few changes around the last two listings you could adapt this to either the old Dynamic Data Futures VS2008 SP1 RTM filters on CodePlex or Josh Heyes’s Dynamic Data Filtering.

Tuesday, 25 May 2010

Part 1 – A Cascading Hierarchical Field Template & Filter for Dynamic Data

In the past I have done several articles on Cascading field templates and filters, these articles will cover a single cascading hierarchical field template that filters by it's parent fields without having to have those tables related directly related to the columns table.

ScreenShot258

Figure 1 – Old Cascading Relationships

So in the diagram above to have cascade from Builder->Developer->HouseType on the plot you must have an foreign key relationship with each of the Parent tables on the Plots tables. In the above Requires Plots table we have an FK relationship with Builder, Developer and HouseType to get the cascade to work.

There was however a Cascade filter in the old Dynamic Data Futures VS2008 SP1 RTM project on Codeplex. This did offered the hope of something better, which in this article we will build. First the field template then with a few changes a Filter.

So the aim of this sample if to have a single foreign key field on the table and have the selection cascade over each parent field.

The Attribute

We will need a simple attribute for this to pass in the list of parent columns

Cascade Relationship EF

Figure 2 – New Cascading Relationships

So we will need to pass the field template a list of parent foreign key navigation properties like this:

Cascade Relationship EF attributes

Figure 3 – Foreign Key columns

In Figure 3 the normal foreign key column Product already in known to use but we will need to supply the name of the next foreign key navigation property which will be  Category.

[UIHint("CascadeHierarchical")]
[CascadeHierarchical("Category")]
public Product Product { get; set; }

Listing 1 – Attribute applied

Note in Listing 1 we only need to supply the next navigation property and if there was another level up we could supply that also and so on.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class CascadeHierarchicalAttribute : Attribute
{
    public String[] Parameters { get; private set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="CascadeHierarchicalAttribute"/> class.
    /// </summary>
    /// <param name="parameters">
    /// The parameters are the parent columns in
    /// order of  hierarchy and must be Foreign Key
    /// navigation columns for the hierarchy for car manufacturers
    /// e.g. Manufacturer, VehicleType, Model and Style on the 
    /// Styles table the parameters would be:
    /// [CascadeHierarchical("Manufacturer", "VehicleType", "Model")]
    /// as Style would already be known via foreign key navigation.
    /// </param>
    public CascadeHierarchicalAttribute(params String[] parameters)
    {
        Parameters = parameters;
    }
}

Listing 2 – CascadeHierarchicalAttribute

The only parameter takes the param attribute and takes an array of type String.

Read Only Field Template

So first thing is to create the read only version of the field template, so what will be required, if we look at the standard foreign key field template the only methods we will need to replace is the GetDisplayString() method. In here we will return a string of the form:

Manufacturer > Vehicle Type > Model > Style

this would gives us with cars something like:

“Ford > Car > Mondeo > 5 Door Hatch”

// value to use to separate values in the Hierarchy
private const string DISPLAY_SEPERATOR = " > ";

protected String GetDisplayString()
{
    // make sure this is a navigation property (ForeignKey column navigation property)
    if (!(Column is MetaForeignKeyColumn))
        throw new InvalidOperationException(String.Format("Column {0} must be a foreign key column navigation property", Column.Name));

    // get cascade hierarchical attribute
    var cascadeHierarchicalAttribute = Column.GetAttribute<CascadeHierarchicalAttribute>();
    if (cascadeHierarchicalAttribute == null)
        throw new InvalidOperationException("Was expecting a CascadeFilterAttribute.");

    // check for null value
    if (FieldValue != null)
    {
        //get parent table
        var parentTable = ForeignKeyColumn.ParentTable;

        // add this foreign key navigation property to the soreted list
        var fieldValues = new SortedList<int, String>();
        fieldValues.Add(0, ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue));

        // get current value as an object
        Object currentValue = FieldValue;

        // loop through each navigation property to build values
        for (int i = 0; i < cascadeHierarchicalAttribute.Parameters.Length; i++)
        {
            // set name of parent column
            var parentColumnName = cascadeHierarchicalAttribute.Parameters[i];

            // get parent column from name
            var parentColumn = (MetaForeignKeyColumn)parentTable.GetColumn(parentColumnName);

            // check for valid column
            if (parentColumn == null && !(parentColumn is MetaForeignKeyColumn))
                throw new InvalidOperationException(String.Format("Invalid parent column {0}", parentColumnName));

            // get next value
            currentValue = currentValue.GetPropertyValue(parentColumnName);

            // extract current value as string using the parent table's display string
            var currentValueString = FormatFieldValue(parentColumn.ParentTable.GetDisplayString(currentValue));

            // add current value as string to the sorted field values list
            fieldValues.Add(i + 1, currentValueString);

            // set next parent table
            parentTable = parentColumn.ParentTable;
        }

        // build display string
        var displayString = new StringBuilder();
        for (int i = cascadeHierarchicalAttribute.Parameters.Length; i >= 0; i--)
            displayString.Append(fieldValues[i] + DISPLAY_SEPERATOR);

        // return the built string
        return FormatFieldValue(displayString.ToString().Substring(0, displayString.ToString().Length - 2));
    }
    else
        // same as standard foreign key field
        return FormatFieldValue(ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue));
}

Listing 2 – new GetDisplayString method

now in Details and List pages we will get output like this:

25-05-2010 15-06-46

Figure 4 – new output from read only CascadeHierarchical field template.

The only clever piece of code in here is the GetPropValue() method which gets the actual value from the parent column using some basic reflection.

/// <summary>
/// Gets the property value.
/// </summary>
/// <param name="sourceObject">The source object.</param>
/// <param name="propertyName">Name of the property.</param>
/// <returns>The named properties value</returns>
public static Object GetPropertyValue(this Object sourceObject, string propertyName)
{
    if (sourceObject != null)
        return sourceObject.GetType().GetProperty(propertyName).GetValue(sourceObject, null);
    else
        return null;
}

Listing 3 -  GetPropertyValue

So in the next part we will create the CascadeHierarchical_Edit field template that has multiple dropdown lists populated one for each parent with the furthest grandparent filtering the next and so on to the child.

Note: I will add a project download in the next article.

Saturday, 4 April 2009

Cascading Filters and Fields – Dynamic Data Entity Framework Version (UPDATED)

Well I wanted to do this in EF and Preview 3 at the same time but I having an issue with that so I’m combining both the Cascading Fields and Filters together and when the bugs are ironed out of the Preview I’ll do it there also.

Firstly the issue with the Preview.

  1. No filters support in the DefaultEFProject
  2. Errors when saving using the DefaultDomainServiceProject

Well I’m going to build a new Dynamic Data Entities Web Application for this project and create a separate project to keep the CascadeExtensions in.

I’ll add the projects zipped to the end of the article.

Lets create the class file first. (I’m assuming you know how to operate VS :D )

Create a new Class Library project Class Library project and delete the Class.cs file and give the project a namespace like DyanmicData.CascadeExtensions

ScreenShot285

Figure 1 – Adding Assembly name and Default namespace

using System;

namespace
DynamicData.CascadeExtensions { /// <summary> /// Attribute to identify which column to use as a /// parent column for the child column to depend upon /// </summary> public class CascadeAttribute : Attribute { /// <summary> /// Name of the parent column /// </summary> public String ParentColumn { get; private set; } /// <summary> /// Default Constructor sets ParentColumn /// to an empty string /// </summary> public CascadeAttribute() { ParentColumn = ""; } /// <summary> /// Constructor to use when /// setting up a cascade column /// </summary> /// <param name="parentColumn">Name of column to use in cascade</param> public CascadeAttribute(string parentColumn) { ParentColumn = parentColumn; } } }
Listing 1 - CascadeAttribute

You will need one of my extension methods to extract the attribute later on:

/// <summary>
/// Get the attribute or a default instance of the attribute
/// if the Column attribute do not contain the attribute
/// </summary>
/// <typeparam name="T">Attribute type</typeparam>
/// <param name="table">Column to search for the attribute on.</param>
/// <returns>The found attribute or a default instance of the attribute of type T</returns>
public static T GetAttributeOrDefault<T>(this MetaColumn column) where T : Attribute, new()
{
    return column.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
}

Listing 2 – GetAttributeOrDefault extension method.

I have some more extension methods to add later that will be used by both the CascadeFieldTemplate and CascadeFilterTemplates.

using System;

namespace DynamicData.CascadeExtensions
{
    /// <summary>
    /// Event Arguments for Category Changed Event
    /// </summary>
    public class SelectionChangedEventArgs : EventArgs
    {
        /// <summary>
        /// Custom event arguments for SelectionChanged 
        /// event of the CascadingFieldTemplate control
        /// </summary>
        /// <param name="value">
        /// The value of the currently selected 
        /// value of the parent control
        /// </param>
        public SelectionChangedEventArgs(String value)
        {
            Value = value;
        }
        /// <summary>
        /// The values from the control of the parent control
        /// </summary>
        public String Value { get; set; }
    }
}

Listing 3 - SelectionChangedEventArgs

Next we create two new classes called CascadeFieldTemplate and CascadeFilterTemplate.

using System;
using System.Web.DynamicData;
using System.Web.UI.WebControls;

namespace DynamicData.CascadeExtensions
{
    /// <summary>
    /// Modifies the standard FieldTEmplateUserControl 
    /// to support cascading of selected values.
    /// </summary>
    public class CascadingFieldTemplate : FieldTemplateUserControl
    {
        /// <summary>
        /// Controls selected value
        /// </summary>
        public String SelectedValue { get; private set; }

        /// <summary>
        /// This controls list control 
        /// </summary>
        public ListControl ListControl { get; private set; }

        /// <summary>
        /// Parent column of this column named in metadata
        /// </summary>
        public MetaForeignKeyColumn ParentColumn { get; private set; }

        /// <summary>
        /// This FieldTemplates column as MetaForeignKeyColumn
        /// </summary>
        public MetaForeignKeyColumn ChildColumn { get; private set; }

        /// <summary>
        /// Parent control acquired from ParentColumn 
        /// </summary>
        public CascadingFieldTemplate ParentControl { get; set; }

        protected virtual void Page_Init(object sender, EventArgs e)
        {
            // get the parent column
            var parentColumn = Column.GetAttributeOrDefault<CascadeAttribute>().ParentColumn;
            if (!String.IsNullOrEmpty(parentColumn))
            {
                ParentColumn = Column.Table.GetColumn(parentColumn) as MetaForeignKeyColumn;
            }

            // cast Column as MetaForeignKeyColumn
            ChildColumn = Column as MetaForeignKeyColumn;


            // get parent field (note you must specify the
            // container control type in <DetailsView> or <FormView>
            ParentControl = GetParentControl();
        }

        /// <summary>
        /// Delegate for the Interface
        /// </summary>
        /// <param name="sender">
        /// A parent control also implementing the 
        /// ISelectionChangedEvent interface
        /// </param>
        /// <param name="e">
        /// An instance of the SelectionChangedEventArgs
        /// </param>
        public delegate void SelectionChangedEventHandler(
            object sender,
            SelectionChangedEventArgs e);

        //publish event
        public event SelectionChangedEventHandler SelectionChanged;

        /// <summary>
        /// Raises the event checking first that an event if hooked up
        /// </summary>
        /// <param name="value">The value of the currently selected item</param>
        public void RaiseSelectedIndexChanged(String value)
        {
            // make sure we have a handler attached
            if (SelectionChanged != null)
            {
                //raise event
                SelectionChanged(this, new SelectionChangedEventArgs(value));
            }
        }

        // advanced populate list control
        protected void PopulateListControl(ListControl listControl, String filterValue)
        {
            //get the parent column
            if (ParentColumn == null)
            {
                // if no parent column then just call
                // the base to populate the control
                PopulateListControl(listControl);
                // make sure control is enabled
                listControl.Enabled = true;
            }
            else if (String.IsNullOrEmpty(filterValue))
            {
                // if there is a parent column but no filter value
                // then make sure control is empty and disabled
                listControl.Items.Clear();

                if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
                    listControl.Items.Add(new ListItem("[Not Set]", ""));

                // make sure control is disabled
                listControl.Enabled = false;
            }
            else
            {
                // get the child columns parent table
                var childTable = ChildColumn.ParentTable;

                // get query {Table(Developer).OrderBy(d => d.Name)}
                var query = ChildColumn.ParentTable.GetQuery(Column.Table.CreateContext());

                // get list of values filtered by the parent's selected entity
                var itemlist = query.GetQueryFilteredByParent(ParentColumn, filterValue);

                // clear list controls items collection before adding new items
                listControl.Items.Clear();

                // only add [Not Set] if in insert mode or column is not required
                if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
                    listControl.Items.Add(new ListItem("[Not Set]", ""));

                // add returned values to list control
                foreach (var row in itemlist)
                    listControl.Items.Add(
                        new ListItem(
                            childTable.GetDisplayString(row),
                            childTable.GetPrimaryKeyString(row)));

                // make sure control is enabled
                listControl.Enabled = true;
            }
        }

        /// <summary>
        /// Gets the Parent control in a cascade of controls
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private CascadingFieldTemplate GetParentControl()
        {
            // get value of dev ddl (Community)
            var parentDataControl = GetContainerControl();

            if (ParentColumn != null)
            {
                // Get Parent FieldTemplate
                var parentDynamicControl = parentDataControl
                    .FindDynamicControlRecursive(ParentColumn.Name)
                    as DynamicControl;

                // extract the parent control from the DynamicControl
                CascadingFieldTemplate parentControl = null;
                if (parentDynamicControl != null)
                    parentControl = parentDynamicControl.Controls[0] 
as
CascadingFieldTemplate; return parentControl; } return null; } /// <summary> /// Get the Data Control containing the FiledTemplate /// usually a DetailsView or FormView /// </summary> /// <param name="control"> /// Use the current field template as a starting point /// </param> /// <returns> /// A CompositeDataBoundControl the base class for FormView and DetailsView /// </returns> private CompositeDataBoundControl GetContainerControl() { var parentControl = this.Parent; while (parentControl != null) { // NOTE: this will not work if used in // inline editing in a list view as // ListView is a DataBoundControl. var p = parentControl as CompositeDataBoundControl; if (p != null) return p; else parentControl = parentControl.Parent; } return null; } } }

Listing 4 – CascadeFieldTemplate

using System;
using System.Web.DynamicData;
using System.Web.UI.WebControls;

namespace DynamicData.CascadeExtensions
{
    /// <summary>
    /// Modifies the standard FieldTEmplateUserControl 
    /// to support cascading of selected values.
    /// </summary>
    public class CascadingFilterTemplate : FilterUserControlBase
    {
        #region Properties
        /// <summary>
        /// This controls list control 
        /// </summary>
        public ListControl ListControl { get; private set; }

        /// <summary>
        /// Paretn column of this column named in metadata
        /// </summary>
        public MetaForeignKeyColumn ParentColumn { get; private set; }

        /// <summary>
        /// This FieldTemplates column as MetaForeignKeyColumn
        /// </summary>
        public MetaForeignKeyColumn ChildColumn { get; private set; }

        /// <summary>
        /// Parent control acquired from ParentColumn 
        /// </summary>
        public CascadingFilterTemplate ParentControl { get; set; }
        #endregion

        //public override IQueryable GetQueryable(IQueryable source)
        //{
        //    return source;
        //}

        protected virtual void Page_Init(object sender, EventArgs e)
        {
            // get the parent column
            var parentColumn = Column.GetAttributeOrDefault<CascadeAttribute>().ParentColumn;
            if (!String.IsNullOrEmpty(parentColumn))
                ParentColumn = Column.Table.GetColumn(parentColumn) as MetaForeignKeyColumn;

            // cast Column as MetaForeignKeyColumn
            ChildColumn = Column as MetaForeignKeyColumn;

            // get dependee field (note you must specify the
            // container control type in <DetailsView> or <VormView>
            ParentControl = GetParentControl();
        }

        /// <summary>
        /// Delegate for the Interface
        /// </summary>
        /// <param name="sender">
        /// A parent control also implementing the 
        /// ISelectionChangedEvent interface
        /// </param>
        /// <param name="e">
        /// An instance of the SelectionChangedEventArgs
        /// </param>
        public delegate void SelectionChangedEventHandler(
            object sender,
            SelectionChangedEventArgs e);

        //publish event
        public event SelectionChangedEventHandler SelectionChanged;

        /// <summary>
        /// Raises the event checking first that an event if hooked up
        /// </summary>
        /// <param name="value">The value of the currently selected item</param>
        public void RaiseSelectedIndexChanged(String value)
        {
            // make sure we have a handler attached
            if (SelectionChanged != null)
            {
                //raise event
                SelectionChanged(this, new SelectionChangedEventArgs(value));
            }
        }

        // advanced populate list control
        protected void PopulateListControl(ListControl listControl, String filterValue)
        {
            //get the parent column
            if (ParentColumn == null)
            {
                // if no parent column then just call
                // the base to populate the control
                PopulateListControl(listControl);
                // make sure control is enabled
                listControl.Enabled = true;
            }
            else if (String.IsNullOrEmpty(filterValue))
            {
                // if there is a parent column but no filter value
                // then make sure control is empty and disabled
                listControl.Items.Clear();

                listControl.Items.Add(new ListItem("[All]", ""));

                // make sure control is disabled
                listControl.Enabled = false;
            }
            else
            {
                // get the child columns parent table
                var childTable = ChildColumn.ParentTable;

                // get query {Table(Developer).OrderBy(d => d.Name)}
                var query = ChildColumn.ParentTable.GetQuery(Column.Table.CreateContext());

                // filter the query by the parent
                var itemlist = query.GetQueryFilteredByParent(ParentColumn, filterValue);

                // clear list controls items collection before adding new items
                listControl.Items.Clear();
                listControl.Items.Add(new ListItem("[All]", ""));

                // add returned values to list control
                foreach (var row in itemlist)
                    listControl.Items.Add(
                        new ListItem(
                            childTable.GetDisplayString(row),
                            childTable.GetPrimaryKeyString(row)));

                // make sure control is enabled
                listControl.Enabled = true;
            }
        }

        /// <summary>
        /// Gets the Parent control in a cascade of controls
        /// </summary>
        /// <returns>An the parent control or null</returns>
        private CascadingFilterTemplate GetParentControl()
        {
            if (ParentColumn != null)
            {
                // get the parent container
                var parentDataControl = GetContainerControl();

                // get the parent container
                if (parentDataControl != null)
                    return parentDataControl.FindFilterControlRecursive(ParentColumn.Name)
                        as CascadingFilterTemplate;
            }
            return null;
        }

        /// <summary>
        /// Get the Data Control containing the FiledTemplate
        /// usually a DetailsView or FormView
        /// </summary>
        /// <param name="control">
        /// Use the current field template as a starting point
        /// </param>
        /// <returns>
        /// A FilterRepeater the control that 
        /// contains the current control
        /// </returns>
        private FilterRepeater GetContainerControl()
        {
            var parentControl = this.Parent;
            while (parentControl != null)
            {
                var p = parentControl as FilterRepeater;
                if (p != null)
                    return p;
                else
                    parentControl = parentControl.Parent;
            }
            return null;
        }
    }
}

Listing 5 – CadcadingFilterTemplate

You may note that I have removed GetQueryFilteredByParent and some other local methods from both CascadeFieldTemplate and CadcadingFilterTemplate, they will be placed in the extension methods class file later.

Now we come the the differences between the Linq to SQL implementation and this the Entity Framework implementation.

The issue I had when trying to make this work with EF was that

private IQueryable GetQueryFilteredByParent
    (MetaTable childTable,
    MetaForeignKeyColumn parentColumn,
    object selectedParent)
{
    // get query {Table(Developer)}
    var query = ChildColumn.ParentTable.GetQuery(DC);

    // {Developers}
    var parameter = Expression.Parameter(childTable.EntityType, childTable.Name);

    // {Developers.Builder}
    var property = Expression.Property(parameter, parentColumn.Name);

    // {value(Builder)}
    var constant = Expression.Constant(selectedParent);

    // {(Developers.Builder = value(Builder))}
    var predicate = Expression.Equal(property, constant);

    // {Developers => (Developers.Builder = value(Builder))}
    var lambda = Expression.Lambda(predicate, parameter);

    // {Table(Developer).Where(Developers => (Developers.Builder = value(Builder)))}
    var whereCall = Expression.Call(typeof(Queryable), 
        "Where", 
        new Type[] { childTable.EntityType }, 
        query.Expression, 
        lambda);

    // generate the query and return it
    return query.Provider.CreateQuery(whereCall);
}

Listing 6 – Old GetQueryFilteredByParent method.

In here I passed in the selectedParent which contained the entity I was filtering on anyway what I found was the EF did not like that at all it said basically I want a simple value like int, String, double etc.

This is the expression I was faced with:

Table(Developer).Where(Developers => (Developers.Builder = value(Builder)))

here I was leaving the join up to L2S but EF wanted me to be more specific

Table(Developer).Where(Developers => (Developers.BuilderId = 2))

But I knew that wouldn't work because EF does not have the FK fields in it’s entities, well not if it can help it :) so I surmised that it would want something like this:

Table(Developer).Where(Developers => (Developers.Builder.Id = 2))

Where Id is the PK of the Builder entity.

And then I was lucky enough to be trying this with Preview 3 and the DefaultDomainServiceProject which if you have a look at the ForeignKey filter you will see some nice Expression creating code:

private Expression BuildQueryBody(
    ParameterExpression parameterExpression, 
    string selectedValue)
{
    IDictionary dict = new Hashtable();
    Column.ExtractForeignKey(dict, selectedValue);

    int i = 0;
    ArrayList andFragments = new ArrayList();
    foreach (DictionaryEntry entry in dict)
    {
        string fieldName = Column.ParentTable.Name + "." 
            + Column.ParentTable.PrimaryKeyColumns[i++].Name;

        Expression propertyExpression = 
            CreatePropertyExpression(parameterExpression, fieldName);

        object value = ChangeType(entry.Value, propertyExpression.Type);
        Expression equalsExpression = Expression.Equal(
            propertyExpression, 
            Expression.Constant(value, propertyExpression.Type));

        andFragments.Add(equalsExpression);
    }

    Expression result = null;
    foreach (Expression e in andFragments)
    {
        if (result == null)
        {
            result = e;
        }
        else
        {
            result = Expression.AndAlso(result, e);
        }
    }
    return result;
}

Listing 7 – BuildQuery from the ForeignKey filter.

This helps build something like this (item.Categories.CategoryID = 1) which eventually produces this where expression and it would deal with composite keys.

Where(item => (item.Categories.CategoryID = 2))

So I swiped that from the ForeignKey filter and added it to my Extension methods, and built the missing bits from what I could glean with Reflector.

So we have the following in the extension methods class

#region IQueryable methods
/// <summary>
/// Gets a list of entities from the source IQueryable 
/// filtered by the MetaForeignKeyColumn's selected value
/// </summary>
/// <param name="sourceQuery">The query to filter</param>
/// <param name="fkColumn">The column to filter the query on</param>
/// <param name="fkSelectedValue">The value to filter the query by</param>
/// <returns>
/// An IQueryable of the based on the source query 
/// filtered but the FK column and value passed in.
/// </returns>
public static IQueryable GetQueryFilteredByParent(this IQueryable sourceQuery, MetaForeignKeyColumn fkColumn, String fkSelectedValue)
{
    // if no filter value return the query
    if (String.IsNullOrEmpty(fkSelectedValue))
        return sourceQuery;

    // {RequiredPlots}
    var parameterExpression = Expression.Parameter(sourceQuery.ElementType, fkColumn.Table.Name);

    // {(RequiredPlots.Builders.Id = 1)}
    var body = BuildWhereClause(fkColumn, parameterExpression, fkSelectedValue);

    // {RequiredPlots => (RequiredPlots.Builders.Id = 1)}
    var lambda = Expression.Lambda(body, parameterExpression);

    // Developers.Where(RequiredPlots => (RequiredPlots.Builders.Id = 1))}
    MethodCallExpression whereCall = Expression.Call(typeof(Queryable),
        "Where", new Type[] { sourceQuery.ElementType },
        sourceQuery.Expression,
        Expression.Quote(lambda));

    // create and return query
    return sourceQuery.Provider.CreateQuery(whereCall);
}

/// <summary>
/// This builds the and where clause taking
/// into account composite keys
/// </summary>
/// <param name="fkColumn">The column to filter the query on</param>
/// <param name="fkSelectedValue">The value to filter the query by</param>
/// <param name="parameterExpression">Parameter expression</param>
/// <returns>
/// Returns the expression for the where clause 
/// i.e. ((x = 1) && (Y = 2)) or (x = 1) etc.
/// </returns>
private static Expression BuildWhereClause(
    MetaForeignKeyColumn fkColumn, 
    ParameterExpression parameterExpression, 
    string fkSelectedValue)
{
    // get the FK's and value into dictionary
    IDictionary dict = new OrderedDictionary();
    fkColumn.ExtractForeignKey(dict, fkSelectedValue);

    // setup index into dictionary
    int i = 0;

    // setup array list to hold each AND fragment
    ArrayList andFragments = new ArrayList();
    foreach (DictionaryEntry entry in dict)
    {
        // get fk name 'Builders.Id'
        string keyName = fkColumn.Name
            + "." + fkColumn.ParentTable.PrimaryKeyColumns[i++].Name;

        // Build property expression 
        // i.e. {RequiredPlots.Builders.Id}
        Expression propertyExpression 
            = BuildPropertyExpression(parameterExpression, keyName);

        // sets the type based on the propertyExpression's type
        // i.e. all the values returned from the DDL are of type string
        // so the type on the expression needs setting to the correct type
        object value = ChangeType(entry.Value, propertyExpression.Type);

        // join the property expression and value in an
        // equals expression i.e. (RequiredPlots.Builders.Id = 1)
        Expression equalsExpression 
            = Expression.Equal(propertyExpression, 
            Expression.Constant(value, propertyExpression.Type));

        // add a fragment to array list
        andFragments.Add(equalsExpression);
    }

    // initialise result
    Expression result = null;
    // join add fragments of composite keys 
    // together together
    foreach (Expression e in andFragments)
    {
        if (result == null)
            result = e;
        else
            result = Expression.AndAlso(result, e);
    }
    // joined fragments look something like:
    // (RequiredPlots.Developer.Id = 1) && (RequiredPlots.HouseType.Id = 1)
    return result;
}

/// <summary>
/// Builds a property expression from the parts it joins
/// the parameterExpression and the propertyName together.
/// i.e. {RequiredPlots}  and "Builders.Id"
/// becomes: {RequiredPlots.Developers.Id}
/// </summary>
/// <param name="parameterExpression">
/// The parameter expression.
/// </param>
/// <param name="propertyName">
/// Name of the property.
/// </param>
/// <returns>
/// A property expression
/// </returns>
public static Expression BuildPropertyExpression(
    Expression parameterExpression, 
    string propertyName)
{
    Expression expression = null;
    // split the propertyName into each part to 
    // be build into a property expression
    string[] strArray = propertyName.Split(new char[] { '.' });
    foreach (string str in strArray)
    {
        if (expression == null)
            expression 
                = Expression.PropertyOrField(parameterExpression, str);
        else
            expression 
                = Expression.PropertyOrField(expression, str);
    }
    // {RequiredPlots.Developer.Id}
    return expression;
}

/// <summary>
/// Changes the type.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="type">The type to convert to.</param>
/// <returns>The value converted to the type.</returns>
public static object ChangeType(object value, Type type)
{
    // if type is null throw exception can't
    // carry on nothing to convert to.
    if (type == null)
        throw new ArgumentNullException("type");

    if (value == null)
    {
        // test for nullable type 
        // (i.e. if Nullable.GetUnderlyingType(type)
        // is not null then it is a nullable type 
        // OR if it is a reference type
        if ((Nullable.GetUnderlyingType(type) != null) 
            || !type.IsValueType)
            return null;
        else // for 'not nullable value types' return the default value.
            return Convert.ChangeType(value, type);
    }

    // ==== Here we are guaranteed to have a type and value ====

    // get the type either the underlying type or 
    // the type if there is no underlying type.
    type = Nullable.GetUnderlyingType(type) ?? type;

    // Convert using the type
    TypeConverter converter 
        = TypeDescriptor.GetConverter(type);
    if (converter.CanConvertFrom(value.GetType()))
    {
        // return the converted value
        return converter.ConvertFrom(value);
    }

    // Convert using the values type
    TypeConverter converter2 
        = TypeDescriptor.GetConverter(value.GetType());
    if (!converter2.CanConvertTo(type))
    {
        // if the type cannot be converted throw an error
        throw new InvalidOperationException(
            String.Format("Unable to convert type '{0}' to '{1}'", 
            new object[] { value.GetType(), type }));
    }
    // return the converted value
    return converter2.ConvertTo(value, type);
}
#endregion

Listing 8 – IQueryable extension methods

Updated: 

In the BuildWhereClause method in Listing 8 I have made a minor change that resolves a major bug:

    string keyName = fkColumn.ParentTable.Name + "." + fkColumn.ParentTable.PrimaryKeyColumns[i++].Name;

has been changed to:

         string keyName = fkColumn.Name + "." + fkColumn.ParentTable.PrimaryKeyColumns[i++].Name;

The issue here was that you would get {RequiredPlots.Developers.Id} instead of {RequiredPlots.Developer.Id} (note the plural Developers) this was fine in Entity Framework where the entity was left as it cane out of the DB but no good for Linq to SQL which uses pluralisation.

So there you have it, there’s a lot more we could do with this to streamline the code make some of the extension methods more generic etc but I think I will leave it there.

Download (UPDATED)

The download is a Web Application Project for EF bit the CascadeExtensions classes, FieldTemplate and FilterUserControl are compatible with EF and L2S.

Note: Also included are the script to create the DB and some data to import in excel format.
Updated: I’ve now added filter ordering via an extension to the FilterRepeater called SortedFilterRepeater and am mapping it in web.config, also added a general sort vi IAutoFieldGenerator on all pages

Friday, 27 March 2009

Cascading Filters – Dynamic Data Futures (Futures on Codeplex) (UPDATED)

This is the second article is the series following on from Cascading Filters – for Dynamic Data v1.0 all we are going to do is apply the same CascadingFilterTemplate to the DefaultFilter in the futures project.

  1. Dynamic Data (v1.0) .Net 3.5 SP1
  2. Dynamic Data Futures (Futures on Codeplex)
  3. Dynamic Data Preview 3 (Preview 3 on Codeplex)

This is the same class as in the previous article just added to a Dynamic Data Futures enabled website.

using System;
using System.Web.DynamicData;
using System.Web.UI;
using Microsoft.Web.DynamicData;


public partial class Default_Filter : CascadingFilterTemplate, ISelectionChangedAware
{
    public event EventHandler SelectionChanged
    {
        add
        {
            DropDownList1.SelectedIndexChanged += value;
        }
        remove
        {
            DropDownList1.SelectedIndexChanged -= value;
        }
    }

    public override string SelectedValue
    {
        get
        {
            return DropDownList1.SelectedValue;
        }
    }

    protected override void Page_Init(object sender, EventArgs e)
    {
        // remember to call the base class
        base.Page_Init(sender, e);

        // add event handler if parent exists
        if (ParentControl != null)
        {
            // subscribe to event
            ParentControl.SelectionChanged += ListControlSelectionChanged;
        }

        if (!Page.IsPostBack)
        {
            if (ParentControl != null)
                PopulateListControl(DropDownList1, ParentControl.SelectedValue);
            else
                PopulateListControl(DropDownList1);

            // Set the initial value if there is one
            if (DropDownList1.Items.Count > 1 && !String.IsNullOrEmpty(InitialValue))
            {
                DropDownList1.SelectedValue = InitialValue;
                RaiseSelectedIndexChanged(InitialValue);
            }
        }
        var c = Column;
    }

    // raise event
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        RaiseSelectedIndexChanged(DropDownList1.SelectedValue);
    }

    // consume event
    protected void ListControlSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        PopulateListControl(DropDownList1, e.Value);
        RaiseSelectedIndexChanged(DropDownList1.Items[0].Value);
    }
}

Listing 1 – Default.ascx.cs from Futures project filters

UPDATED: I’ve added this DropDownList1.Items.Count > 1 above to fix error mentioned

In Listing 1 I’ve marked up the changes in the Default.ascx.cs file.

<%@ Control 
    Language="C#" 
    CodeFile="Default.ascx.cs" 
    Inherits="Default_Filter" %>

<asp:DropDownList 
    ID="DropDownList1" 
    runat="server" 
    AutoPostBack="true" 
    EnableViewState="true" 
    CssClass="droplist" 
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="All" Value="" />
</asp:DropDownList>

Listing 2 – only one change here the event handler for the dropdown list

Again in Listing 2 the only change is marked in BOLD ITELIC OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" this just allows us to fire the event when the selection changes as well as when notification of a change occurs.

I’ve used the same DB as in the previous article and the same metadata so you should get the same effect.

Next we will be jumping to the ASP.Net 4.0 Preview using DomainService and adding filtering to the new Filters.

Download (UPDATED)