Using the ASP.Net membership provider in a Windows forms application part 3.
In my last two blog
entries I showed how to use the ASP.Net membership provider in a Windows
application. Now that we can add a validate users we might want to start using
roles as well. To work with security roles we need to use the class
System.Web.Security.Roles. This class works pretty much in the same way as the
Membership provider. To add a new role we use the CreateRole() function and to
associate a user with this role we use the AddUserToRole() function. So adding
the Developer role to my previously created user account can be done with the
following code:
Roles.CreateRole("Developer")
Roles.AddUserToRole("Maurice",
"Developer")
However if you try this you will receive an error: “The Role
Manager feature has not been enabled.”. To enable roles we need to add
one more thing to the app.config. Add following line to the <system.web> section:
<roleManager enabled="true" />
Once this is done you are ready to add roles and associate users with
there roles.
Use the following code to check if a user has a specific role:
If Roles.IsUserInRole("Maurice", "Developer") Then
Console.WriteLine("Is a
developer.")
Else
Console.WriteLine("Doesn't
write code.")
End If
Of course this leaves us with a place to store the current user name so
we know which user is logged in when we need to check for a specific role. The
IsUserInRole() function has an additional overload that takes only a single
parameter, the role name. Next time more about how to use this overload.
Maurice de Beijer
www.TheProblemSolver.nl