using …

Pure C#

‘Enum’ Kategorisi için Arşiv

FieldInfo.IsStatic Property

Yazan: esersahin 06/10/2009

http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.isstatic(VS.80).aspx

using System;
using System.Reflection;

// Make two fields.
public class Myfielda
{
    private string field = “A private field”;
    public string Field
    {
        get{return field;}
        set{if(field!=value){field=value;}}
    }
}
public class Myfieldb
{
    static string field = “B private static field”;
    public string Field
    {
        get{return field;}
        set{if(field!=value){field=value;}}
    }
}
 
public class Myfieldinfo
{
    public static int Main()
    {
        Console.WriteLine(“\nReflection.FieldInfo”);
        Myfielda Myfielda = new Myfielda();
        Myfieldb Myfieldb = new Myfieldb();
 
        // Get the Type and FieldInfo.
        Type MyTypea = typeof(Myfielda);
        FieldInfo Myfieldinfoa = MyTypea.GetField(“field”, BindingFlags.NonPublic|BindingFlags.Instance);
        Type MyTypeb = typeof(Myfieldb);
        FieldInfo Myfieldinfob = MyTypeb.GetField(“field”, BindingFlags.NonPublic|BindingFlags.Static);
 
        // For the first field, get and display the name, field, and IsStatic property value.
        Console.Write(“\n{0} – “, MyTypea.FullName);
        Console.Write(“{0}; “, Myfieldinfoa.GetValue(Myfielda));
        Console.Write(“IsStatic – {0}”, Myfieldinfoa.IsStatic);
 
        // For the second field get and display the name, field, and IsStatic property value.
        Console.Write(“\n{0} – “, MyTypeb.FullName);
        Console.Write(“{0}; “, Myfieldinfob.GetValue(Myfieldb));
        Console.Write(“IsStatic – {0}”, Myfieldinfob.IsStatic);
 
        return 0;
    }
}

Yazı kategorisi: Enum, FieldInfo | » yorum bırak;

FieldInfo Class

Yazan: esersahin 06/10/2009

http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo(VS.80).aspx

C#
using System;
using System.Reflection;

public class FieldInfoClass
{
    public int myField1 = 0;
    protected string myField2 = null;
    public static void Main()
    {
        FieldInfo[] myFieldInfo;
        Type myType = typeof(FieldInfoClass);
        // Get the type and fields of FieldInfoClass.
        myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
            | BindingFlags.Public);
        Console.WriteLine("\nThe fields of " +
            "FieldInfoClass are \n");
        // Display the field information of FieldInfoClass.
        for(int i = 0; i < myFieldInfo.Length; i++)
        {
            Console.WriteLine("\nName            : {0}", myFieldInfo[i].Name);
            Console.WriteLine("Declaring Type  : {0}", myFieldInfo[i].DeclaringType);
            Console.WriteLine("IsPublic        : {0}", myFieldInfo[i].IsPublic);
            Console.WriteLine("MemberType      : {0}", myFieldInfo[i].MemberType);
            Console.WriteLine("FieldType       : {0}", myFieldInfo[i].FieldType);
            Console.WriteLine("IsFamily        : {0}", myFieldInfo[i].IsFamily);
        }
    }
}

Yazı kategorisi: Enum, FieldInfo | » yorum bırak;

Generic Enum to List converter (C#)

Yazan: esersahin 06/10/2009

http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx

One for the utility library…

Here’s a small function I’ve found to be quite useful recently. It takes an enum type and returns a generic list populated with each enum item.

        public static List<T> EnumToList<T>()
        {
            Type enumType = typeof (T);

            // Can’t use type constraints on value types, so have to do check like this
            if (enumType.BaseType != typeof(Enum))
                throw new ArgumentException(“T must be of type System.Enum”);
            
            Array enumValArray = Enum.GetValues(enumType);

            List<T> enumValList = new List<T>(enumValArray.Length);

            foreach (int val in enumValArray) {
                enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
            }

            return enumValList;
        }

Here’s one of the ways that I’ve used it:

List<DayOfWeek> weekdays =
    EnumHelper.EnumToList<DayOfWeek>().FindAll(
        delegate (DayOfWeek x)
        {
            return x != DayOfWeek.Sunday && x != DayOfWeek.Saturday;
        });

Yazı kategorisi: Enum, List | » yorum bırak;

Enum List DropDown Control

Yazan: esersahin 10/10/2008

http://jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

I’ve been wanting to try this concept out for awhile, and I finally had a reasonable opportunity.  The idea was to slap a System.ComponentModel.Description attribute onto each field of an Enum, and then bind a dropdown list directly to the Enum.

I got it working and the code is pretty concise.  Please excuse the fact that I’m working in VB for this one; it’s my DotNetNuke project, and I was already working in VB to edit some modules.  The code would be even prettier in C# I imagine.

First, let’s decorate an enum. Import System.ComponentModel here.

   1: Public Enum RegionCode
   2:     <Description("-- Select --")> NotSelected = 0
   3:     <Description("US - Midwest")> Midwest = 1
   4:     <Description("US - Northeast")> Northeast = 2
   5:     <Description("US - Southeast")> Southeast = 3
   6:     <Description("US - Southwest")> Southwest = 4
   7:     <Description("US - West")> West = 5
   8:     Canada = 6
   9: End Enum

Next, we need to build a helper routine that can get the description off of a decorated enum field.  It must gracefully handle the case when a description is not specified, as with Canada.

In .NET 3.5, you’d probably want to build these as extension methods, which would be a trivial change.  Import System.ComponentModel here too.

   1: ''' <summary>
   2: ''' Get the Description of an enum value
   3: ''' </summary>
   4: ''' <param name="value"></param>
   5: ''' <returns></returns>
   6: ''' <remarks>If there is no description attribute, the name will be used.</remarks>
   7: Public Function GetDescription(ByVal value As System.Enum) As String
   8:     Return GetDescription(value.GetType().GetField(value.ToString))
   9: End Function
  10:
  11: ''' <summary>
  12: ''' Get the description of a field
  13: ''' </summary>
  14: ''' <param name="field"></param>
  15: ''' <returns></returns>
  16: ''' <remarks>If the field doesn't have a description attribute, the name is used</remarks>
  17: Public Function GetDescription(ByVal field As System.Reflection.FieldInfo)
  18:     ' Get the array of description attributes applied (there will be 0 or 1)
  19:     Dim descriptions() As Object
  20:     descriptions = field.GetCustomAttributes(GetType(DescriptionAttribute), False)
  21:
  22:     ' If there was a description, return it
  23:     If descriptions.Length > 0 Then
  24:         Return DirectCast(descriptions(0), DescriptionAttribute).Description
  25:     End If
  26:
  27:     ' Otherwise return the field's name
  28:     Return field.Name
  29: End Function

Now that we can easily grab the description from an enum field, let’s build ourselves a new dropdown control.

   1: Imports System.Reflection
   2:
   3: ''' <summary>
   4: ''' A custom dropdown that binds to an enum
   5: ''' </summary>
   6: ''' <remarks>
   7: ''' The DataSource is set to an Enum type name, not a collection,
   8: ''' and it can be set within the markup if desired
   9: ''' <example><![CDATA[
  10: '''     <app:EnumList Runat="server" ID="ddlRegion" DataSource="MyApp.RegionCode" />
  11: '''     ...
  12: '''     ddlRegion.DataBind()
  13: '''     ddlRegion.SelectedValue = RegionCode.West
  14: ''' ]]></example>
  15: ''' </remarks>
  16: Public Class EnumList
  17:     Inherits System.Web.UI.WebControls.DropDownList
  18:
  19:     Private _enumType As Type
  20:     ''' <summary>
  21:     ''' Specify the enum type that we'll bind to
  22:     ''' </summary>
  23:     ''' <value></value>
  24:     ''' <returns></returns>
  25:     ''' <remarks></remarks>
  26:     Public Shadows Property DataSource() As String
  27:         Get
  28:             Return _enumType.ToString
  29:         End Get
  30:         Set(ByVal value As String)
  31:             _enumType = System.Type.GetType(value, True, True)
  32:         End Set
  33:     End Property
  34:
  35:     ''' <summary>
  36:     ''' Replace SelectedValue with an Enum-based version
  37:     ''' </summary>
  38:     ''' <value></value>
  39:     ''' <returns></returns>
  40:     ''' <remarks></remarks>
  41:     Public Shadows Property SelectedValue() As System.Enum
  42:         Get
  43:             ' Get the value from the request to allow for disabled viewstate
  44:             Dim RequestValue As String = Me.Page.Request.Params(Me.UniqueID)
  45:
  46:             Return System.Enum.Parse(_enumType, RequestValue)
  47:         End Get
  48:         Set(ByVal value As System.Enum)
  49:             MyBase.SelectedValue = value.ToString
  50:         End Set
  51:     End Property
  52:
  53:     ''' <summary>
  54:     ''' Replace DataBind so that we can bind to the list of fields in the
  55:     ''' enum.  Call our GetDescription function for each one to get the
  56:     ''' text to display.
  57:     ''' </summary>
  58:     ''' <remarks></remarks>
  59:     Public Overrides Sub DataBind()
  60:         Me.Items.Clear()
  61:         Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Static
  62:
  63:         For Each field As FieldInfo In _enumType.GetFields(flags)
  64:             Me.Items.Add(New ListItem(GetDescription(field), field.Name))
  65:         Next
  66:     End Sub
  67:
  68: End Class

The usage is quite simple, as the example in the comment shows.  Here’s the markup for the control:

   1: <app:EnumList Runat="server" ID="ddlRegion" DataSource="MyApp.RegionCode" />

And in the code-behind, it’s wired up as follows:

   1: ddlRegion.DataBind()
   2: ddlRegion.SelectedValue = RegionCode.West

Here’s the result.  I chose to have the value of the dropdown be the enum field name rather than its value, because that felt cleaner.

image

   1: <select name="dnn$ctr396$ManageJobs$ddlRegion" id="dnn_ctr396_ManageJobs_ddlRegion">
   2:     <option value="NotSelected">-- Select --</option>
   3:     <option value="Midwest">US - Midwest</option>
   4:     <option value="Northeast">US - Northeast</option>
   5:     <option value="Southeast">US - Southeast</option>
   6:     <option value="Southwest">US - Southwest</option>
   7:     <option selected="selected" value="West">US - West</option>
   8:     <option value="Canada">Canada</option>
   9: </select>

I suspect that there are going to be some goofy bugs in here if this was hit with some complex scenarios.  But fortunately for me, this project won’t have any complex scenarios.

Yazı kategorisi: Enum | » yorum bırak;

Extending the DropDownList to Support Enums

Yazan: esersahin 10/10/2008

Introduction -> http://aspalliance.com/1514_Extending_the_DropDownList_to_Support_Enums.all

A fairly common task in some of the applications I work with is to provide a user with a DropDownList of options that is populated by an enum.  This can easily be done with a little bit of code to bind a stock DropDownList control to the enum, but this kind of thing quickly starts to violate the DRY (Don’t Repeat Yourself) principle, so I created a simple derived DropDownList control that takes advantage of Generics to make it especially effective and require less code and casting of data types.

Binding a Standard DropDownList to an Enum

Before we delve into the derived DropDownList, consider the code that it is meant to replace.  Let’s say that we have an enum that describes Status, and has possible values of Active, Inactive, Pending, and Declined.  We’ll say these are for Proposal, so we’ll call the enum ProposalStatus.

Listing 1: ProposalStatus enum

public enum ProposalStatus
{
  Active =1,
  Inactive = 2,
  Pending = 3,
  Declined = 4
}

Now if we want to render a DropDownList that uses this enum as its data source, we would use code like the following:

Listing 2: Binding Names to DropDownList

if (!Page.IsPostBack)
{
  ProposalStatusDropDownList.DataSource = 
  Enum.GetNames(typeof(ProposalStatus));
  ProposalStatusDropDownList.DataBind();
}

This will render a DropDownList with display and value both as the name of the enum – the value is not stored in the DropDownList.  To get at the value, you would use code like this:

Listing 3: Getting a Strongly Typed Enum Value from the DropDownList

protected void Button1_Click(object sender, EventArgs e)
{
  ProposalStatus myStatus = (ProposalStatus)Enum.Parse(
    typeof(ProposalStatus), ProposalStatusDropDownList.SelectedValue);
  Label1.Text = myStatus.ToString();
}

Of course, if you actually want to store the enum’s numeric value as the value of the DropDownList, the most effective way to achieve that is to load up a SortedList<int,string> with the values and their corresponding names, and then DataBind to this collection.  This is easily done with a helper method like the one shown in Listing 4.  Note that since we cannot use where T:System.Enum the best we can do is constrain T to be a struct and then do a type check in code to verify it inherits from Enum.

Listing 4: Convert Enum to SortedList<string,int> Collection

public static SortedList<stringint> GetEnumDataSource<T>() where T:struct
{
    Type myEnumType = typeof(T);
    if (myEnumType.BaseType != typeof(Enum))
    {
        throw new ArgumentException("Type T must inherit from System.Enum.");
    }

    SortedList<stringint> returnCollection = new SortedList<stringint>();
    string[] enumNames = Enum.GetNames(myEnumType);
    for (int i = 0; i < enumNames.Length; i++)
    {
        returnCollection.Add(enumNames[i],
            (int)Enum.Parse(myEnumType, enumNames[i]));
    }
    return returnCollection;
}

Then to use this method with a DropDownList we would use code like what is shown in Listing 5.

Listing 5: Bind to SortedList from Enum

ProposalStatusDropDownList2.DataSource =
GetEnumDataSource<ProposalStatus>();
ProposalStatusDropDownList2.DataValueField = "Value";
ProposalStatusDropDownList2.DataTextField = "Key";
ProposalStatusDropDownList2.DataBind();
Creating a Generic Enum DropDownList

Now that we’ve written a bunch of code to show how anybody can do this to a stock DropDownList control, let’s roll all of this code into a single reusable control, the EnumDropDownList.  One additional requirement we’ll add to this control is that it optionally include a ListItem that simple displays “All” and has no associated enum value.  We’ll use this when the DropDownList is being used to display filters on search results or reports, and in this case the “All” value will mean that we don’t want to filter by this enum.  Similarly, to make our filtering easier, we’ll also include a nullable integer property, SelectedIntegerValue, since the data access layer is going to expect integer values for the statuses we choose to filter on (or null if none).  The control will include the GetEnumDataSource<T> method shown earlier, and of course this could be refactored out into a separate utility class where it would make more sense.  I’ve included it in EnumDropDownList to make the sample easier to follow.  The complete source for EnumDropDownList is shown in Listing 6.

Listing 6: EnumDropDownSource

public class EnumDropDownList<T> : DropDownList where T : struct
{
    private bool _showAllOption = true;
    public bool ShowAllOption
    {
        get
        {
            return _showAllOption;
        }
        set
        {
            _showAllOption = value;
        }
    }
    public new T? SelectedValue
    {
        get
        {
            if (String.IsNullOrEmpty(this.SelectedItem.Text))
            {
                return null;
            }
            return (T)Enum.Parse(typeof(T), this.SelectedItem.Text);
        }
    }
    public int? SelectedIntegerValue
    {
        get
        {
            if (ShowAllOption && this.SelectedIndex == 0)
            {
                return null;
            }
            if (String.IsNullOrEmpty(this.SelectedItem.Text))
            {
                return null;
            }
            return (int)Enum.Parse(typeof(T), this.SelectedValue.ToString());
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new ArgumentException("Type T must inherit from System.Enum.");
        }
        BindData();
    }

    protected void BindData()
    {
        this.DataSource = GetEnumDataSource<T>();
        this.DataTextField = "Key";
        this.DataValueField = "Value";
        this.DataBind();
        if (ShowAllOption)
        {
            this.Items.Insert(0, new ListItem("All"""));
        }
    }

    public static SortedList<stringint> GetEnumDataSource<T>() where T : new()
    {
        Type myEnumType = typeof(T);
        if (myEnumType.BaseType != typeof(Enum))
        {
            throw new ArgumentException("Type T must inherit from System.Enum.");
        }

        SortedList<stringint> returnCollection = new SortedList<stringint>();
        string[] enumNames = Enum.GetNames(myEnumType);
        for (int i = 0; i < enumNames.Length; i++)
        {
            returnCollection.Add(enumNames[i],
                (int)Enum.Parse(myEnumType, enumNames[i]));
        }
        return returnCollection;
    }
}

Now to use this control, unfortunately you can’t simply add markup to the ASPX page.  Some options were discussed by Mikhail at Microsoft but I can’t find that anything was ever implemented up through ASP.NET 3.5.  Thus, you can only instantiate this control from your C# or VB code, and then add it to the page using a Placeholder control or similar technique.  This is fairly minor, however, and the resulting code in the page’s codebehind is shown in Listing 7.  PlaceHolder1 is defined on the page where we want the DropDownList to be shown.

Listing 7: Rendering the Control in a PlaceHolder

protected EnumDropDownList<ProposalStatus> ProposalStatusDropDownList1;
protected override void OnInit(EventArgs e)
{
  base.OnInit(e);
  ProposalStatusDropDownList1 = new EnumDropDownList<ProposalStatus>();
  this.PlaceHolder1.Controls.Add(ProposalStatusDropDownList1);
}
Resources

Yazı kategorisi: Enum | » yorum bırak;

DropDownLists with Enums as DataSource

Yazan: esersahin 10/10/2008

http://developcode.blogspot.com/2006/12/dropdownlists-with-enums-as-datasource.html

When creating DropDownLists out of enums in ASP.NET, I often tend to dislike the way the usual examples use the enum’s Values and Names as keys and values for the DropDownList. In this example, I have created an enhanced enum using DescriptionAttribute instead. This way, you can go a lot further on deciding what the visible values in a DropDownList may be – without being tied to a C# type name syntax.

This way, you can get these kinds of DropDownLists using pure enums only:

Step 1 – Enhance your enums with the Description:


using System.ComponentModel;

public enum CourierCompanies
{
[Description("Please select a courier company")]
None = -1,

[Description("Other")]
Other = 0,

[Description("DHL")]
DHL,

[Description("Action Courier")]
ActionCourier,

[Description("American Courier Express")]
ACE

}


Step 2: Create a helper class which extracts description data both for each enum value and a key/value pair for use in DataSources:


using System.ComponentModel;
using System.Reflection;

public class EnumDescription
{
/// <summary>
/// Get the description attribute for one enum value
/// </summary>
/// <param name=”value”>>Enum value
/// <returns>The description attribute of an enum, if any</returns>
public static string GetDescription(Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}

/// <summary>
/// Gets a list of key/value pairs for an enum, using the description attribute as value
/// </summary>
/// <param name=”enumType”>>typeof(your enum type)
/// <returns>A list of KeyValuePairs with enum values and descriptions</returns>
public static List<KeyValuePair;<string, string>> GetValuesAndDescription(System.Type enumType)
{
List<KeyValuePair><string, string>> kvPairList = new List<KeyValuePair<string, string>>();

foreach (Enum enumValue in Enum.GetValues(enumType))
{
kvPairList.Add(new KeyValuePair<string,string>(enumValue.ToString(), GetDescription(enumValue)));
}

return kvPairList;
}
}


Step 3: Fill the DropDownList using the enum itself as a DataSource:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCourier.DataSource = EnumDescription.GetValuesAndDescription(typeof(CourierCompanies));
ddlCourier.DataTextField = “Value”;
ddlCourier.DataValueField = “Key”;
ddlCourier.DataBind();
}
}

The reason for using the names “Value” and “Key” is that the properties of the generic KeyValuePair type are “Value” and “Key”.

Yazı kategorisi: Enum | » yorum bırak;