As with all things .NET there is more than one way to skin a cat. So it is true with membership. All the tutorials, blogs and books I have gotten my hands on so far have walked us through the nifty little web site administration tool that comes with ASP.NET 2.0. As typical with me, it did not work and really messed up my first crack at a production site.
So I found a new thing, gobal.asax, in particular the Application_Start event. So here is how it goes, first create your inial Roles. Make sure you check to see if it exists first. This is because your application_start event will fire more than once, not often, but multiple times over the course of your site's life.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
If Roles.RoleExists('Administrator') = False Then
If Roles.RoleExists('Manager') = False Then
If IsNothing(Membership.GetUser('Host')) Then
Dim mu As MembershipUser = Membership.CreateUser('Host', 'HostPassword', 'email@example.com')
If Roles.IsUserInRole('Host', 'Administrator') = False Then
If IsNothing(Membership.GetUser('Manager')) Then
Dim mu As MembershipUser = Membership.CreateUser('Manager', 'MgrPwd', firstname.lastname@example.org)
If Roles.IsUserInRole('Manager', 'Manager') = False Then
Catch ex As Exception
OK so loooking at the code I am adding two Roles to the site, Administrator and Manager. So make sure the role does not exist and then add it. The next thing I do i check for some users, Host and Manager (sorry I am not creative with usernames ;)). Again check to see if they exists, then add them to the correct role or if you want Roles. We should also check to see if the user already exists in the role before adding, just to be on the safe site.
I really like this method, because it will always allow me a safe way to get in when the site first launches. I will also periodically check to see if my expected roles and users exists each time the application restarts.
Of course you need to make sure you have your site configured for Membership first before doing this or you will have some problems.