In the following article we discussed extending the user interface of the CreateUserWizard:
Extending Wizard Steps in CreateUserWizard
And then in this article we discussed saving the custom properties (profiles) in the database for each user:
Saving the Custom User Data from CreateUserWizard via Profiles
Now let’s discuss how to attach a role to the newly created user.
In general, you will not let the user pick the role. You, as the administrator of the site, will define a set of roles for the site; for example, the roles could be: admin, user, manager, marketinguser, financeuser, generalmanager, etc. Each of these roles will have certain privileges associated with it.
Typically you will create these roles using the ASP.Net Web Site Administration Tool. A role is a simple string that is a stand-in for a set of tasks.
Figure 1. Web Site Administration Tool
Attaching a Role
Attaching a role to a user is as simple as using Roles.AddUserToRole method as shown in Listing 1. This code also shows adding profile properties to a user.
Code Listing 1. Attaching a Role
/// Save the profile properties after the user has been created.
/// <param name="sender"></param>
/// <param name="e"></param>
protected void cuwCreateUser_CreatedUser(object sender, EventArgs e)
// Update the profile values
ProfileCommon userProfile = (ProfileCommon) ProfileCommon.Create(cuwCreateUser.UserName, true);
userProfile.FirstName = ((TextBox)cuwCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("FirstName")).Text;
userProfile.LastName = ((TextBox)cuwCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("LastName")).Text;
userProfile.Company = ((TextBox)cuwCreateUser.CreateUserStep.ContentTemplateContainer.FindControl("Company")).Text;
// Save the values
// Attach a role
In the above code, we are using the Roles static class. This class has a whole bunch of static methods – AddUsersToRole, AddUsersToRoles, AddUserToRole, AddUserToRoles, RemoveUserFromRole, and so on. Since this is a static class, we can use these methods without instantiating the class.
Roles in the Database
Finally, let’s take a look at how the role information is stored in the database.
Figure 2. Roles Database Diagram
As you can see, the many-to-many relationship between roles and users is resolved by the aspnet_UsersInRole table. Via the users table, the roles table is connected to membership, personalization, and profile tables.