Tuesday, 28 July 2009

Dynamic Data Custom Field Template – Values List, Take 2

An alternative way of doing the Dynamic Data Custom Field Template – Values List this version uses the UIHint’s ControlParameters property to pass in values to the control.

[MetadataType(typeof(Value.Metadata))]
partial class Value
{
    internal class Metadata
    {
        public object Id { get; set; }
        [UIHint("ValuesList", null, "ValueList", "Y,N,N/A")]
        //[ValuesList("Y,N,N/A")]
        public object TestR { get; set; }
        [UIHint("ValuesList", null, "ValueList", "Y,N,Other")]
        //[ValuesList("Y,N,Other")]
        public object Test { get; set; }
    }
}

Listing 1 – Metadata using the UIHint’s ControlParameters

See the example of using UIHint’s ControlParameters in Listing 1. In the above example you can see that I am passing in the ValueList in the UIHint’s ControlParameters as a key value pair.

/// <summary>
/// Populates a list control with all the values from a parent table.
/// </summary>
/// <param name="listControl">The list control to populate.</param>
protected new void PopulateListControl(ListControl listControl)
{
    var uiHint = Column.GetAttribute<UIHintAttribute>();
    if (uiHint == null || uiHint.ControlParameters.Count == 0 || 
        !uiHint.ControlParameters.Keys.Contains("ValueList"))
        throw new InvalidOperationException(String.Format(
            "ValuesList for FieldTemplate {0} field is missing from UIHint",
            Column.Name));

    var valuesList = ValuesListAttribute(
        uiHint.ControlParameters["ValueList"].ToString());
    if (valuesList.Count() == 0)
        throw new InvalidOperationException(String.Format(
            "ValuesList for FieldTemplate {0} field, is empty",
            Column.Name));

    listControl.Items.AddRange(valuesList);
}

Listing 2 – PopulateListControl

In Listing 2 you can see the extraction of the ValuesList from the UIHint’s ControlParameters collection.

So Listings 1 & 2 will get you the same as the previous article but without the new attribute.

Take 2

In take two of this control binh said “But would you change a little to handle to have combobox with value and display value. The Value will be save to database and The Display value will be showed to user.” so I thought I would add this version here.

My personal view is this should be done either via an FK relationship or a Enum value. (Both my Your First FieldTemplate and Dynamic Data Preview 4 have an Enum FieldTemplate) but here goes.

In the Edit FieldTemplate this is all you need to do is modify the ValuesList method.

public ListItem[] GetValuesList(String values)
{
    var items = values.Split(new char[] { ',', ';' });
    var listItems = (from item in items
                     select new ListItem()
                     {
                         Text = item.Split(new char[] { '|' })[1],
                         Value = item.Split(new char[] { '|' })[0]
                     }).ToArray();
    return listItems;
}
Listing 3 – updated ValuesListAttribute
[MetadataType(typeof(Value.Metadata))]
partial class Value
{
    internal class Metadata
    {
        public object Id { get; set; }
        [UIHint("ValuesList", null, "ValueList", "1|Y,2|N,3|N/A")]
        public object TestR { get; set; }
        [UIHint("ValuesList", null, "ValueList", "1|Y,2|N,3|Other")]
        public object Test { get; set; }
    }
}

Listing 4 – sample metadata

Here you can see that the values and text are seperated by the pipe symbol ‘|’. However having done this you would now need to create a ValuesList (ReadOnly) FieldTemplate to get the ValuesList and the match the value in the field and then display the correct value, which in my opinion would be quite messy, so here I will stick to using Enums.

Download

Wednesday, 15 July 2009

Securing Dynamic Data Preview 4 Refresh – Part 3

Continuing from the previous article Securing Dynamic Data Preview 4 Refresh – Part 2  we will proceed to complete the series by finishing off the hyperlinks so you have the option of them all showing as disabled or all being hidden.

The reasoning behind this extra bit to the series (if you can call two articles a series) is I don’t like

  • Dead hyperlinks when you mouse over you get the hyperlink action i.e. underline.
  • I like consystancy i.e. some links hidden and some shown as dead I want it all to be the same.

So to complete this we will add a new web user control called DynamicHyperLink.ascx which will wrap the asp:DynamicHyperlink control.

%@ Control 
    Language="C#" 
    AutoEventWireup="true" 
    CodeBehind="DynamicHyperLink.ascx.cs" 
    Inherits="DD_EF_SecuringDynamicData.DynamicData.DynamicHyperLink" %>

<asp:DynamicHyperLink 
    ID="DynamicHyperLink1" 
    runat="server" 
    onprerender="DynamicHyperLink1_PreRender">
</asp:DynamicHyperLink>
<asp:Literal ID="Literal1" runat="server">&nbsp;</asp:Literal>

Listing 1 - DynamicHyperLink.ascx

public partial class DynamicHyperLink : System.Web.UI.UserControl
{
    public String Action { get; set; }
    public String Text { get; set; }
    public String CssClass { get; set; }
    public Boolean ShowText { get; set; }
    public String DisabledClass { get; set; }

    protected void Page_Init(object sender, EventArgs e)
    {
        DynamicHyperLink1.Action = Action;
        DynamicHyperLink1.Text = Text;
        DynamicHyperLink1.CssClass = CssClass;
    }

    /// <summary>
    /// Handles the PreRender event of the DynamicHyperLink1 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>
    protected void DynamicHyperLink1_PreRender(object sender, EventArgs e)
    {
        // the DynamicHyperLink is considered disabled if it has no URL
        if (String.IsNullOrEmpty(DynamicHyperLink1.NavigateUrl))
        {
            DynamicHyperLink1.Visible = false;
            Literal1.Visible = false;
            if (ShowText)
            {
                Literal1.Visible = true;
                Literal1.Text = String.Format(
                    "<span class=\"{0}\">{1}</span>&nbsp;", 
                    DisabledClass, 
                    Text);
            }
        }
    }
}

Listing 2 - DynamicHyperLink.ascx.cs

With the DynamicHyperLink web user control we simply have some properties to allow us to pass in the main properties of the asp:DynamicHyperLink Action, Text and CssClass. The last two properties ShowText and DisbledClass are used:

  • ShowText – to show the Text property in a span when the DynamicHyerLink is hidden.
  • DisbledClass – is the css class to use when ShowText is true.

So this is the way it works:

When the DynamicHyperLink’s NavigateUrl is and empty string or null then the DynamicHyperLink is in the disabled state. In the disabled state if ShowText is false then no control is displayed when in a disabled state, and when ShowText is true as span is displayed surrounding the Text property and having the DisabledCalss css as the span’s class.

<%@ Control 
    Language="C#" 
    AutoEventWireup="true" 
    CodeBehind="DeleteLink.ascx.cs" 
    Inherits="DD_EF_SecuringDynamicData.DeleteLink" %>
<asp:LinkButton 
    ID="LinkButton1" 
    runat="server" 
    CommandName="Delete" Text="Delete"
    OnClientClick='return confirm("Are you sure you want to delete this item?");' />
<asp:Literal ID="Literal1" runat="server">&nbsp;</asp:Literal>

Listing 3 – DeleteHyperLink.ascx

public partial class DeleteHyperLink : System.Web.UI.UserControl
{
    public Boolean ShowText { get; set; }
    public String CssClass { get; set; }
    public String DisabledClass { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        LinkButton1.CssClass = CssClass;

        // get restrictions for the current
        // users access to this table
        var table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
        var usersRoles = Roles.GetRolesForUser();
        var tableRestrictions = table.Attributes.OfType<SecureTableAttribute>();
        if (tableRestrictions.Count() == 0)
            return;

        foreach (var tp in tableRestrictions)
        {
            // the LinkButton is considered disabled if delete is denied.
            if (tp.HasAnyRole(usersRoles) &&
                (tp.Restriction & TableDeny.Delete) == TableDeny.Delete)
            {
                LinkButton1.Visible = false;
                LinkButton1.OnClientClick = null;
                LinkButton1.Enabled = false;
                Literal1.Visible = false;
                if (ShowText)
                {
                    Literal1.Visible = true;
                    Literal1.Text = String.Format(
"<span class=\"{0}\">Delete</span>&nbsp;",
DisabledClass); } } } } }

Listing 4 – DeleteHyperLink.ascx.cs

This is pretty similar to the DynamicHyperLink.ascx the main difference being how the LinkButton is determined to be disabled, this is done by the foreach loop checking each restriction on the current table and checking to see if it is TableDeny.Delete and if so setting the disabled state.

Download

Note: This has an ASPNETDB database which requires SQL Express 2008 and a connection to Northwind you will need to edit the connection string for Northwind.

Happy coding HappyWizard

Tuesday, 14 July 2009

Securing Dynamic Data Preview 4 Refresh – Part 2

Continuing from the previous article Securing Dynamic Data Preview 4 Refresh – Part 1 we will proceed to complete the second two items in the to do list below:

Things we will need to Do

  • Dynamic Data Route Handler
  • Remove Delete Link from List and Details pages
  • Secure Meta model classes
  • Make columns read only using Entity Templates.

Secure Meta model classes

It would have been nice if I could have overridden the Scaffold and IsReadOnly methods of the MetaColumn class for this there would have been less code peppered around Dynamic Data but we can hope for the future.

public class SecureMetaModel : MetaModel
{
    /// <summary>
    /// Creates the metatable.
    /// </summary>
    /// <param name="provider">The metatable provider.</param>
    /// <returns></returns>
    protected override MetaTable CreateTable(TableProvider provider)
    {
        return new SecureMetaTable(this, provider);
    }
}

Listing 1 – SecureMetaModel class

public class SecureMetaTable : MetaTable
{
    /// <summary>
    /// Initializes a new instance of the <see cref="SecureMetaTable"/> class.
    /// </summary>
    /// <param name="metaModel">The meta model.</param>
    /// <param name="tableProvider">The table provider.</param>
    public SecureMetaTable(
        MetaModel metaModel, 
        TableProvider tableProvider) :
        base(metaModel, tableProvider) { }

    protected override void Initialize()
    {
        base.Initialize();
    }

    /// <summary>
    /// Gets the scaffold columns.
    /// </summary>
    /// <param name="mode">The mode.</param>
    /// <param name="containerType">Type of the container.</param>
    /// <returns></returns>
    public override IEnumerable<MetaColumn> GetScaffoldColumns(
        DataBoundControlMode mode, 
        ContainerType containerType)
    {
        return from column in base.GetScaffoldColumns(mode, containerType)
               where column.SecureColumnVisible()
               select column;
    }
}

Listing 2 – SecureMetaTable class

/// <summary>
/// Secures the column visible.
/// </summary>
/// <param name="column">The column.</param>
/// <returns></returns>
public static Boolean SecureColumnVisible(this MetaColumn column)
{
    var userRoles = Roles.GetRolesForUser();
    var activeDenys = column.GetColumnPermissions(userRoles);
    if (activeDenys.Contains(ColumnDeny.Read))
        return false;
    else
        return true;
}

Listing 3 – SecureColumnVisible extension method

[Flags]
public enum ColumnDeny
{
    Read    = 1,
    Write   = 2,
}

Listing 4 – ColumnDeny enum

So in the above four listings we have the simplified solution to hide columns based on user roles.

How it works

Listing 1 is required to let us include the SecureMetaTable in the default model Listing 2 is the SecureMetaTable all we do here is filter the columns based on user roles see Listing 3 SecureColumnVisible which hides columns based on ColumnDeny.Read this very easily and cleanly done thanks to the ASP.Net team and letting us derive from the meta classes.

Make columns read only using Entity Templates

Now to make columns read only in Edit or Insert modes based on use roles, for this we will modify tow of the default EntityTemplates Default_Edit.ascx.cs and Default_Insert.ascx.cs in these template we add the code in listing 5 to the DynamicControl_Init event handler.

if (currentColumn.SecureColumnReadOnly())
    dynamicControl.Mode = DataBoundControlMode.ReadOnly;
else
    dynamicControl.Mode = DataBoundControlMode.Edit; //Insert for the insert template
Listing 5 – Code to make a field read only in Edit or Insert modes
protected void DynamicControl_Init(object sender, EventArgs e)
{
    DynamicControl dynamicControl = (DynamicControl)sender;
    dynamicControl.DataField = currentColumn.Name;

    if (currentColumn.SecureColumnReadOnly())
        dynamicControl.Mode = DataBoundControlMode.ReadOnly;
    else
        dynamicControl.Mode = DataBoundControlMode.Edit; //Insert for the insert template
}

Listing 6 – finished DynamicControl_Init for the Edit Entity Template

/// <summary>
/// Secures the column read only.
/// </summary>
/// <param name="column">The column.</param>
/// <returns></returns>
public static Boolean SecureColumnReadOnly(this MetaColumn column)
{
    var userRoles = Roles.GetRolesForUser();
    var activeDenys = column.GetColumnPermissions(userRoles);
    if (activeDenys.Contains(ColumnDeny.Write))
        return true;
    else
        return false;
}

Listing 7 – SecureColumnReadOnly extension method

/// <summary>
/// Get a list of permissions for the specified role
/// </summary>
/// <param name="attributes">
/// Is a AttributeCollection taken 
/// from the column of a MetaTable
/// </param>
/// <param name="role">
/// name of the role to be matched with
/// </param>
/// <returns>A List of permissions</returns>
public static List<ColumnDeny> GetColumnPermissions(this MetaColumn column, String[] roles)
{
    var permissions = new List<ColumnDeny>();

    // you could put: 
    // var attributes = column.Attributes;
    // but to make it clear what type we are using:
    System.ComponentModel.AttributeCollection attributes = column.Attributes;

    // check to see if any roles passed
    if (roles.Count() > 0)
    {
        // using Linq to Object to get 
        // the permissions foreach role
        permissions = (from a in attributes.OfType<SecureColumnAttribute>()
                       where a.HasAnyRole(roles)
                       select a.Permission).ToList();
    }
    return permissions;
}

Listing 8 – GetColumnPermissions extension method

The above code Listings 5 & 6 simply test to see if the column is restricted to read only based on users roles and uses Listing 7 & 8 extension methods to achieve this.

And finally to make this work with Dynamic Data we need to modify the Global.asax

public class Global : System.Web.HttpApplication
{
    private static MetaModel s_defaultModel = new SecureMetaModel();
    public static MetaModel DefaultModel
    {
        get
        {
            return s_defaultModel;
        }
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        DefaultModel.RegisterContext(
            typeof(Models.NorthwindEntities), 
            new ContextConfiguration() { ScaffoldAllTables = true });

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

    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

Listing 9 – adding the SecureMetaModel to the Globalasax

Once we have a declared  our metamodel property in the Global.asax we can just reference it for the app by using it to register the context.

Download

Note: This has an ASPNETDB database which requires SQL Express 2008 and a connection to Northwind you will need to edit the connection string for Northwind.

I’m working on better hyperlinks for another post to follow shortly, these hyperlinks will offer the option of:

  • Hiding the link if it is disabled
  • Showing plain text if disabled

via an property at design time.

Monday, 13 July 2009

Securing Dynamic Data Preview 4 Refresh – Part 1

This article is another stab at creating a simple framework to add a simple security layer to Dynamic Data. This time I’ve based my first level of security on the sample posted by Veloce here Secure Dynamic Data Site. And getting column level security using the Great Buried Sample in Dynamic Data Preview 4 – Dynamic Data Futures I found last month.

Like my previous security layers for Dynamic Data I’m going to use a permissive system because you have to add these attributes to the metadata classes (and that can be a laborious task) and so I though is would be better under these circumstances to just remove access at individual tables and columns, rather than having to add attributes to every table and column to set the security level.

Things we will need to Do

  • Dynamic Data Route Handler
  • Remove Delete Link from List and Details pages
  • Secure Meta model classes
  • Make columns read only using Entity Templates.

Dynamic Data Route Handler

Firstly again we must thank Veloce for his Secure Dynamic Data Site see his blog for morebits (pun intended) of Dynamic Data goodness. So what I decided to do was cut out a load of stuff from his example and pare it down to something that is easy to modify and understand.

/// <summary>
/// The SecureDynamicDataRouteHandler enables the 
/// user to access a table based on the following:
/// the Roles and TableDeny values assigned to 
/// the SecureTableAttribute.
/// </summary>
public class SecureDynamicDataRouteHandler : DynamicDataRouteHandler
{
    public SecureDynamicDataRouteHandler() { }

    /// <summary>
    /// Creates the handler.
    /// </summary>
    /// <param name="route">The route.</param>
    /// <param name="table">The table.</param>
    /// <param name="action">The action.</param>
    /// <returns>An IHttpHandler</returns>
    public override IHttpHandler CreateHandler(
        DynamicDataRoute route,
        MetaTable table,
        string action)
    {
        var usersRoles = Roles.GetRolesForUser();
        var tableRestrictions = table.Attributes.OfType<SecureTableAttribute>();

        // if no permission exist then full access is granted
        if (tableRestrictions.Count() == 0)
            return base.CreateHandler(route, table, action);

        foreach (var tp in tableRestrictions)
        {
            if (tp.HasAnyRole(usersRoles))
            {
                // if any action is denied return no route
                if ((tp.Restriction & TableDeny.Read) == TableDeny.Read)
                    return null;
                if ((tp.Restriction & TableDeny.Write) == TableDeny.Write &&
                    ((action == "Edit") || (action == "Insert")))
                    return null;
            }
        }

        return base.CreateHandler(route, table, action);
    }
}

Listing 1 – SecureDynamicDataRouteHandler

This route handler is called each time a route is evaluated see listing 2 where we have added RouteHandler = new SecureDynamicDataRouteHandler() to the default route.

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

Listing 2 – Default route in Global.asax.cs

Now look at the CreateHandler method of Listing 1 1st we get users roles and the tables permissions, then if the table has no restrictions we just return a handler from the base DynamicDataRouteHandler class. After this we check each table restriction to see if this user is in one of the roles in the restriction, then is the user has one of the roles in the restriction we check the restrictions (most restricting first) for a match and then deny the route by returning null appropriately.

[Flags]
public enum TableDeny
{
    Read    = 1,
    Write   = 2,
    Delete  = 4,
}

[Flags]
public enum DenyAction
{
    Delete = 0x01,
    Details = 0x02,
    Edit = 0x04,
    Insert = 0x08,
    List = 0x10,
}

Listing 3 – Security enums

Note: You don’t need to have the values appended to the enum i.e. Delete = 0x01 but it’s worth noting that if you don’t set the first value to 1 it will default to 0 and any failed result will match 0 i.e. tp.Restriction & DenyAction.List if enum then even it tp.Restriction does not AND with DenyAction.List the result will be 0

Listing 3 shows the security enums used in this sample however the DenyAction is not used I include it here as an option I considered in place of TableDeny enum. Let me explain you could replace the code inside the foreach loop of the route handler with Listing 4.

// alternate route handler code
if ((tp.Restriction & DenyAction.List) == DenyAction.List &&
    action == "List")
    return null;
if ((tp.Restriction & DenyAction.Details) == DenyAction.Details &&
    action == "Details")
    return null;
if ((tp.Restriction & DenyAction.Edit) == DenyAction.Edit &&
    action == "Edit")
    return null;
if ((tp.Restriction & DenyAction.Insert) == DenyAction.Insert &&
    action == "Insert")
    return null;  

Listing 4 – alternate route handler code

This would allow you to deny individual actions instead of Read or Write as in basic form of the route handler.

Note: You should also note the use of the [Flags] attribute on the enums as this allows this sort of declaration in the metadata:
[SecureTable(TableDeny.Write | TableDeny.Delete, "Sales")]
which is the reason why we have the test in the form of:
(tp.Restriction & DenyAction.List) == DenyAction.List 
and not
tp.Restriction == DenyAction.List

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class SecureTableAttribute : System.Attribute
{
    // this property is required to work with "AllowMultiple = true" ref David Ebbo
    // As implemented, this identifier is merely the Type of the attribute. However, 
    // it is intended that the unique identifier be used to identify two 
    // attributes of the same type.
    public override object TypeId { get { return this; } }

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="permission"></param>
    /// <param name="roles"></param>
    public SecureTableAttribute(TableDeny permission, params String[] roles)
    {
        this._permission = permission;
        this._roles = roles;
    }

    private String[] _roles;
    public String[] Roles
    {
        get { return this._roles; }
        set { this._roles = value; }
    }

    private TableDeny _permission;
    public TableDeny Restriction
    {
        get { return this._permission; }
        set { this._permission = value; }
    }

    /// <summary>
    /// helper method to check for roles in this attribute
    /// the comparison is case insensitive
    /// </summary>
    /// <param name="role"></param>
    /// <returns></returns>
    public Boolean HasRole(String role)
    {
        // call extension method to convert array to lower case for compare
        String[] rolesLower = _roles.AllToLower();
        return rolesLower.Contains(role.ToLower());
    }
}

Listing 5 -  SecureTableAttribute

The TableDenyAttribute is strait forward two properties and a methods to check if a roles is in the Roles property.

public static class SecurityExtensionMethods
{
    /// <summary>
    /// Returns a copy of the array of string 
    /// all in lowercase
    /// </summary>
    /// <param name="strings">Array of strings</param>
    /// <returns>array of string all in lowercase</returns>
    public static String[] AllToLower(this String[] strings)
    {
        String[] temp = new String[strings.Count()];
        for (int i = 0; i < strings.Count(); i++)
        {
            temp[i] = strings[i].ToLower();
        }
        return temp;
    }

    /// <summary>
    /// helper method to check for roles in this attribute
    /// the comparison is case insensitive
    /// </summary>
    /// <param name="roles"></param>
    /// <returns></returns>
    public static Boolean HasAnyRole(this SecureTableAttribute tablePermission, String[] roles)
    {
        var tpsRoles = tablePermission.Roles.AllToLower();
        // call extension method to convert array to lower case for compare
        foreach (var role in roles)
        {
            if (tpsRoles.Contains(role.ToLower()))
                return true;
        }
        return false;
    }
}

Listing 6 – some extension methods

These extension methods in Listing 6 are used to make the main code more readable.

Remove Delete Link from List and Details pages

I’m including this with this first article because it will give you a complete solution at table level.

<%@ Control 
    Language="C#" 
    AutoEventWireup="true" 
    CodeBehind="DeleteButton.ascx.cs" 
    Inherits="DD_EF_SecuringDynamicData.DeleteButton" %>
<asp:LinkButton 
    ID="LinkButton1" 
    runat="server" 
    CommandName="Delete" Text="Delete"
    OnClientClick='return confirm("Are you sure you want to delete this item?");' />

Listing 7 – DeleteButton.ascx

public partial class DeleteButton : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var table = DynamicDataRouteHandler.GetRequestMetaTable(Context);

        var usersRoles = Roles.GetRolesForUser();
        var tableRestrictions = table.Attributes.OfType<SecureTableAttribute>();
        if (tableRestrictions.Count() == 0)
            return;

        foreach (var tp in tableRestrictions)
        {
            if (tp.HasAnyRole(usersRoles) &&
                (tp.Restriction & TableDeny.Delete) == TableDeny.Delete)
            {
                LinkButton1.Visible = false;
                LinkButton1.OnClientClick = null;
                LinkButton1.Enabled = false;
            }
        }
    }
}

Listing 8 – DeleteButton.ascx.cs

This user control in Listing 8 is used to replace the delete button on the List.aspx and Details.aspx pages, this code is very similar to the code in the route handler. We first check each restriction to see if the user is in one of its roles and then if the restriction is TableDeny.Delete and then disable the Delete button.

<ItemTemplate>
    <table id="detailsTable" class="DDDetailsTable" cellpadding="6">
        <asp:DynamicEntity runat="server" />
        <tr class="td">
            <td colspan="2">
                <asp:DynamicHyperLink 
                    runat="server" 
                    Action="Edit" 
                    Text="Edit" />
                <uc1:DeleteButton 
                    ID="DetailsItemTemplate1" 
                    runat="server" />
            </td>
        </tr>
    </table>
</ItemTemplate>

Listing 9 – Details.aspx page

<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:DynamicHyperLink 
                runat="server" 
                ID="EditHyperLink" 
                Action="Edit" 
                Text="Edit"/>&nbsp;
            <uc1:DeleteButton 
                ID="DetailsItemTemplate1" 
                runat="server" />&nbsp;
            <asp:DynamicHyperLink 
                ID="DetailsHyperLink" 
                runat="server" 
                Text="Details" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

Listing 10 – List.aspx page

<%@ Register src="../Content/DeleteButton.ascx" tagname="DeleteButton" tagprefix="uc1" %>

You will also need to add this line after the Page directive at the top of both the List.aspx and Details.aspx pages.

Note: I will present a slightly more complex version of this hyperlink user control in the next article which will allow the any hyperlink  as an option to remain visible but be disabled.

And that’s it for this article next we will look at using the Great Buried Sample in Dynamic Data Preview 4 – Dynamic Data Futures I mentioned earlier to allow us to hide column based on user’s roles and also add the feature to make columns read only based on user’s roles.

Wednesday, 8 July 2009

Dynamic Data Custom Field Template – Values List

Here I have created a simple FieldTemplate for a recent project to allow you to give the user a predefined set of text values to choose from without a FK field relationship. An example of this could be a field with optional values of ‘Y’, ‘N’, ‘N/A’ or ‘Y’, ‘N’, ‘Other’ etc.

Requirements

  • Custom Attribute
  • Custom FieldTemplate

I have cover attributes many time on this blog so I’ll just post the code here:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValuesListAttribute : Attribute
{
    public ValuesListAttribute() { }

    /// <summary>
    /// Construvtor take a list of values
    /// to show in the ListControl
    /// </summary>
    /// <param name="values">
    /// A ',' or ';' seperated list of values in the order
    /// that they should appear in the list control.
    /// </param>
    public ValuesListAttribute(String values)
    {
        var items = values.Split(new char[] { ',', ';' });
        Values = (from item in items
                  select new ListItem()
                  {
                      Text = item,
                      Value = item
                  }).ToArray();
    }

    public ListItem[] Values { get; set; }
}

Listing 1 – ValuesListAttribute

[MetadataType(typeof(Value.Metadata))]
partial class Value
{
    internal class Metadata
    {
        public object Id { get; set; }
        [UIHint("ValuesList")]
        [ValuesList("Y,N,N/A")]
        public object TestR { get; set; }
        [UIHint("ValuesList")]
        [ValuesList("Y,N,Other")]
        public object Test { get; set; }
    }
}

Listing 2 – sample metadata

So now to the FieldTemplate we don’t need to have two versions ValuesList and ValuesList_Edit as the data type we will be using this on is always text so the ValuesList version will automatically use the standard Text FieldTemplate.

<%@ Control 
    Language="C#" 
    CodeBehind="ValuesList_Edit.ascx.cs" 
    Inherits="DD_ValuesListFieldTemplate.ValuesList_EditField" %>

<asp:DropDownList 
    ID="DropDownList1" 
    runat="server" 
    CssClass="droplist">
</asp:DropDownList>

<asp:RequiredFieldValidator 
    runat="server" 
    ID="RequiredFieldValidator1" 
    CssClass="droplist" 
    ControlToValidate="DropDownList1" 
    Display="Dynamic" 
    Enabled="false" />

Listing 3 – ValuesList_Edit.ascx

public partial class ValuesList_EditField : System.Web.DynamicData.FieldTemplateUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SetUpValidator(RequiredFieldValidator1);

        if (DropDownList1.Items.Count == 0)
        {
            // add [Not Set] in insert mode as the field would
            // otherwise just take on the first value in the list
            // if the user clicks save without changing it.
            if (!Column.IsRequired || Mode == DataBoundControlMode.Insert)
            {
                DropDownList1.Items.Add(new ListItem("[Not Set]", ""));
            }

            // fill the dropdown list with the 
            // values in the ValuesList attribute
            PopulateListControl(DropDownList1);
        }
    }

    /// <summary>
    /// Populates a list control with all the values from a parent table.
    /// </summary>
    /// <param name="listControl">The list control to populate.</param>
    protected new void PopulateListControl(ListControl listControl)
    {
        var uiHint = Column.GetAttribute<UIHintAttribute>();
        if (uiHint == null || uiHint.ControlParameters.Count == 0 || !uiHint.ControlParameters.Keys.Contains("ValueList"))
            throw new InvalidOperationException(String.Format(
                "ValuesList for FieldTemplate {0} field is missing from UIHint",
                Column.Name));

        var valuesList = ValuesListAttribute(uiHint.ControlParameters["ValueList"].ToString());
        if (valuesList.Count() == 0)
            throw new InvalidOperationException(String.Format(
                "ValuesList for FieldTemplate {0} field, is empty",
                Column.Name));

        listControl.Items.AddRange(valuesList);
    }

    public ListItem[] ValuesListAttribute(String values)
    {
        var items = values.Split(new char[] { ',', ';' });
        var listItems = (from item in items
                         select new ListItem()
                         {
                             Text = item,
                             Value = item
                         }).ToArray();
        return listItems;
    }

    // added page init to hookup the event handler
    protected override void OnDataBinding(EventArgs e)
    {
        if (Mode == DataBoundControlMode.Edit)
        {
            ListItem item = DropDownList1.Items.FindByValue(FieldValueString);
            if (item != null)
                DropDownList1.SelectedValue = FieldValueString;
        }

        if (Mode == DataBoundControlMode.Insert)
            DropDownList1.SelectedIndex = 0;

        base.OnDataBinding(e);
    }

    /// <summary>
    /// Provides dictionary access to all data in the current row.
    /// </summary>
    /// <param name="dictionary">The dictionary that contains all the new values.</param>
    protected override void ExtractValues(IOrderedDictionary dictionary)
    {
        // If it's an empty string, change it to null
        string val = DropDownList1.SelectedValue;
        if (val == String.Empty)
            val = null;

        dictionary[Column.Name] = ConvertEditedValue(val);
    }

    /// <summary>
    /// Gets the data control that handles the data field in a field template.
    /// </summary>
    /// <value></value>
    /// <returns>
    /// A data control that handles the data field in a field template.
    /// </returns>
    public override Control DataControl
    {
        get
        {
            return DropDownList1;
        }
    }
}

Listing 4 – ListValues_Edit.ascx.cs FieldTemplate

The FieldTemplate has a RequiredFieldValidator on it in case the field is required but as the user will be choosing from a list non of the other valuators make sense. Also note in the extract values method the value is replaced with null if an empty string is selected (the default in insert so no value will be added if the user does not explicitly select one.

In PopulateListControl we have replaced the base class FieldTemplateUserControl’s PopulateListControl with our own that will use the values passed into via the ValuesListAttribute (which is required for the FieldTemplate to function).

So there you have it a simple custom FieldTemplate for those situations where the database either uses a field with the values ‘Y’ and ‘N’ instead of a bit field or where you just want the user to choose from a simple list of possible cases.

Download