Tuesday, November 4, 2008

Using dictionaries for constant Identifiers

I wanted to have a constant string so that I could have a list of roles, however I also wanted to have a friendly description, so how do you go about this? The reason for using a constant string is so that we are consistent when we are checking our roles. e.g.
if (_user.IsInRole(Role.Practitioner))
. . .

But what happens when you want to get a friendly description too? Well firstly I wanted to be able to put all the roles I had defined into a drop down list, so it would be nice if all the roles were defined in one place. So I wanted to be able to do this

// Put the roles in the role dropdownlist
RoleDropDownList.DataSource = Role.Roles;
RoleDropDownList.DataTextField = "Value";
RoleDropDownList.DataValueField = "Key";
RoleDropDownList.Items.Insert(0, new ListItem("All", ""));

So how do we do it? Simply use a dictionary. Have the key be the constant string and the value a friendly description. Now the important point to note here is that we could be tempted to use StringDictionary as it is a specialization of a Dictionary, but if you look carefully in the documentation, the key will be converted to a lower case string and that *is not what we want*.

/// <summary>
These are the membership roles that users can have
/// </summary>
public static class Role
/// <summary>A basic user (frozen user)</summary>
public const string Basic = "Basic";

/// <summary>A standard practitioner</summary>
public const string Practitioner = "Practitioner";

/// <summary>An IP administrator</summary>
public const string Administrator = "Administrator";

/// <summary>A training manager</summary>
public const string TrainingManager = "TrainingManager";

/// <summary>A submissions manager</summary>
public const string SubmissionManager = "SubmissionManager";

/// <summary>A submission assessor</summary>
public const string Assessor = "Assessor";

public const string Mentor = "Mentor";

/// <summary>
Create a friendly description of each role
/// </summary>
public static Dictionary<String, String> Roles
= new Dictionary<String, String>()
{ Basic, "Frozen User" },
{ Practitioner, "Practitioner" },
{ Administrator, "Administrator" },
{ TrainingManager, "Training Manager" },
{ SubmissionManager, "Submission Manager" },
{ Assessor, "Assessor"},
{ Mentor, "Mentor"}