LDAP departmentnumber query - vb.net

I am attempting to query a list of users that are assigned to a specific departmentnumber in LDAP, which I know should be a list of about 100. The below code only pulls back one member (which last name starts with T, so in my mind it seems like it's only returning the last value):
Dim userIds As IEnumerable(Of String) = {"7871"}
For Each i As String In userIds
Dim de As New DirectoryEntry("LDAP://test.net:389/DC=test,DC=net")
Dim LdapFilter As String = "(departmentNumber=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
Dim res As SearchResultCollection = searcher.FindAll()
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("givenName")(0).ToString())
item.SubItems.Add(result.Properties("cn")(0).ToString())
item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
Next

this works:
Dim userIds As IEnumerable(Of String) = {"7871"}
For Each i As String In userIds
Dim de As New DirectoryEntry("LDAP://test.net:389/DC=test,DC=net")
Dim LdapFilter As String = "(departmentNumber=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult
Dim res As SearchResultCollection = searcher.FindAll()
For Each result In res
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("givenName")(0).ToString())
item.SubItems.Add(result.Properties("cn")(0).ToString())
item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
Next
Next

Related

Receive object reference error when iterate the xdocument to retrieve xml element value

Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")
Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
If Not lobXnode Is Nothing Then
Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
Select Nam
Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")
End If
Next
When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.

Looking for a way to populate listview from String array

I have a problem populating a ListView with an I have created. All of the data goes to one column instead of rows. Could you help me to populate it correctly?
Dim finalas() As String = arrf.ToArray(GetType(System.String))
For Each element As String In finalas
Dim item As New ListViewItem(element)
ListView1.Items.Add(item)
Next
I have found a solution myself, if some one needs it, here you go:
Sub readTextFile()
' Create new StreamReader instance with Using block.
Dim path As String = "D:\data.txt"
Dim st() As String = File.ReadAllLines(path) 'read the file into array of
Dim p_1 As String = ""
Dim p_2 As String = ""
Dim arrl As Integer = 11
For Each itm As String In st 'loop the array of string item by item
Dim Arr() As String = itm.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries) 'split the string
Dim name() As String = itm.Split(New String() {"'"}, StringSplitOptions.RemoveEmptyEntries)
' Arr.Skip(1).ToArray -nenuskaito pirmojo
' Arr = Arr.Take(Arr.Length - 1).ToArray - nenuskaito paskutinio
'galutinis array
p_1 = Arr(1)
p_2 = Arr(2)
Dim finarr As New List(Of String)
finarr.Add(p_1)
finarr.Add(p_2)
finarr.Add(name(1))
For i As Integer = 4 To arrl
finarr.Add(Arr(((Arr.Length - 1) - arrl) + i))
Next
'MsgBox(finarr(0) & finarr(1) & finarr(2) & finarr(3) & finarr(4) & finarr(5) & finarr(6) & finarr(7) & finarr(8) & finarr(9) & finarr(10))
Dim items As New List(Of ListViewItem)
Dim lvItem = New ListViewItem(finarr(0))
For i = 1 To 10
lvItem.SubItems.Add(finarr(i))
Next i
items.Add(lvItem)
ListView1.Items.AddRange(items.ToArray)
Next
Return
End Sub

Can't get attributes from AD using vb.net

I use below code to get first name, last name, email, and department from AD using VB.Net 1.1
Public Shared Function GetAttribute(ByVal username As String, ByVal pwd As String) As UserInfo
Dim objUserInfo As New UserInfo
Dim ObjFirstName As String = ""
Dim ObjLastName As String = String.Empty
Dim ObjEmail As String = ""
Dim objDepartment As String = ""
Dim Success As Boolean = False
Dim LDAPAddress As String = ConfigurationSettings.AppSettings.Get("LDAPAddress")
Dim Entry As New System.DirectoryServices.DirectoryEntry(LDAPAddress, username, pwd)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
Dim Filter As String = "(samAccountName=" & username & ")"
Dim findUser As DirectorySearcher = New DirectorySearcher(Entry, Filter)
Dim results As SearchResultCollection = findUser.FindAll
Try
Dim Resultsx As System.DirectoryServices.SearchResult = Searcher.FindOne
Success = Not (Resultsx Is Nothing)
findUser.PropertiesToLoad.Add("name")
Dim name As String = DirectCast(Resultsx.Properties(name)(0), String)
Dim de As System.DirectoryServices.DirectoryEntry = Resultsx.GetDirectoryEntry()
Dim gg = de.Properties.PropertyNames()
For Each Onn As String In gg
Dim str As String = String.Format("{0}", Onn)
Next
Try
ObjFirstName = de.Properties("GivenName").Value.ToString()
ObjEmail = de.Properties("mail").Value.ToString()
ObjLastName = de.Properties("sn").Value.ToString()
objDepartment = de.Properties("department").Value.ToString()
Catch ex As Exception
ObjFirstName = de.Properties("DisplayName").Value.ToString()
End Try
But I can't get those attributes. in
Dim str As String = String.Format("{0}", Onn)
there are only 15 attributes, and there are no firstname, lastname, email, and department. What am I doing wrong?
Your code, though old-fashioned, looks fine on first sight. If you insist to continue with your code, I'll have a look later.
In the meantime, this code should fit your situation:
Dim user As DirectoryEntry = New DirectoryEntry("UserDN")
Dim src As DirectorySearcher = New DirectorySearcher(user, "(&(objectClass=user)(objectCategory=Person))")
src.PropertiesToLoad.Add("sn")
src.PropertiesToLoad.Add("givenName")
src.PropertiesToLoad.Add("mail")
src.PropertiesToLoad.Add("department")
Dim res As SearchResult = src.FindOne
Console.WriteLine(res.Properties("sn")(0))
Console.WriteLine(res.Properties("givenName")(0))
Console.WriteLine(res.Properties("mail")(0))
Console.WriteLine(res.Properties("department")(0))
Console.ReadLine()

Looping through each item in a ListBox control with VB.NET

I wrote the below program to look up an LDAP user and return back a property. The way I need it to work is as follows: first I will load a list of user ID's into ListBox1, then when I click a button a property (such as DisplayName) will be appended to ListBox2. Right now I have to click on an item in ListBox1 and then click the button and it works, but I want it to loop through every ID in ListBox1 and write the properties for all of them to ListBox2 without me having to click on each user ID. How can I put the below in a for each loop?
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & ListBox1.Text & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
ListBox2.Items.Add(result.Properties("displayName")(0).ToString())
Update
I tried to use a ListView to display two columns, as suggested. It's not working, however. It just adds the ListView columns:
Dim item As ListViewItem = ListView1.Items.Add("Username")
Dim item1 As ListViewItem = ListView1.Items.Add("Title")
For Each i As String In ListBox1.Items
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
item.SubItems.Add(result.Properties("sAMAccountName")(0).ToString())
item1.SubItems.Add(result.Properties("title")(0).ToString())
Dim ADEntry As DirectoryEntry = New DirectoryEntry(result.Path)
If result.Properties("displayName") Is Nothing Then
On Error Resume Next
End If
Next
You shouldn't really be using the ListBox1.Text property. It's rather confusing. In this case, you want to loop through all of the strings in the ListBox1.Items list (presuming they are actually strings). For instance:
For Each i As String in ListBox1.Items
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
ListBox2.Items.Add(result.Properties("displayName")(0).ToString())
Next
Or, if ListBox1 doesn't actually contain strings, you could loop through them as Object and call the ToString method on each one, like this:
For Each i As Object in ListBox1.Items
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i.ToString() & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
ListBox2.Items.Add(result.Properties("displayName")(0).ToString())
Next
As I mentioned in the comments below, rather than using two separate ListBox controls, it would be preferable to use a ListView control with two columns. For instance, if you had a ListView1 control with three columns (entitled "ID", "Username", and "Title"), then you could add the items like this:
Dim userIds As IEnumerable(Of String) = getAllLdapUserIds() ' Get the list of ID's using whatever means you are currently using
For Each i As String In userIds
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("sAMAccountName")(0).ToString())
item.SubItems.Add(result.Properties("title")(0).ToString())
Next

Splitting listviews items help needed

I have some code that loops through a listview and puts the values into 'output1' & 'output2'. However, what is happening is that the results are strung together like thus: 0307NG77775660NG7778. How do I split so that I can include in access db.
There are 2 columns in the listview and they contain values in the format of:
1st row 0307 - NG7777, 2nd row 5660 - 7778 etc. This is a desktop winforms code. Thanks
Dim BoxList As New List(Of String)
Dim BoxItem As String
Dim CustRefList As New List(Of String)
Dim CustRef As String
For Each item As ListViewItem In Me.lvSelectedItems.Items
Dim box As String = item.Text
BoxItem = item.SubItems.Item(1).Text
BoxList.Add(box)
output2 += BoxItem
Dim cust As String = item.Text
CustRef = item.SubItems.Item(1).Text
CustRefList.Add(cust)
output1 += CustRef
Next
output = String.Join(" "c, BoxList.ToArray(), CustRefList.ToArray())
Dim cmd As OleDbCommand = New OleDbCommand("Insert into Temp (temp, [class]) Values ('" & output1 & "', '" & output2 & "')", oledbCnn)
dr = cmd.ExecuteReader
Make username a List(Of String), then just do:
usernameList.Add(username) 'instead of output1 += username
When done with the loop, do this:
output1 = String.Join(" "c, usernameList.ToArray())
You can pick a join character of your choice (if you don't like spaces " ").
EDIT: Example:
Dim usernameList As New List(Of String)
Dim session As String
For Each item As ListViewItem In Me.lvSelectedItems.Items
Dim username As String = item.Text
session = item.SubItems.Item(1).Text
usernameList.Add(username)
output2 += session
Next
output1 = String.Join(" "c, usernameList.ToArray())