Created
April 4, 2014 15:28
-
-
Save damonjmurray/9977078 to your computer and use it in GitHub Desktop.
The ActiveDirectoryService class in its original state, before refactoring.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ActiveDirectoryService | |
{ | |
private const string GroupNotFoundMessage = "The directory group, '{0}', could not be found."; | |
private const string UserNotFoundMessage = "The user account, '{0}', could not be found "; | |
private readonly string _adDomain; | |
public ActiveDirectoryService(string domain) | |
{ | |
_adDomain = domain; | |
} | |
public bool IsMember(string accountName, string groupName) | |
{ | |
using (var context = new PrincipalContext(ContextType.Domain, _adDomain)) | |
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName)) | |
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, accountName)) | |
{ | |
if (group == null) | |
throw new NoMatchingPrincipalException(string.Format(GroupNotFoundMessage, groupName)); | |
if (user == null) | |
throw new NoMatchingPrincipalException(string.Format(UserNotFoundMessage, accountName)); | |
return user.IsMemberOf(group); | |
} | |
} | |
public void AddUserToGroup(string accountName, string groupName) | |
{ | |
using (var context = new PrincipalContext(ContextType.Domain, _adDomain)) | |
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName)) | |
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, accountName)) | |
{ | |
if (group == null) | |
throw new NoMatchingPrincipalException(string.Format(GroupNotFoundMessage, groupName)); | |
if (user == null) | |
throw new NoMatchingPrincipalException(string.Format(UserNotFoundMessage, accountName)); | |
group.Members.Add(user); | |
group.Save(); | |
} | |
} | |
public void RemoveUserFromGroup(string accountName, string groupName) | |
{ | |
using (var context = new PrincipalContext(ContextType.Domain, _adDomain)) | |
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName)) | |
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, accountName)) | |
{ | |
if (group == null) | |
throw new NoMatchingPrincipalException(string.Format(GroupNotFoundMessage, groupName)); | |
if (user == null) | |
throw new NoMatchingPrincipalException(string.Format(UserNotFoundMessage, accountName)); | |
group.Members.Remove(user); | |
group.Save(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment