How do I get the users that belong to a group in Active Directory? - vb.net

I have a dropdownlist that I am trying to fill with users that belong to a certain group in Active Directory.
The group name is OverRiders and 8 people are members of this group. More members could be added.
I have the following dropdown but I run the code, the dropdown is blank.
What am I doing wrong?
Please see code:
Private Sub FillDropdown()
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://CN=OverRiders,OU=Departments,DC=domain,DC=com")
Dim osearcher As DirectorySearcher = New DirectorySearcher(oroot)
Dim oresult As SearchResultCollection
Dim result As SearchResult
Dim list As New List(Of String)
osearcher.Filter = "(&(objectCategory=group)(cn={0}))"
' search filter; only display emp with firstname / lastname pair
osearcher.PropertiesToLoad.Add("name") ' member
oresult = osearcher.FindAll()
For Each result In oresult
If Not result.GetDirectoryEntry.Properties("name").Value Is Nothing Then
list.Add(result.GetDirectoryEntry.Properties("name").Value.ToString())
Call list.Sort()
End If
Next
emplist.DataSource = list
emplist.DataBind()
End Sub
I have been able to confirm that the group does exist and the group name is valid.
Thanks a lot in advance

Changed:
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://CN=OverRiders,OU=Departments,DC=domain,DC=com")
to
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://DC=domain,DC=com")
and this:
osearcher.Filter = "(&(objectCategory=group)(cn={0}))"
to this:
osearcher.Filter = "(&(objectCategory=user)(memberOf=CN=overRiders,OU=Departments,DC=domain,DC=com)‌​)"
Everything else remain unchanged.
Hope it helps someone else.

I know this is an old question, but this is what worked for me in a similar situation:
Dim UsersInGroup As New Collection()
Dim de As New DirectoryEntry("LDAP://[Domain]")
Dim MemberSearcher As New DirectorySearcher
With MemberSearcher
.SearchRoot = de
.Filter = "(&(ObjectClass=Group)(CN=" & Group & "))"
.PropertiesToLoad.Add("Member")
End With
Dim mySearchResults As SearchResult = MemberSearcher.FindOne()
For Each User In mySearchResults.Properties("Member")
UsersInGroup.Add(User)
Next

Related

How to retrieve properties for an Active Directory user using DirectorySearcher in VB.Net

I am trying to retrieve the email address for a known Active Directory user by using their login ID and the DirectorySearcher.FindOne() method in VB.Net but I have been unable to get any results.
Sorry but I am new to VB.Net and do not know where I am going wrong. I have tried using various examples that I have found on the net but they all are in C#. I have been able to convert the code to VB but I am still not able to pull results using what I have found. In the latest example I found here! it is using the FindAll() method and putting the results in a SearchResultCollection object. The collection ended up with a count of 0 so I have tried using the FindOne() method and tried to put the result in a SearchResult object. This didn't work for me either.
Public Shared Sub RetrieveUser(ByVal username As String)
Dim propUsername As String = "samaccountname"
Dim propFirstName As String = "givenName"
Dim propLastName As String = "sn"
Dim propDisplayName As String = "cn"
Dim propMail As String = "mail"
Dim propGuid As String = "objectguid"
Dim results As SearchResultCollection
Dim result As SearchResult
Dim directoryEntry As DirectoryEntry = New DirectoryEntry("LDAP_PATH", "DOMIAIN\USERNAME", "PASSWORD", AuthenticationTypes.ServerBind)
Using directorySearcher As DirectorySearcher = New DirectorySearcher(directoryEntry)
directorySearcher.PropertiesToLoad.Add(propUsername)
directorySearcher.PropertiesToLoad.Add(propDisplayName)
directorySearcher.PropertiesToLoad.Add(propFirstName)
directorySearcher.PropertiesToLoad.Add(propLastName)
directorySearcher.PropertiesToLoad.Add(propMail)
directorySearcher.PropertiesToLoad.Add(propGuid)
directorySearcher.Filter = String.Format("({0})", "&(objectClass=user)(cn=" & username & ")")
directorySearcher.SearchScope = SearchScope.Subtree
' directorySearcher.SearchRoot.AuthenticationType = AuthenticationTypes.Secure
directorySearcher.PageSize = 100
'results = directorySearcher.FindAll()
result = directorySearcher.FindOne()
'For Each result In results
If result.Properties.Contains(propUsername) Then
Console.WriteLine("User Name: " & result.Properties(propUsername)(0))
End If
If result.Properties.Contains(propGuid) Then
Console.WriteLine("User GUID: " & BitConverter.ToString(CType(result.Properties(propGuid)(0), Byte())).Replace("-", String.Empty))
End If
If result.Properties.Contains(propMail) Then
Console.WriteLine("Mail ID: " & result.Properties(propMail)(0))
End If
If result.Properties.Contains(propDisplayName) Then
Console.WriteLine("DisplayName: " & result.Properties(propDisplayName)(0))
End If
'Next
directorySearcher.Dispose()
directoryEntry.Dispose()
End Using
End Sub

Adding User to AD Group in VB.Net (2008)

I needed to add users to Active Directory using VB. I found code that works (mostly), except for assigning the user to a group. I'm fairly certain that the code works, I just don't know the format of the group to pass to it.
Given the code (below), and the image of my AD structure (below that), what is the structure of the GroupName passed to the routine to add the user to the group "Level1/All Users/Level 2/A-K"?
TIA
Public Shared Sub AddUserToGroup(ByVal de As DirectoryEntry, ByVal deUser As DirectoryEntry, ByVal GroupName As String)
Dim deSearch As DirectorySearcher = New DirectorySearcher()
deSearch.SearchRoot = de
deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
Dim results As SearchResultCollection = deSearch.FindAll()
Dim isGroupMember As Boolean = False
If results.Count > 0 Then
Dim group As New DirectoryEntry(results(0).Path)
Dim members As Object = group.Invoke("Members", Nothing)
For Each member As Object In CType(members, IEnumerable)
Dim x As DirectoryEntry = New DirectoryEntry(member)
Dim name As String = x.Name
If name <> deUser.Name Then
isGroupMember = False
Else
isGroupMember = True
Exit For
End If
Next member
If (Not isGroupMember) Then
group.Invoke("Add", New Object() {deUser.Path.ToString()})
End If
group.Close()
End If
Return
End Sub
According to your input from your comment I set up this Sub for you.
You havn't clarified the level below Level2 so I just called it Level3.
This function already enables User as a disabled User is useless...
References:
Imports System.DirectoryServices
How to Use:
CreateUser("Doe", "John")
Method:
Public Sub CreateUser(ByVal givenname As String, ByVal surname As String)
Dim dom As New DirectoryEntry()
Dim ou As DirectoryEntry = dom.Children.Find("OU=All Users")
Dim ou2 As DirectoryEntry = ou.Children.Find("OU=Level2")
Dim ou3 As DirectoryEntry = ou2.Children.Find("OU=Level3")
Dim firstLetter As String = givenname.Substring(0, 1)
Dim ou4 As DirectoryEntry
If firstLetter Like "*[A-K]*" Then
ou4 = ou3.Children.Find("OU=A-K")
Else
ou4 = ou3.Children.Find("OU=L-Z")
End If
Dim ADuser As DirectoryEntry = ou4.Children.Add("CN=" & givenname & "\, " & surname, "user")
ADuser.CommitChanges()
'The User is now created. Most people forget to enable their users so I'll put it in here too
'UF_DONT_EXPIRE_PASSWD 0x10000
Dim exp As Integer = CInt(ADuser.Properties("userAccountControl").Value)
ADuser.Properties("userAccountControl").Value = exp Or &H1
ADuser.CommitChanges()
'UF_ACCOUNTDISABLE 0x0002
Dim val As Integer = CInt(ADuser.Properties("userAccountControl").Value)
ADuser.Properties("userAccountControl").Value = val And Not &H2
ADuser.CommitChanges()
End Sub
See my answer in this post for basic knowledge of interaction with AD and LDAP.

vb.net ldap querying 2 domains at same time

I have a program i developed that looks up user info in LDAP and returns it to a listview. It works fine with one domain, when i try to include the second in an IF statement it fails like something is empty in LDAP, which is not blank when i manually check. The logic in my if statement is probably flawed, can someone take a peek?
Dim userIds As IEnumerable(Of String) = {"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8"}
For Each i As String In userids
Dim de As New DirectoryEntry("LDAP://domain1.com:389/DC=domain1,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
Dim res As SearchResultCollection = searcher.FindAll()
If res Is Nothing OrElse res.Count <= 0 Then
Dim tdbfg As New DirectoryEntry("LDAP://domain2.com:389/OU=Users,OU=domain2,DC=domain2,DC=com")
Dim TDLdapFilter As String = "(sAMAccountName=" & i & ")"
Dim TDsearcher As New DirectorySearcher(tdbfg, TDLdapFilter)
Dim TDresult As SearchResult = searcher.FindOne()
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("displayName")(0).ToString())
item.SubItems.Add(result.Properties("title")(0).ToString())
item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
Else
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("displayName")(0).ToString())
item.SubItems.Add(result.Properties("title")(0).ToString())
item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
End If
Next
Basically, if it cant find the userid in the first search, it should look again in the second domain, and return the results. Also, how can i turn this into an ELSEIF statement? I would like to have a third else statement that says if the ids arent found in either domain then "do something".
Thanks!
ahh, had my variables wrong in the else portion!
hope this helps someone else.

vb.net ldap query try catch statement

Ok i have the below code that works, it looks up users that could be a part of 2 domains. The logic works. I wrapped a try-catch statement to catch blanks or users that dont exist. Basically im thinking, ill see an error everytime a user is blank or doesnt exist, ill handle it with a try-catch. Then in my try-catch, im added the ID searched and some text to a listview. It works, but its added a blank line with just the wrong ID and then it adds the line with ID and the text i want. Not sure if my try-catch is in wrong order?
Dim userIds As IEnumerable(Of String) = {"idthatworks", "idthatworks", "doesntwork", "idthatworks", "doesntwork"}
For Each i As String In userIds
Try
Dim de As New DirectoryEntry("LDAP://domain1.net:389/DC=domain1,DC=net")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
Dim res As SearchResultCollection = searcher.FindAll()
If res Is Nothing OrElse res.Count <= 0 Then
Dim tdbfg As New DirectoryEntry("LDAP://domain2.com:389/OU=Users,OU=domain2,DC=domain2,DC=com")
Dim TDLdapFilter As String = "(sAMAccountName=" & i & ")"
Dim TDsearcher As New DirectorySearcher(tdbfg, TDLdapFilter)
Dim TDresult As SearchResult = TDsearcher.FindOne()
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(TDresult.Properties("givenName")(0).ToString())
item.SubItems.Add(TDresult.Properties("cn")(0).ToString())
item.SubItems.Add(TDresult.Properties("userPrincipalName")(0).ToString())
ElseIf Not res.Count <= 0 Then
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("displayName")(0).ToString())
item.SubItems.Add(result.Properties("title")(0).ToString())
item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
End If
Catch ex As Exception
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add("Not found in US or CA Domain")
item.SubItems.Add("Not found in US or CA Domain")
item.SubItems.Add("Not found in US or CA Domain")
End Try
Next

Search LDAP for user permissions with VB.NET

I'm trying to get some information from Active Directory with VB.NET.
I have the "primaryGroupID" of a user, which is 2096 in this case.
How can I get, with VB.NET, the CN of this group?
Ultimately, what I need to do is find a list of groups that a user belongs to (including groups that belong to another group). I already have a function that gets the main groups except for the primary group, and another function that returns the ID of the primary group. Both detailed below.
Public Function getUserGroups(ByVal Username)
Dim grupos As New ArrayList()
Try
Dim Entry As New System.DirectoryServices.DirectoryEntry(ldapPath, ldapAdminUser, ldapAdminPass)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.Subtree
Searcher.Filter = "(&(objectcategory=user)(SAMAccountName=" & Username & "))"
Dim res As SearchResult = Searcher.FindOne
For i = 0 To res.Properties("memberOf").Count() - 1
grupos.Add(res.Properties("memberOf")(i).ToString)
Next
Catch ex As Exception
End Try
Return grupos
End Function
Public Function GetUserPrimaryGroupID(ByVal user As String) As String
Dim grupoID As String = ""
Try
Dim Entry As New System.DirectoryServices.DirectoryEntry(ldapPath, ldapAdminUser, ldapAdminPass)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.Subtree
Searcher.Filter = "(&(objectcategory=user)(SAMAccountName=" & user & "))"
Dim res As SearchResult = Searcher.FindOne
For i = 0 To res.Properties("primaryGroupID").Count() - 1
grupoID = (res.Properties("primaryGroupID")(i).ToString) 'Esto devuelve la ruta "CN" del grupo
'grupoID = (res.Properties("primaryGroupID")(i).ToString)
'Dim de As DirectoryEntry = New DirectoryEntry("LDAP://" + res.Properties("primaryGroupID")(i).ToString())
Next
Catch ex As Exception
End Try
Return grupoID
End Function
There's a VBScript sample here - http://support.microsoft.com/kb/297951.
Essentially the primary group ID is the RID (the last component of the SID) of a group. So to find the group, you concatenate the domain SID and the primary group ID together.