Showing posts with label Dynamic Data Futures. Show all posts
Showing posts with label Dynamic Data Futures. Show all posts

Sunday, 31 May 2009

Sorting Filters in Dynamic Data (DD v1.0)

This is just a small sample of how to sort your filters in Dynamic Data using the ColumnOrderAttribute from the Dynamic Data Futures project. I was surprised at how easy it was and that I’d not thought of it before.

using System;
using System.Linq;
using System.Web.DynamicData;
namespace DynamicData.CascadeExtensions
{
 /// <summary>
 /// Allows to specify the ordering of columns. 
/// Columns are will be sorted in increasing order based
/// on the Order value. Columns without this attribute
/// have a default Order of 0. Negative values are
/// allowed and can be used to place a column before all other columns. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field,
Inherited = true,
AllowMultiple = false)] public class ColumnOrderAttribute : Attribute, IComparable { public static ColumnOrderAttribute Default = new ColumnOrderAttribute(0); public ColumnOrderAttribute(int order) { Order = order; } /// <summary> /// The ordering of a column. Can be negative. /// </summary> public int Order { get; private set; } public int ListOrder { get; set; } public int CompareTo(object obj) { return Order - ((ColumnOrderAttribute)obj).Order; } } public static partial class HelperExtansionMethods { public static ColumnOrderAttribute GetColumnOrdering(this MetaColumn column) { return column.Attributes.OfType<ColumnOrderAttribute>()
.DefaultIfEmpty(ColumnOrderAttribute.Default).First(); } } }

Listing 1 - Column Order attribute

So Listing 1 is just a direct rip off of the ColumnOrderAttribute in the Futures project. and then the code to order the filters based on the ColumnOrderAttribute.

protected void Page_Load(object sender, EventArgs e)
{
 table = GridDataSource.GetTable();
 Title = table.DisplayName;
 InsertHyperLink.NavigateUrl = table.GetActionPath(PageAction.Insert);
 // Disable various options if the table is readonly
 if (table.IsReadOnly)
 {
 GridView1.Columns[0].Visible = false;
 InsertHyperLink.Visible = false;
 }
// set the filter order
 var filters = from c in table.Columns
 where c is MetaForeignKeyColumn
 orderby c.GetColumnOrdering()
 select c;
 FilterRepeater.DataSource = filters;
 FilterRepeater.DataBind();
}

Listing 2 – modified Page_Load event handler

Here in Listing 2 you can see the code highlighted in bold italic is setting the filter sort order simples.

Note: the only caveat is that the filters are generated twice smile_sad

That caveat in mind I decided to do this instead:

public class SortedFilterRepeater : FilterRepeater
{
 protected override IEnumerable<MetaColumn> GetFilteredColumns()
 {
 // sort the filters by their filter order as specified in FilterAttribute.
 // Table.Columns.Where(c => IsFilterableColumn(c))
// .OrderBy(column => FilterOrdering(column));
var filteredColumns = from c in Table.Columns where IsFilterableColumn(c) orderby FilterOrdering(c) select c; return filteredColumns; } protected bool IsFilterableColumn(MetaColumn column) { // don't filter custom properties by default if (column.IsCustomProperty) return false; // always filter FK columns and bools if (column is MetaForeignKeyColumn) return true; if (column.ColumnType == typeof(bool)) return true; return false; } private ColumnOrderAttribute FilterOrdering(MetaColumn column) { return column.Attributes
.OfType<ColumnOrderAttribute>()
.DefaultIfEmpty(ColumnOrderAttribute.Default)
.First(); } }

Listing 3 – SortedFilterRepeater

Updated: Listing 3 is just a ripp-off on the AdvancedFilterRepeater in the Dynamic Data Futures sample.

I implemented this using by adding a mapping to the web.config as in Listing 4.

<pages>
 <tagMapping>
 <add tagType="System.Web.DynamicData.FilterRepeater"
mappedTagType="DynamicData.CascadeExtensions.SortedFilterRepeater" /> </tagMapping> </pages>

Listing 4 – Adding mapping to web.config

The advantage of the above is:

  1. It only generates the filters once
  2. This will work with my CascadingFilters

So I think this addendum wraps this up as we have sorting of filters in Dynamic Data Preview 4.

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)

[フレーム]

Monday, 23 March 2009

Cascading or Dependant Field Templates for ASP.Net 4.0 Preview

Introduction

So Here’s the Idea (which is a continuation of Dynamic Data – Cascading FieldTemplates) you have a field that is a dropdown list of one thing and another that is a subset of the previous. So to have a real world example (I’ve been working in the House Building Industry in the UK for the last 5 years so I have a ready example.

A very simple House Sales system

Figure 1 – A very simple House Sales system

In Figure 1 we have five tables, each Builder would have a number of Developments and each Development would have a series of House Types. Now a Plot would exist on a Development of a single Builder and have a House Type, in my example I have two plots tables RequiredPlot and NotRequiredPlot the difference is simple in one all the FK fields are require i.e. not nullable and in the other they are nullable. This is to show both faces of the cascading FieldTemplate. When you insert a plot in Dynamic Data then you must choose the Builder the Development and the House Type.

Insert New Plot NotRequired (Note the [Not Set] in the NotRequired) Insert New Plot Required

Figure 2 – Insert New Plot NotRequired and Required (Note the [Not Set] in the NotRequired)

Here in Figure 2 Inserting a new Plot we have a problem at the moment I can choose a development of a different builder than the plot and the same with house type.

So my idea here is to provide a generic way of saying this field depends upon that filed (i.e. House Type depends upon Development and Development depends upon Builder).

(削除) Bug (削除ここまで)Undocumented Feature

And also having done this before I have found a nasty (削除) bug (削除ここまで) (sorry) undocumented feature my software never has bugs only undocumented features. This err Feature shows it’s self when you have a list where one say in our case Builder has only one Development and you are not using the [not set] and only showing values if you select Builder A and her has two developments and you select development 2 this will filter the contents of the House Types dropdown list, if you then change the Builder to a builder that only have one development then you will not get the corrects house types showing in the House Types dropdown list, because you cannot change the Development because there is only one.

OK I hope that last paragraph made sense because it took me a while to see why the problem exists, which is the cascade does not ripple through the cascading controls. This version of cascading Field Template will rectify this problem.

So explanation over, to the code.

Building the Extension the the FieldTemplateUserControl

The two main requirements of this implementation are:

  1. Have a ripple down the chain of controls when a selection at the top is made.
  2. A generic means of cascade.

In the previous version I simply hooked up the SelectionChanged event of the DropDownList but that only fired when the dropdown list is changed manually. So this time we will implement our own event in the UserControl which we can fire on DropDownList SelectionChanged event and when we receive a SelectionChange event from the parent control.

Before we dive into the main body of code we need to understand the event structure so here’s a basic intro to events. I’m going to use some terminology so here are my definitions how I understand it.

Term Explanation Where
Delegate Think of a Delegate as the declaration of the method pattern you must use to implement or consume this event Publisher
Publisher This is the code that has the event and wants to let other code know about the event  
Client This is the code that wants to know when the event happens in the publisher  
X This is the event  
Publish Is saying I have an event that can inform you when X happens Publisher 
Raise The publisher announces that X has happened Publisher
Subscribe Tell me when X happens Client
Consume Is actually deal with the results of the event X Client
EventArgs information passed to the event from the Publisher relating to event X own class

Table 1 – Event Terms and Descriptions

I personally find most explanations of event handling confusing so I cobbled together the above from what I’ve read, to help stop me getting confused when need to work with events.

Cascade Attribute and Associated Extension Methods

We need an attribute

/// <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

Below are the standard extension methods I use to find attributes I use these so I don’t have to test for null as I know I will get an attribute back, for a detailed explanation of these see Writing Attributes and Extension Methods for Dynamic Data.

public static partial class HelperExtansionMethods
{
 /// <summary>
 /// Get the attribute or a default instance of the attribute
 /// if the Table attribute do not contain the attribute
 /// </summary>
 /// <typeparam name="T">Attribute type</typeparam>
 /// <param name="table">Table 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 MetaTable table) where T : Attribute, new()
 {
 return table.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
 }
 /// <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 – Extension methods for finding attributes

Custom EventArgs Type

So the first thing we need is an event argument to pass the value of the selected item to the child field, since we are going to the trouble of having our own event we may as well do away with the whole looking for the control and extracting it’s value that we did before this will greatly simplify the code and make it more efficient as we will not be searching the control tree which takes time.

/// <summary>
/// Event Arguments for Category Changed Event
/// </summary>
public class SelectionChangedEventArgs : EventArgs
{
 /// <summary>
 /// Initializes a new category changed event
 /// </summary>
 /// <param name="categoryId">
 /// The categoryId of the currently selected category
 /// </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 – Selection Changes Event Arguments

CascadingFieldTemplate Class

This part of this article involves creating the cascade class to apply to the ForeignKey_Edit FieldTEmplate

Class diagram for CascadingFieldTemplate

Figutre 3 -  Class diagram for CascadingFieldTemplate

I will be using a few bits from the old Dynamic Data Futures project which you can find here Dynamic Data on Codeplex the file I will be using is the LinqExpressionHelper file as what the point of writing what already bee written. I’ll point out this code when we get to it but it’s always worth crediting the author of the code, so as usual all the credit goes to the ASP.Net team for the really clever bit of code here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.DynamicData;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using System.Web.UI;
/// <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; }
}
/// <summary>
/// Modifies the standard FieldTemplateUserControl 
/// to support cascading of selected values.
/// </summary>
public class CascadingFieldTemplate : FieldTemplateUserControl
{
 /// <summary>
 /// Data context
 /// </summary>
 private object DC;
 /// <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)
 {
 DC = Table.CreateContext();
 // 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;
 //TODO: find a way of determining which the parent control is DetailsView or FormView
 // get dependee 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 parent FiledTeamlate
 string[] parentColumnPKV = filterValue.Split(',');
 var parentFieldTemplate = GetSelectedParent(
 parentColumnPKV, 
 ParentColumn.ParentTable);
 // get list of values filteres by the parent's selected entity
 var itemlist = GetQueryFilteredByParent(
 childTable, 
 ParentColumn, 
 parentFieldTemplate);
 // 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>
 /// Get the entity value of the selected 
 /// value of the parent column
 /// </summary>
 /// <param name="primaryKeyValues">
 /// An array of primary key values
 /// </param>
 /// <param name="parentTable">
 /// Parent columns FK table
 /// </param>
 /// <returns>
 /// Returns the currently selected entity
 /// from the parent list as an object
 /// </returns>
 private object GetSelectedParent(
 string[] primaryKeyValues, 
 MetaTable parentTable)
 {
 var query = parentTable.GetQuery(DC);
 // Items.Where(row => row.ID == 1).Single()
// this is where I use that file from Dynamic Data Futures
var singleWhereCall = LinqExpressionHelper.BuildSingleItemQuery( query, parentTable, primaryKeyValues); return query.Provider.Execute(singleWhereCall); } /// <summary> /// Returns an IQueryable of the current FK table filtered by the /// currently selected value from the parent filed template /// </summary> /// <param name="childTable"> /// This columns FK table /// </param> /// <param name="parentColumn"> /// Column to filter this column by /// </param> /// <param name="selectedParent"> /// Value to filter this column by /// </param> /// <returns> /// An IQueryable result filtered by the parent columns current value /// </returns> 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); } /// <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 – SelectionChangedEventArgs Class

You will note this class inherits the FieldTemplateUserControl class so we get all the magic of the underlying class. We declare a delegate:

public delegate void SelectionChangedEventHandler(object sender, SelectionChangedEventArgs e);

Note the SelectionChangedEventArgs are not just empty standard EventArgs we now get the value of the parent passed in from the parent of the currently selected value.

And then the event:

public event SelectionChangedEventHandler SelectionChanged;

The we have the guts of the class PopulateListControl which takes the selected value pass in from the parent FieldTemplate where we get a list of items for this column filtered by the parent value if it exists and has a value.

Then we have GetQueryFilteredByParent where we actually get the list of items filtered by the parent FieldTemplate.

And I did say I’d point out where I was using that helper class from Dynamic Data Futures:

var singleWhereCall = LinqExpressionHelper.BuildSingleItemQuery(query, parentTable, primaryKeyValues);

Also here it’s worth talking about:

private CompositeDataBoundControl GetContainerControl()

and in particular this line of code:

var p = parentControl as CompositeDataBoundControl;

the CompositeDataBoundControl is the base type of the DetailsView and the FormView as will know if you’ve looked at the previews (I’ve only just got into it been too busy with work, but that’s stopped for a little while) to facilitate EntityTemplates Details, Edit and Insert now use the FormView control so I’ve written this modification to handle either version, the release with .Net 3.5 SP1 or the Preview. Note however that if you use ListView with inline editing as in my article:

Custom PageTemplates Part 3 - Dynamic/Templated Grid with Insert (Using ListView)

then you will need to modify the code to search for the ListView also.

Modifying the Standard ForeignKey_Edit FieldTemplate

Here we will wire up the SelectionChanged event so a change in FieldTemplate will ripple down the list

parent –> child(parent) –> child etc.

Here again is the code for the FieldTemplate as it has been modified:

using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ForeignKey_EditField : CascadingFieldTemplate //System.Web.DynamicData.FieldTemplateUserControl
{
 protected override void Page_Init(object sender, EventArgs e)
 {
 // remember to call the base class
 base.Page_Init(sender, e);
 // add event handler if dependee exists
 if (ParentControl != null)
 {
 // subscribe to event
 ParentControl.SelectionChanged += SelectedIndexChanged;
 }
 }
 protected void Page_Load(object sender, EventArgs e)
 {
 if (DropDownList1.Items.Count == 0)
 {
 if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
 DropDownList1.Items.Add(new ListItem("[Not Set]", ""));
 PopulateListControl(DropDownList1);
 }
 SetUpValidator(RequiredFieldValidator1);
 SetUpValidator(DynamicValidator1);
 }
 #region Event
 // raise event
 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
 {
 RaiseSelectedIndexChanged(DropDownList1.SelectedValue);
 }
 // consume event
 protected void SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
 {
 PopulateListControl(DropDownList1, e.Value);
 if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
 RaiseSelectedIndexChanged("");
 else
 {
 RaiseSelectedIndexChanged(DropDownList1.Items[0].Value);
 }
 }
 #endregion
 protected override void OnDataBinding(EventArgs e)
 {
 base.OnDataBinding(e);
 if (Mode == DataBoundControlMode.Edit)
 {
 string selectedValueString = GetSelectedValueString();
 ListItem item = DropDownList1.Items.FindByValue(selectedValueString);
 if (item != null)
 {
// if there is a default value cascade it
 RaiseSelectedIndexChanged(item.Value);
 DropDownList1.SelectedValue = selectedValueString;
 }
 }
 else if (Mode == DataBoundControlMode.Insert)
 {
 // if child field has hook up for cascade
 RaiseSelectedIndexChanged("");
 }
 }
 protected override void ExtractValues(IOrderedDictionary dictionary)
 {
 // If it's an empty string, change it to null
 string value = DropDownList1.SelectedValue;
 if (String.IsNullOrEmpty(value))
 {
 value = null;
 }
 ExtractForeignKey(dictionary, value);
 }
 public override Control DataControl
 {
 get
 {
 return DropDownList1;
 }
 }
}

Listing 4 - ForeignKey_Edit FieldTemplate

I’ve highlighted all the changes in BOLD ITALIC to emphasise  the content the main thins to look for are:

In the Page_Init here wee hook up the event if there is a parent control, and then the section that is surrounded with a region called event here we react to the SelectedIndexChanged event of the DropDownList1 and also consume the event from the parent if it exists.

<asp:DropDownList 
 ID="DropDownList1" 
 runat="server" 
 CssClass="DDDropDown" 
 AutoPostBack="True" 
 onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

Listing 5 – changes to the DropDownList control in the page

Here again in Listing 5 I’ve highlighted the changed content, firstly we have enabled AutoPostBack and wired up the OnSelectedIndexChanged event to the event handler DropDownList1_SelectedIndexChanged in the code behind inside the event region.

Sample Metadata

[MetadataType(typeof(RequiredPlotMD))]
public partial class RequiredPlot
{
 public partial class RequiredPlotMD
 {
 public object Id { get; set; }
 public object BuilderId { get; set; }
 public object DeveloperId { get; set; }
 public object HouseTypeId { get; set; }
 public object No { get; set; }
 public object Builder { get; set; }
  [Cascade("Builder")]
 public object Developer { get; set; }
 [Cascade("Developer")]
 public object HouseType { get; set; }
 }
}
[MetadataType(typeof(NotRequiredPlotMD))]
public partial class NotRequiredPlot
{
 public partial class NotRequiredPlotMD
 {
 public object Id { get; set; }
 public object BuilderId { get; set; }
 public object DeveloperId { get; set; }
 public object HouseTypeId { get; set; }
 public object No { get; set; }
 public object Builder { get; set; }
 [Cascade("Builder")]
 public object Developer { get; set; }
  [Cascade("Developer")]
 public object HouseType { get; set; }
 }
}

Listing 6 – Sample metadata

In the attached file is a copy of the website zipped a script for creating the database and an excel spreadsheet with all the data which you can import into the DB which is fiddly but it saves me having to have several different version of the DB

[フレーム]

I would go into more detail breaking it down line by line but I like to have the full listing with lots of comments myself, but if you think I should be more detailed let me know.

Note: This also works with Dynamic Data from .Net 3.5 SP1

Happy coding 

Monday, 15 September 2008

Dynamic Data: Part 3-FileUpload FieldTemplates

  1. Part 1 - FileImage_Edit FieldTemplate.
  2. Part 2 - FileImage_Edit FieldTemplate.
  3. Part 3 - FileUpload FiledTemplate.

FileUpload and FileUpload_Edit FiledTemplates

I thought this would complement the DBImage and FileImage FieldTemplates and so I thought what would you want to be able to do:

  • Upload a file to a specified folder.
  • Download the said file once uploaded.
  • Display an image for the file.
  • Control the download capability via attributes and user Roles.
  • Handle errors such as wrong file type or when file is missing from upload folder.

The FileUpload Attributes

In this example I’m creating on attribute to hold all the parameters to do with FileUpload.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class FileUploadAttribute : Attribute
{
 /// <summary>
 /// where to save files
 /// </summary>
 public String FileUrl { get; set; }
 /// <summary>
 /// File tyoe to allow upload
 /// </summary>
 public String[] FileTypes { get; set; }
 /// <summary>
 /// image type to use for displaying file icon
 /// </summary>
 public String DisplayImageType { get; set; }
 /// <summary>
 /// where to find file type icons
 /// </summary>
 public String DisplayImageUrl { get; set; }
 /// <summary>
 /// If present user must be a member of one
 /// of the roles to be able to download file
 /// </summary>
 public String[] HyperlinkRoles { get; set; }
 /// <summary>
 /// Used to Disable Hyperlink (Enabled by default)
 /// </summary>
 public Boolean DisableHyperlink { get; set; }
 /// <summary>
 /// helper method to check for roles in this attribute
 /// the comparison is case insensitive
 /// </summary>
 /// <param name="role"></param>
 /// <returns></returns>
 public bool HasRole(String[] roles)
 {
 if (HyperlinkRoles.Count() > 0)
 {
 var hasRole = from hr in HyperlinkRoles.AsEnumerable()
 join r in roles.AsEnumerable()
 on hr.ToLower() equals r.ToLower()
 select true;
 return hasRole.Count() > 0;
 }
 return false;
 }
}
Listing 1 – FileUploadAttribute

You will notice in the Listing 1 that all the properties are using c# 3.0’s new Automatic Properties feature less typing; just type prop and hit tab twice and there is you property ready to be filled in.

The second thing you will see is the HasRoles method on this attribute, which takes an array of roles and checks to see if HyperlinkRoles property has any matches. It does this by joining the two arrays together in a Linq to Object query and then selects true for each match in the join. I’m sure this is more readable that the traditional nested foreach loops, it’s certainly neater :D.

The FileUpload FieldTemplate

This FiledTemplate will show the filename and associated icon.

FileUpload with icon

Figure 1- File and associated Icon

<%@ Control
 Language="C#"
 AutoEventWireup="true"
 CodeFile="FileUpload.ascx.cs"
 Inherits="FileImage" %>
<asp:Image ID="Image1" runat="server" />&nbsp;
<asp:Label ID="Label1" runat="server" Text="<%# FieldValueString %>"></asp:Label>
<asp:HyperLink ID="HyperLink1" runat="server"></asp:HyperLink>&nbsp;
<asp:CustomValidator
 ID="CustomValidator1"
 runat="server"
 ErrorMessage="">
</asp:CustomValidator>

Listing 2 – FileUpload.ascx file

As you can see from Listing 1 there are Image, Label and Hyperlink controls on the page. The Label and Hyperlink are mutually exclusive if the conditions are right then a Hyperlink will show so that the file can be downloaded else just a Label will show with the filename.

using System;
using System.IO;
using System.Linq;
using System.Web.DynamicData;
using System.Web.Security;
using System.Web.UI;
using Microsoft.Web.DynamicData;
public partial class FileImage : FieldTemplateUserControl
{
 public override Control DataControl
 {
 get
 {
 return Label1;
 }
 }
 protected override void OnDataBinding(EventArgs e)
 {
 base.OnDataBinding(e);
 //check if field has a value
 if (FieldValue == null)
 return;
 // get the file extension
 String extension = FieldValueString.Substring(
 FieldValueString.LastIndexOf(".") + 1,
 FieldValueString.Length - (FieldValueString.LastIndexOf(".") + 1));
 // get attributes
 var fileUploadAttributes = MetadataAttributes.OfType<FileUploadAttribute>().FirstOrDefault();
 String fileUrl = fileUploadAttributes.FileUrl;
 String displayImageUrl = fileUploadAttributes.DisplayImageUrl;
 String displayImageType = fileUploadAttributes.DisplayImageType;
 // check the file exists else throw validation error
 String filePath;
 if (fileUploadAttributes != null)
 filePath = String.Format(fileUrl, FieldValueString);
 else
 // if attribute not set use default
 filePath = String.Format("~/files/{0}", FieldValueString);
 // show the relavent control depending on metadata
 if (fileUploadAttributes.HyperlinkRoles.Length > 0)
 {
 // if there are roles then check: 
 // if user is in one of the roles supplied
 // or if the hyperlinks are disabled 
 // or if the file does not exist
 // then hide the link
 if (!fileUploadAttributes.HasRole(Roles.GetRolesForUser()) fileUploadAttributes.DisableHyperlink !File.Exists(Server.MapPath(filePath)))
 {
 Label1.Text = FieldValueString;
 HyperLink1.Visible = false;
 }
 else
 {
 Label1.Visible = false;
 HyperLink1.Text = FieldValueString;
 HyperLink1.NavigateUrl = filePath;
 }
 }
 else
 {
 // if either hyperlinks are disabled or the
 // file does not exist then hide the link
 if (fileUploadAttributes.DisableHyperlink !File.Exists(Server.MapPath(filePath)))
 {
 Label1.Text = FieldValueString;
 HyperLink1.Visible = false;
 }
 else
 {
 Label1.Visible = false;
 HyperLink1.Text = FieldValueString;
 HyperLink1.NavigateUrl = filePath;
 }
 }
 // check file exists on file system
 if (!File.Exists(Server.MapPath(filePath)))
 {
 CustomValidator1.ErrorMessage = String.Format("{0} does not exist", FieldValueString);
 CustomValidator1.IsValid = false;
 }
 // show the icon
 if (!String.IsNullOrEmpty(extension))
 {
 // set the file type image
 if (!String.IsNullOrEmpty(displayImageUrl))
 {
 Image1.ImageUrl = String.Format(displayImageUrl, extension + "." + displayImageType);
 }
 else
 {
 // if attribute not set the use default
 Image1.ImageUrl = String.Format("~/images/{0}", extension + "." + displayImageType);
 }
 Image1.AlternateText = extension + " file";
 // if you apply dimentions from DD Futures
 var imageFormat = MetadataAttributes.OfType<ImageFormatAttribute>().FirstOrDefault();
 if (imageFormat != null)
 {
 // if either of the dims is 0 don't set it
 // this will mean that the aspect will remain locked
 if (imageFormat.DisplayWidth != 0)
 Image1.Width = imageFormat.DisplayWidth;
 if (imageFormat.DisplayHeight != 0)
 Image1.Height = imageFormat.DisplayHeight;
 }
 }
 else
 {
 // if file has no extension then hide image
 Image1.Visible = false;
 }
 }
}

Listing 3 – FileUpload.ascx.cs file

In Listing 3 you can see that everything goes on in the OnDataBinding event handler.

The FileUpload_Edit FieldTemplate

<%@ Control
 Language="C#"
 AutoEventWireup="true"
 CodeFile="FileUpload_Edit.ascx.cs"
 Inherits="FileImage_Edit" %>
 
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
 <asp:Image ID="Image1" runat="server" />&nbsp;
 <asp:Label ID="Label1" runat="server" Text="<%# FieldValueString %>"></asp:Label>
 <asp:HyperLink ID="HyperLink1" runat="server"></asp:HyperLink>&nbsp;
</asp:PlaceHolder>
<asp:FileUpload ID="FileUpload1" runat="server" />&nbsp;
<asp:CustomValidator
 ID="CustomValidator1"
 runat="server"
 ErrorMessage="">
</asp:CustomValidator>

Listing 4 – FileUpload_Edit.ascx file

In Listing 4 the PlaceHolder control is used to hide the Image, Label and Hyperlink when in insert mode or when there is no value to be shown.

using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Web.DynamicData;
using System.Web.Security;
using System.Web.UI;
using Microsoft.Web.DynamicData;
public partial class FileImage_Edit : FieldTemplateUserControl
{
 public override Control DataControl
 {
 get
 {
 return Label1;
 }
 }
 protected override void OnDataBinding(EventArgs e)
 {
 base.OnDataBinding(e);
 //check if field has a value
 if (FieldValue == null)
 return;
 // when there is already a value in the FieldValue
 // then show the icon and label/hyperlink
 PlaceHolder1.Visible = true;
 // get the file extension
 String extension = FieldValueString.Substring(
 FieldValueString.LastIndexOf(".") + 1,
 FieldValueString.Length - (FieldValueString.LastIndexOf(".") + 1));
 // get attributes
 var fileUploadAttributes = MetadataAttributes.OfType<FileUploadAttribute>().FirstOrDefault();
 String fileUrl = fileUploadAttributes.FileUrl;
 String displayImageUrl = fileUploadAttributes.DisplayImageUrl;
 String displayImageType = fileUploadAttributes.DisplayImageType;
 String filePath;
 // check the file exists else throw validation error
 if (fileUploadAttributes != null)
 filePath = String.Format(fileUrl, FieldValueString);
 else
 // if attribute not set use default
 filePath = String.Format("~/files/{0}", FieldValueString);
 // show the relavent control depending on metadata
 if (fileUploadAttributes.HyperlinkRoles.Length > 0)
 {
 // if there are roles then check: 
 // if user is in one of the roles supplied
 // or if the hyperlinks are disabled 
 // or if the file does not exist
 // then hide the link
 if (!fileUploadAttributes.HasRole(Roles.GetRolesForUser()) fileUploadAttributes.DisableHyperlink !File.Exists(Server.MapPath(filePath)))
 {
 Label1.Text = FieldValueString;
 HyperLink1.Visible = false;
 }
 else
 {
 Label1.Visible = false;
 HyperLink1.Text = FieldValueString;
 HyperLink1.NavigateUrl = filePath;
 }
 }
 else
 {
 // if either hyperlinks are disabled or the
 // file does not exist then hide the link
 if (fileUploadAttributes.DisableHyperlink !File.Exists(Server.MapPath(filePath)))
 {
 Label1.Text = FieldValueString;
 HyperLink1.Visible = false;
 }
 else
 {
 Label1.Visible = false;
 HyperLink1.Text = FieldValueString;
 HyperLink1.NavigateUrl = filePath;
 }
 }
 // check file exists on file system
 if (!File.Exists(Server.MapPath(filePath)))
 {
 CustomValidator1.ErrorMessage = String.Format("{0} does not exist", FieldValueString);
 CustomValidator1.IsValid = false;
 }
 // show the icon
 if (!String.IsNullOrEmpty(extension))
 {
 // set the file type image
 if (!String.IsNullOrEmpty(displayImageUrl))
 {
 Image1.ImageUrl = String.Format(displayImageUrl, extension + "." + displayImageType);
 }
 else
 {
 // if attribute not set the use default
 Image1.ImageUrl = String.Format("~/images/{0}", extension + "." + displayImageType);
 }
 Image1.AlternateText = extension + " file";
 // if you apply dimentions from DD Futures
 var imageFormat = MetadataAttributes.OfType<ImageFormatAttribute>().FirstOrDefault();
 if (imageFormat != null)
 {
 // if either of the dims is 0 don't set it
 // this will mean that the aspect will remain locked
 if (imageFormat.DisplayWidth != 0)
 Image1.Width = imageFormat.DisplayWidth;
 if (imageFormat.DisplayHeight != 0)
 Image1.Height = imageFormat.DisplayHeight;
 }
 }
 else
 {
 // if file has no extension then hide image
 Image1.Visible = false;
 }
 }
 protected override void ExtractValues(IOrderedDictionary dictionary)
 {
 // get attributes
 var fileUploadAttributes = MetadataAttributes.OfType<FileUploadAttribute>().FirstOrDefault();
 String fileUrl;
 String[] extensions;
 if (fileUploadAttributes != null)
 {
 fileUrl = fileUploadAttributes.FileUrl;
 extensions = fileUploadAttributes.FileTypes;
 if (FileUpload1.HasFile)
 {
 // get the files folder
 String filesDir = fileUrl.Substring(0, fileUrl.LastIndexOf("/") + 1);
 // resolve full path c:\... etc
 String path = Server.MapPath(filesDir);
 // get files extension without the dot
 String fileExtension = FileUpload1.FileName.Substring(
 FileUpload1.FileName.LastIndexOf(".") + 1).ToLower();
 // check file has an allowed file extension
 if (extensions.Contains(fileExtension))
 {
 // try to upload the file showing error if it fails
 try
 {
 FileUpload1.PostedFile.SaveAs(path + "\\" + FileUpload1.FileName);
 Image1.ImageUrl = String.Format(fileUploadAttributes.DisplayImageUrl, fileExtension + ".png");
 Image1.AlternateText = fileExtension + " file";
 dictionary[Column.Name] = FileUpload1.FileName;
 }
 catch (Exception ex)
 {
 // display error
 CustomValidator1.IsValid = false;
 CustomValidator1.ErrorMessage = ex.Message;
 }
 }
 else
 {
 CustomValidator1.IsValid = false;
 CustomValidator1.ErrorMessage = String.Format("{0} is not a valid file to upload", FieldValueString);
 }
 }
 }
 }
}
Listing 5 - FileUpload_Edit.ascx.cs file

In Listing 5 the OnDataBinding event handler is pretty much the same as the FileUpload.ascs.cs file. Here its the ExtractValues method that does the work of uploading and displaying errors, i.e. if the file type of the file to be uploaded does not match a file type specified in the metadata or there is an error during the upload.

Helper Class FileUploadHelper

public static class FileUploadHelper
{
 /// <summary>
 /// If the given table contains a column that has a UI Hint with the value "DbImage", finds the ScriptManager
 /// for the current page and disables partial rendering
 /// </summary>
 /// <param name="page"></param>
 /// <param name="table"></param>
 public static void DisablePartialRenderingForUpload(Page page, MetaTable table)
 {
 foreach (var column in table.Columns)
 {
 // TODO this depends on the name of the field template, need to fix
 if (String.Equals(
 column.UIHint, "DBImage", StringComparison.OrdinalIgnoreCase)
 String.Equals(column.UIHint, "FileImage", StringComparison.OrdinalIgnoreCase)
 String.Equals(column.UIHint, "FileUpload", StringComparison.OrdinalIgnoreCase))
 {
 var sm = ScriptManager.GetCurrent(page);
 if (sm != null)
 {
 sm.EnablePartialRendering = false;
 }
 break;
 }
 }
 }
}

Listing 6 - FileUploadHelper

This is just a modified version of the Dynamic Data Futures DisablePartialRenderingForUpload method the only difference is that I’ve added support for both my file upload capable FieldTemplates FileImage and FileUpload.

Finally Some Sample Metadata

[MetadataType(typeof(FileImageTestMD))]
public partial class FileImageTest : INotifyPropertyChanging, INotifyPropertyChanged
{
 public class FileImageTestMD
 {
 public object Id { get; set; }
 public object Description { get; set; }
 [UIHint("FileUpload")]
 [FileUpload(
 FileUrl = "~/files/{0}",
 FileTypes = new String[] { "pdf", "xls", "doc", "xps" },
 DisplayImageType = "png",
 DisableHyperlink = false,
 HyperlinkRoles=new String[] { "Admin", "Accounts" },
 DisplayImageUrl = "~/images/{0}")]
 [ImageFormat(22, 0)]
 public object filePath { get; set; }
 }
}

Listing 7 – sample metadata

The FileUpload Project

[フレーム]

Note: Please note that the ASPNETDB.MDF supplied in this website is SQL 2008 Express and will not work with SQL 2005 and earlier, you will need to set your own up. Or you can just strip out the login capability from the site.master and web.config.

Enjoy smile_teeth

Subscribe to: Comments (Atom)

AltStyle によって変換されたページ (->オリジナル) /