Implementation:
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Web;
using System.Configuration;
public class CurrentUser
{
public static UserPrincipal User
{
get
{
return UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), Username);
}
}
public static PrincipalSearchResult Groups
{
get
{
return User.GetAuthorizationGroups();
}
}
public static string Username
{
get { return HttpContext.Current.User.Identity.Name.Split('\\')[1]; }
}
}
Helper Class:
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
public static class ActiveDirectory
{
public static IEnumerable GetGroups(string name)
{
var context = new PrincipalContext(ContextType.Domain);
var group = new GroupPrincipal(context) { Name = "*" + name + "*", IsSecurityGroup = true};
var searcher = new PrincipalSearcher(group);
var results = searcher.FindAll();
return results.OrderBy(x => x.Name).Cast().ToList();
}
public static IEnumerable GetUsers(string name)
{
var context = new PrincipalContext(ContextType.Domain);
var user = new UserPrincipal(context) { DisplayName = "*" + name + "*", Enabled = true };
var searcher = new PrincipalSearcher(user);
var results = searcher.FindAll();
return results.OrderBy(x => x.DisplayName).Cast().ToList();
}
public static IEnumerable GetUsersByGroup(string name)
{
return GetGroup(name).Members.Cast().ToList();
}
public static UserPrincipal GetUser(string username)
{
return UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), username);
}
public static GroupPrincipal GetGroup(string name)
{
return GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), name);
}
public static UserPrincipal GetUserByGuid(string guid)
{
return UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), IdentityType.Guid, guid.ToGuid().ToString());
}
public static UserPrincipal GetUserByDisplayName(string displayName)
{
var context = new PrincipalContext(ContextType.Domain);
var user = new UserPrincipal(context) { DisplayName = displayName, Enabled = true };
var searcher = new PrincipalSearcher(user);
return (UserPrincipal) searcher.FindOne();
}
}
No comments:
Post a Comment