Last post Dec 22, 2005 12:27 PM by dunnry
Dec 20, 2005 03:43 PM|von g thep|LINK
Before I add a user to a group how would I check if the user already is a member?
Dec 20, 2005 05:47 PM|scommisso|LINK
You can run an AD query searching for that user and then check and see if that group is listed as part of the 'memberOf' property.
Here's an example function you can use:
Function GetPropertyArray(ByVal user
As String =
returnStr = New
Dim i As
Integer = 0
For Each oObject
returnStr(i) = CStr(oObject)
i += 1
The 'user' parameter is going to be the DirectoryEntry objects in the DirectoryEntryCollection returned by DirectorySearcher.FindAll(), property name, in your case, is going to be "memberOf".
If you want to see how to search, check out a few of the posts in here... I have some of my source code in this post:
Dec 21, 2005 10:00 AM|dunnry|LINK
Dec 21, 2005 04:57 PM|von g thep|LINK
Instead of making a roundtrip across the network to check if they are a member and then adding the member (2 network trips), you can just add and catch the error. If you check the error # you should be able to determine if the user was already there and
just swallow it. This way you have 1 network trip in the normal code path and 1 network trip + 1 handled exception in the other.
It might not make much of a difference for small number of group additions, but if this process is doing it a lot, it might help out with performance.
Can you provide me an example of how to "catch and swallow" the exception? I'm not sure how to do this.
Dec 22, 2005 12:27 PM|dunnry|LINK
catch (DirectoryServicesCOMException dsEx) //v2.0
if (dsEx.ExtendedError != ALREADYINGROUP)
throw; //gulp, we just ate ALREADYINGROUP error
catch (COMException cEx) //v1.x
if (cEx.ErrorCode != ALREADYINGROUP)
throw; //yummy, we just swallowed ALREADYINGROUP
I don't know offhand what ALREADYINGROUP error code is, but you can just catch the exception and look at the number to figure it out. I have shown two different catches depending
on which version of the framework you are using.