RSS

Monthly Archives: May 2011

System.Enum Methods Summary

GetNames
Get all the names of the enum in string type.

GetValues
Get all the values of the enum in whatever the underlying enum type.

Parse
Convert string type to whatever the underlying enum type.

To do explicit conversion from underlying enum type to enum can be achieved by casting the enum type. For example:

public enum ReasonOptOut
{
    TooMuchEmail = 1,
    DontLikeService,
    NoLongerInterested,
    JustBecause,
    YouDontNeedToKnow
}
int reason = 2
(ReasonOptOut)reason

The above code will return ReasonOptOut.DontLikeService

 
Leave a comment

Posted by on May 16, 2011 in General

 

Tags: ,

TechChallenge: Extensibility in Bitwise Technique to Store Data

The application has a form with 10 check boxes. The value of the check boxes are: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512. These check boxes are stored in a database table, in a column with integer data type. The way these check boxes stored is using bitwise technique. So, if check box 1 and 2 are checked, the value stored in database is 3 (1 | 2 = 3). If check box 2 and 4 are checked, the value stored is 6 (2 | 4 = 6).

Some of the conditions / situations are:
– there is existing data in database table.
– the solution shall be able to handle previous existing data as well as new ones.
– try to avoid database schema changes.
– when the data is queried, bitwise operation ‘AND’ is used to find out which of the checkboxes are being checked.

What is the best design architecture approach if we want to expand this form to include 20 more check boxes?

 
Leave a comment

Posted by on May 16, 2011 in General

 

Tags: ,

Get Dynamically Generated Item from CheckBoxList on Post Back in ASP.Net

In the case where CheckBoxList’s items are dynamically generated and bound to the control, we will need to generate and bind the data source on initialization page life cycle. This is so that we can get CheckBoxList control’s value on post back.

This is my code to add ListItem to my CheckBoxList

protected override void OnInit(EventArgs e)
{
    SortedDictionary<string, int> conditions = new SortedDictionary<string, int>();
    foreach (int conditionValue in Enum.GetValues(typeof(RoadConditions)))
    {
        if (conditionValue != 0)
            conditions.Add(((RoadConditions)conditionValue).ToString(), conditionValue);
    }

    foreach (KeyValuePair<string, int> condition in conditions)
    {
        ListItem conditionListItem = new ListItem(condition.Key, condition.Value.ToString());
        this.cblRoadConditions.Items.Add(conditionListItem);
    }
}

As you can see in the code above, both foreach parts are basically looping through an enumeration object, create ListItem object and populate it with key and value from the enumeration, and add the ListItem to my CheckBoxList called “cblRoadConditions”.

It also applies when you use DataSource and DataBind() to bind to CheckBoxList.

Whichever the approach, this binding part to server control will need to happen in:

protected override void OnInit(EventArgs e)
{
}
 
Leave a comment

Posted by on May 16, 2011 in General

 

Tags: , ,

Add Space to Enum with DescriptionAttribute

As we already know enum can’t contain any string. So what if I want to bind my enum to drop down list but my enum looks like the following:

public enum ReasonOptOut
{
    TooMuchEmail,
    DontLikeService,
    NoLongerInterested,
    JustBecause,
    YouDontNeedToKnow
}

What will happen when I bind this in to a drop down list is, the drop down list will have exact same text like I have in my enum.

I want friendlier names. So, here’s an alternative:

public enum ReasonOptOut
{
    [DescriptionAttribute("Too Much Email")]
    TooMuchEmail,
    Disappointed,
    [DescriptionAttribute("I Don't Like Your Service")]
    DontLikeService,
    [DescriptionAttribute("I am No Longer Interested")]
    NoLongerInterested,
    [DescriptionAttribute("Just Because")]
    JustBecause,
    [DescriptionAttribute("You Don't Need To Know")]
    YouDontNeedToKnow
}

First is to add DescriptionAttribute, or just Description attribute for each enum you want to have friendlier name.

Secondly, add the following code to retrieve Description attribute if available:

Please note that the code below is in Extension Method.

public static class EnumUtilities
{
    public static string GetFriendlyName(this Enum e)
    {
        FieldInfo fieldInfo = e.GetType().GetField(e.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes.Length > 0)
        {
            return attributes[0].Description;
        }
        else
        {
            return e.ToString();
        }
    }
}

To use the code above, you will have to add System.Reflection and System.ComponentModel namespace.

We basically retrieve the Description attribute that contains description for that enum and send back to sender. If there’s no Description defined, the enum’s name will be returned. Here’s how to use it:

ReasonOptOut.DontLikeService.GetFriendlyName();
 
Leave a comment

Posted by on May 12, 2011 in General

 

Tags: ,

Binding Enum to Drop Down List / Server Controls

My enum type:

public enum Status
{
    Submitted = 1,
    Pending,
    Review,
    Processing,
    Approved
}

To bind this to a drop down list, or all other bindable server controls, there are two ways:

Straight Binding

To bind enum type to drop down list in which the value and text of the list item will be the same.

ddStatus.DataSource = Enum.GetNames(typeof(Status));
ddStatus.DataBind();

Value and Text Binding

To bind enum type to drop down list in which the value and text of the list item are different.

foreach (int statusValue in Enum.GetValues(typeof(Status)))
{
    ListItem statusItem = new ListItem(Enum.GetName(typeof(Status), statusValue), statusValue.ToString());
    this.ddStatus.Items.Add(statusItem);
}

This will bind TKey to the drop down’s text and TValue to drop down’s value. Here, I am not calling DataBind() method. Instead, I just loop through the enum type and add it to the drop down list.

You can also loop through the enum and store the name and value in Dictionary<TKey, TValue> or List<T> and bind it to other controls.

If you need to sort the Dictionary<TKey, TValue>, try SortedDictionary

 
1 Comment

Posted by on May 11, 2011 in General

 

Tags: , ,

Sort Dictionary<TKey, TValue>

For those who wondered how to sort your Dictionary<TKey, TValue> type, stop wondering now. You can easily achieve this by using SortedDictionary<TKey, TValue>. The usage is exactly the same as Dictionary<TKey, TValue>.

However, SortedDictionary<TKey, TValue> is sorted only by TKey.

 
Leave a comment

Posted by on May 11, 2011 in General

 

Tags: ,

JSON Array Deserialization in C# With Extension Method

After my first post about Json Serialization and Deserialization, I quickly realize I also need to deserialize object from Json array. Well, the previous code doesn’t work on deserializing Json array. My Json array looks like this:

[ { "firstname": "Alexander", "lastname": "Smith", "email": "asmith@company.com" }, { "firstname": "George", "lastname": "McAllen", "email": "gmcallen@company.com" } ]

The code for deserializing Json array is:

public static List<T> FromJsonArray(this string s)
{
    javaScriptSerializer = new JavaScriptSerializer();

    javaScriptSerializer.Deserialize<List<T>>(s);
}

It pretty much works the same way, only difference is instead of using just T, I use List<T> as return type. Everything else is still the same.

 
3 Comments

Posted by on May 11, 2011 in General

 

Tags: , , ,

 
%d bloggers like this: