using System;
using Telerik.Security.ActiveDirectory;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.DirectoryServices;
public class CustomRoleProvider : TelerikADRoleProvider
{
public override string[] GetRolesForUser(string userName)
{
DirectoryEntry searchRoot = new DirectoryEntry(this.ADConnectionString, this.ADUserName, this.ADPassword, this.AuthType);
DirectorySearcher userSearcher = new DirectorySearcher(searchRoot, String.Format(this.UserSearchFilter, userName));
List<string> groupsList = new List<string>();
DirectoryEntry userEntry = null;
try
{
SearchResult userResult = userSearcher.FindOne();
userEntry = userResult.GetDirectoryEntry();
}
catch (System.Runtime.InteropServices.COMException)
{
// problem occured with the LDAP query, manage the expection if you like
throw;
}
if (userEntry != null)
{
StringBuilder groupsFilter = new StringBuilder();
groupsFilter.Append("(|");
userEntry.RefreshCache(new string[] { "tokenGroups" });
foreach (byte[] sid in userEntry.Properties["tokenGroups"])
{
groupsFilter.AppendFormat("(objectSid={0})", BuildFilterOctetString(sid));
}
groupsFilter.Append(")");
List<string> result = new List<string>();
using (searchRoot)
{
DirectorySearcher groupsSearcher = new DirectorySearcher(searchRoot, groupsFilter.ToString());
try
{
SearchResultCollection groupsCollection = groupsSearcher.FindAll();
foreach (SearchResult sr in groupsCollection)
{
result.Add(sr.Properties["samAccountName"][0].ToString());
}
}
catch (System.Runtime.InteropServices.COMException)
{
// problem occured with the LDAP query, manage the expection if you like
throw;
}
}
return result.ToArray();
}
else
return new string[0];
}
private string BuildFilterOctetString(byte[] bytes)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
result.AppendFormat(
"\\{0}",
bytes[i].ToString("X2")
);
}
return result.ToString();
}
}