Easy default roles for new users with the CreateUserWizard

Here's a scenario for you: You have an admin panel and you want to let the administrators of the site create extra admin accounts when they need to. Your site uses asp.net membership and roles and you need an easy way to make sure the new admin is added to the administrator role at creation.

To implement this on your site you only need a couple of lines of code.

  1. Open the page in your admin panel which has the CreateUserWizard in it.
  2. Make sure that you have disabled automatic login for newly created users.
  3. Single click on the CreateUserWizard in design view.
  4. Bring the properties window up by pressing F4 if its not already visible.
  5. Click the lightning rod to view the events.
  6. Double click on the CreatedUser event.
  7. Put the code from the event below into your newly created event.
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    CreateUserWizard cuw = (CreateUserWizard)sender;

    string RoleToJoin = "Administrator";

    if (!Roles.IsUserInRole(cuw.UserName, RoleToJoin))
        Roles.AddUserToRole(cuw.UserName, RoleToJoin);

If your Roles isn't lighting up then you are missing a reference to the System.Web.Security namespace which can be added by inserting the following code into the top of your code-behind:

using System.Web.Security;
kick it on DotNetKicks.com Shout it

No comments :