Click here to Skip to main content
Licence CPOL
First Posted 21 Oct 2006
Views 10,696
Bookmarked 10 times

Type Safe Role Names

By | 21 Oct 2006 | Article
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:

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

Then, define a RoleNames class like this:

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:

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)

About the Author

aanodide

Web Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 21 Oct 2006
Article Copyright 2006 by aanodide
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid