Showing posts with label Nucleus. Show all posts
Showing posts with label Nucleus. Show all posts

Wednesday, November 10, 2010

Visual Studio 2010: ASP.NET ControlBuilder MakeGeneric Workaround

Working with enumerations is very code friendly and we use them often especially when we are referencing a lookup table.  The ORM that we use (LLBLGen Pro) released its latest version recently and they make it even easier for us to map an enumeration to an entity field.

Sometimes these lookup tables need to be presented to the end user for whatever reason - be it a drop down, radio button list or a check box list.  When working in VS 2008 I stumbled onto this blog that outlines a straight forward way to create a generic drop down that exposes the the selected value as the specified generic Enum. Using that approach, we centralized all of the enum parsing that goes on for the gets and sets when working with the selected items. We took that implementation and created a generic dropdown and checkbox list.  It worked great in our environment at the time which was Visual Studio 2008.

Here is the checkbox list control that we were using:
public class EnumCheckBoxList<T> : EnumCheckBoxList where T : struct
{
    public List<T> SelectedEnumValues
    {
        get
        {
            List<T> items = new List<T>(base.Items.Count);
            foreach (ListItem item in base.Items)
            {
                if (item.Selected)
                    items.Add((T)Enum.Parse(typeof(T), item.Value));
            }
            return items;
        }
        set
        {
            base.ClearSelection();

            foreach (T item in value)
                base.Items.FindByValue(Enum.GetName(typeof(T), item)).Selected = true;
        }
    }

    /// <summary>
    /// Only valid for use on bit flagged enumerations
    /// </summary>
    public T? SelectedFlaggedEnumValues
    {
        get
        {
            ulong values = 0;
            foreach (ListItem item in base.Items)
            {
                if (item.Selected)
                    values = values | Convert.ToUInt64((T)Enum.Parse(typeof(T), item.Value));
            }
            return values == 0 ? null : (T?)Enum.Parse(typeof(T), values.ToString());
        }
        set
        {
            if (value != null)
            {
                Type enumType = typeof(T);
                foreach (Enum e in Enum.GetValues(enumType))
                {
                    ulong singleEnumFromFlagResult = 0;
                    if ((singleEnumFromFlagResult = (Convert.ToUInt64(e) & Convert.ToUInt64(value.Value))) > 0)
                    {
                        Enum singleEnumFromFlag = (Enum)Enum.Parse(enumType, singleEnumFromFlagResult.ToString());
                        base.Items.FindByValue(Enum.GetName(enumType, singleEnumFromFlag)).Selected = true;
                    }
                }
            }
        }
    }
}

[ControlBuilder(typeof(EnumCheckBoxListControlBuilder))]
public partial class EnumCheckBoxList : CheckBoxList
{
    public string EnumTypeName { get; set; }
}

public class EnumCheckBoxListControlBuilder : ControlBuilder
{
    public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id,
                              System.Collections.IDictionary attribs)
    {

        string enumTypeName = (string)attribs["EnumTypeName"];
        Type enumType = Type.GetType(enumTypeName);
        if (enumType == null)
            throw new Exception(string.Format("Type for enum {0} can not be created", enumTypeName));

        Type dropDownType = typeof(EnumCheckBoxList<>).MakeGenericType(enumType);
        base.Init(parser, parentBuilder, dropDownType, tagName, id, attribs);
    }
}

Today our new development is done primarily in Visual Studio 2010.  We needed the same functionality for the generic dropdown and checkbox list for our Nucleus project but upon bringing over our implementation we discovered that the ControlBuilder wasn't updating the .designer file - so our controls weren't being converted to their generic implementations. After a little Googling, I found a bug entered in Microsoft Connect that described the issue we are having with VS 2010 and it seems that there isn't any workaround currently available for our situation using the ControlBuilder implementation.

The generic control was nice because programmers wouldn't have to go back and forth suppling plumbing to parse string values into enumerations and vise versa. We took the same idea and instead created a few extension methods.  The extension methods shown below have a get and set defined for a list of enumeration values and also a get and set for enumerations that are decorated with the FlagsAttribute.

/// <summary>
/// Get the selected enumeration values in the listbox
/// </summary>
/// <typeparam name="T">The type of enumeration represented in the listbox</typeparam>
/// <param name="list">The listbox</param>
/// <returns>Returns the list of selected enumeration values in the listbox</returns>
public static List<T> GetSelectedEnumValues<T>(this ListControl list) where T : struct
{
    List<T> items = new List<T>(list.Items.Count);
    foreach (ListItem item in list.Items)
    {
        if (item.Selected)
            items.Add((T)Enum.Parse(typeof(T), item.Value));
    }
    return items;
}

/// <summary>
/// Select the values in the given list of enums in the listbox.
/// </summary>
/// <typeparam name="T">The type of enumeration represented in the listbox</typeparam>
/// <param name="list">The listbox</param>
/// <param name="valuesToSelect">The enum values to select in the listbox</param>
public static void SetSelectedEnumValues<T>(this ListControl list, List<T> valuesToSelect) where T : struct
{
    list.ClearSelection();

    foreach (T item in valuesToSelect)
        list.Items.FindByValue(Enum.GetName(typeof(T), item)).Selected = true;
}

/// <summary>
/// Get the selected enumeration values in the listbox. This method should be called if the enumeration is decorated with the Flags attribute.
/// </summary>
/// <typeparam name="T">The type of enumeration represented in the listbox. This enumeration must be decorated with the Flags attribute</typeparam>
/// <param name="list">The listbox</param>
/// <returns>Returns the selected enumeration values in the listbox as a flagged enumeration. If no values are selected, null is returned</returns>
public static T? GetSelectedFlaggedEnumValues<T>(this ListControl list) where T : struct
{
    ulong values = 0;
    foreach (ListItem item in list.Items)
    {
        if (item.Selected)
            values = values | Convert.ToUInt64((T)Enum.Parse(typeof(T), item.Value));
    }
    return values == 0 ? null : (T?)Enum.Parse(typeof(T), values.ToString());
}

/// <summary>
/// Select the values in the given flag enumeration in the listbox.
/// </summary>
/// <typeparam name="T">The type of enumeration represented in the listbox. This enumeration must be decorated with the Flags attribute</typeparam>
/// <param name="list">The listbox</param>
/// <param name="valuesToSelect">The enum values (represented as Flags) to select in the listbox</param>
public static void SetSelectedFlaggedEnumValues<T>(this ListControl list, T valuesToSelect) where T : struct
{
    list.ClearSelection();

    Type enumType = typeof(T);
    foreach (Enum e in Enum.GetValues(enumType))
    {
        ulong singleEnumFromFlagResult = 0;
        if ((singleEnumFromFlagResult = (Convert.ToUInt64(e) & Convert.ToUInt64(valuesToSelect))) > 0)
        {
            Enum singleEnumFromFlag = (Enum)Enum.Parse(enumType, singleEnumFromFlagResult.ToString());
            list.Items.FindByValue(Enum.GetName(enumType, singleEnumFromFlag)).Selected = true;
        }
    }
}

Hopefully Microsoft responds to the Connect bug with a fix in an upcoming service pack.  In the mean time these extension methods will do the trick.

Links

Monday, October 25, 2010

New Project - Welcome Scrum

Before today, we were working in an informal agile process with fairly short development cycles. We work as a team but often developers would be unaware of new features that others were working on. A big problem with this is that it makes it difficult for another team member to pick up where someone left off.

Enter our new project, code name Nucleus.  Dave and I have been planning for a few months the vision and features of the project and we formally kicked it off today - Hooray!  We were introduced to a new project process called Scrum through Visual Studio 2010 and Telerik's Team Pulse product.  Scrum is an agile practice that gets the entire team involved in nearly the entire process from planning to tasks to conducting demos of the work completed.

With our first stab of Scrum, we will start with the following 2 week Sprint Schedule.
  • Day 1: Sprint Planning Meetings
    • Part I (4 hours max): Participants include Product Owner and Scrum Master
      • Determine focus of the Sprint and flag possible Sprint Backlog items
    • Part I (4 hours max): All Team Members participate
      • Discuss in detail each flagged Sprint Backlog item
        • Use Scrum Poker to estimate effort
      • Determine actual Sprint Backlog and assign work to team members
  • Day 2-10: Daily Sprint Meeting (15 minute max)
    • Team members answer:
      • What have you done since the last meeting?
      • What will you do from now until the next meeting?
      • Is there anything holding up your work?
  • Day 6: Requirements Planning (4 hour max)
      • Participants include Product Owner and Scrum Master
        • Add and edit the Product backlog
        • Additional stakeholders may be invited
  • Day 10: Sprint Review and Retrospective (4 hour max)
    • Demo functionality added from the Sprint.
    • Reflect on the Sprint to determine what worked, what didn't work and what would we change in the next Sprint.
Additionally we sprinkled into Sprint a few formal code reviews.

We had an outstanding Day 1 in our first ever Sprint.  We played a little Scrum Poker, talked about backlog items and by the end of the day we all had our tasks outlined for the rest of the Sprint.

Links