Last active
March 18, 2016 04:35
-
-
Save damonjmurray/9977568 to your computer and use it in GitHub Desktop.
The ActiveDirectoryService class after "fudging" generic delegates to eliminate code duplication
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) | |
{ | |
return PerformPrincipalOperation(accountName, groupName, (group, user) => user.IsMemberOf(group)); | |
} | |
public void AddUserToGroup(string accountName, string groupName) | |
{ | |
PerformPrincipalOperation<object>(accountName, groupName, (group, user) => | |
{ | |
group.Members.Add(user); | |
group.Save(); | |
return null; | |
}); | |
} | |
public void RemoveUserFromGroup(string accountName, string groupName) | |
{ | |
PerformPrincipalOperation<object>(accountName, groupName, (group, user) => | |
{ | |
group.Members.Remove(user); | |
group.Save(); | |
return null; | |
}); | |
} | |
private T PerformPrincipalOperation<T>(string accountName, string groupName, | |
Func<GroupPrincipal, UserPrincipal, T> operation) | |
{ | |
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 operation(group, user); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment