Active Directory group lookup function failing

mhme

New Member
Help! I've been trying to write a function that will confirm a user's membership in an Active Directory group, and while it works if the member happens to be in the group, it throws an exception if the user is not.Here is the function:\[code\]private bool IsUserMemberOfGroup(string user, string group){ using (var ctx = new PrincipalContext(ContextType.Domain)) using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, group)) using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, user)) { if (groupPrincipal == null) { return false; } else { return userPrincipal.IsMemberOf(groupPrincipal); } }}\[/code\]And here is the YSOD:Server Error in '/' Application. Unknown error (0x80005000) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: Unknown error (0x80005000)
Source Error:
\[code\] Line 34: elseLine 35: {Line 36: return userPrincipal.IsMemberOf(groupPrincipal);Line 37: }Line 38: }\[/code\] I don't know if it's related, but when I step through the function, groupPrincipal.Members.Count throws an exception of type "System.NullReferenceException", with Count.Base shows an exception with the message "Object reference not set to instance of an object".What the heck's going on? Why won't a bool named IsMemberOf just return false when someone's not a member?Thanks,Daniel
 
Back
Top