15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

550 ❘ ChaPTer 21 security<br />

For using roles, you also need to implement a role provider. The class SampleRoleProvider derives from<br />

the base class RoleProvider <strong>and</strong> implements the methods GetRolesForUser() <strong>and</strong> IsUserInRole():<br />

using System;<br />

using System.Collections.Specialized;<br />

using System.Web.Security;<br />

namespace Wrox.ProCSharp.Security<br />

{<br />

public class SampleRoleProvider: RoleProvider<br />

{<br />

internal static string ManagerRoleName = "Manager".ToLowerInvariant();<br />

internal static string EmployeeRoleName = "Employee".ToLowerInvariant();<br />

public override void Initialize(string name, NameValueCollection config)<br />

{<br />

base.Initialize(name, config);<br />

}<br />

public override void AddUsersToRoles(string[] usernames,<br />

string[] roleNames)<br />

{<br />

throw new NotImplementedException();<br />

}<br />

// override abstract RoleProvider members<br />

// ...<br />

public override string[] GetRolesForUser(string username)<br />

{<br />

if (string.Compare(username,<br />

SampleMembershipProvider.ManagerUserName, true) == 0)<br />

{<br />

return new string[] { ManagerRoleName };<br />

}<br />

else if (string.Compare(username,<br />

SampleMembershipProvider.EmployeeUserName, true) == 0)<br />

{<br />

return new string[] { EmployeeRoleName };<br />

}<br />

else<br />

{<br />

return new string[0];<br />

}<br />

}<br />

}<br />

}<br />

public override bool IsUserInRole(string username, string roleName)<br />

{<br />

string[] roles = GetRolesForUser(username);<br />

foreach (var role in roles)<br />

{<br />

if (string.Compare(role, roleName, true) == 0)<br />

{<br />

return true;<br />

}<br />

}<br />

return false;<br />

}<br />

code snippet AppServices/SampleRoleProvider.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!