Click here to Skip to main content
15,883,922 members
Articles / Web Development / ASP.NET

Type Safe Role Names

Rate me:
Please Sign up or sign in to vote.
1.53/5 (5 votes)
21 Oct 2006CPOL 15.9K   10  
A way to let the compiler stop you from mistyping role names.

Introduction

It seems to me that using the Roles.XXX methods are prone to error because they take strings as arguments. You could mistype a string and be screwed. Even if you use a class that encapsulates the strings, you could still screw up by not using that class.

I propose using type safe wrapper functions to the Role.XXX functions.

Implementation

First, define all your roles in an enum:

C#
public enum Roles : int
{
    SuperAdmin = 0,
    TrialNeedsActivation,
    Trial,
    Admin,
    Operator
}

Then, define a RoleNames class like this:

C#
public static class RoleNames
{
    private static readonly string[] _roles = Enum.GetNames(typeof(Roles));
    public static string Get(Roles r)
    {
        return _roles[(int)r];
    }
}

Finally, define wrapper classes like this:

C#
public static void RemoveUserFromRole(string user, Roles role)
{
    Roles.RemoveUserFromRole(user, RoleNames.Get(role));
}

public static void AddUserToRoles(string user, Roles[] roles)
{
    List<STRING> rolestrings = new List<STRING>();

    foreach (Roles r in roles)
    {
        rolestrings.Add(RoleNames.Get(r));
    }

    Roles.AddUserToRoles(user, rolestrings.ToArray());
}

public static void AddUserToRole(string user, Roles role)
{
    Roles.AddUserToRole(user, RoleNames.Get(role));
}

Conclusion

Now when you write your code, the compiler will force a correct role name.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --