Looping through each item in a ListBox control with VB.NET - 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

Related

Drag and drop multiple files by filter into listview

I'm currently have this code to store data to listview
I have to store first the info to textbox lines and then store them to listview.
Is there easy way without storing first textbox and directly put the files into listview?
What I want is to drag and drop or browse the multiple video ts file in the first column and then the srt in the sub column.
hope that you know what I mean. I'm rally new in listview
Sub AddToListView()
LV.Items.Clear()
Dim vn = vName.Lines
Dim sn = sName.Lines
Dim vp = vPath.Lines
Dim sp = sPath.Lines
Dim items As New List(Of ListViewItem)
Dim upper = {vn.GetUpperBound(0), sn.GetUpperBound(0), vp.GetUpperBound(0), sp.GetUpperBound(0)}
For I = 0 To upper.Min
items.Add(New ListViewItem({vn(I), sn(I), vp(I), sp(I)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
SortItems()
LV.EndUpdate()
AddToParam()
End Sub
Sub readFiles()
Dim folder As String = txtinputFolder.Text
Dim sb1 As New StringBuilder
Dim sb2 As New StringBuilder
Dim sb3 As New StringBuilder
Dim sb4 As New StringBuilder
For Each item In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
sb1.Append(item & vbNewLine)
Next
vPath.Text = ""
vPath.Text = sb1.ToString.Trim
For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
sb2.Append(Path.GetFileName(file) & vbNewLine)
Next
vName.Text = ""
vName.Text = sb2.ToString.Trim
For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
sb3.Append(Path.GetFileName(file) & vbNewLine)
Next
sName.Text = ""
sName.Text = sb3.ToString.Trim
For Each item3 In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
sb4.Append(item3 & vbNewLine)
Next
sPath.Text = ""
sPath.Text = sb4.ToString.Trim
End Sub
If i'm not wrong subtitle name should be the same as the movie
Sub readFiles(ByVal searchdirectory As String)
For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
Dim parentPath As String = Path.GetDirectoryName(FullPath)
Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
Dim srtPath As String = parentPath & "\" & movieName & ".srt"
If File.Exists(srtPath) Then
Lv.Items.Add(FullPath).SubItems.AddRange(New String() {movieName & ".ts", srtPath, movieName & ".srt"})
Else
Lv.Items.Add(FullPath).SubItems.AddRange(New String() {movieName & ".ts", "Not Exist", "No subtitle"})
End If
Next
Lv.Sorting = SortOrder.Ascending
Lv.Sort()
End Sub
usage
readFiles("you path")
You could try something like this:
Sub AddToListView(vNames As String(), sNames As String(), vPaths As String(), sPaths As String())
LV.Items.Clear()
Dim items As New List(Of ListViewItem)
Dim upperBounds = {vNames.GetUpperBound(0), sNames.GetUpperBound(0), vPaths.GetUpperBound(0), sPaths.GetUpperBound(0)}
For i = 0 To upperBounds.Min
items.Add(New ListViewItem({vNames(i), sNames(i), vPaths(i), sPaths(i)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
SortItems()
LV.EndUpdate()
AddToParam()
End Sub
Sub readFiles()
Dim folder As String = txtinputFolder.Text
Dim vPaths As New List(Of String)
Dim vNames As New List(Of String)
Dim sPaths As New List(Of String)
Dim sNames As New List(Of String)
For Each filePath In Directory.EnumerateFiles(folder, "*.ts")
vPaths.Add(filePath)
vNames.Add(Path.GetFileName(filePath))
Next
For Each filePath In Directory.EnumerateFiles(folder, "*.srt")
sPaths.Add(filePath)
sNames.Add(Path.GetFileName(filePath))
Next
AddToListView(vNames.ToArray(), sNames.ToArray(), vPaths.ToArray(), sPaths.ToArray())
End Sub
If you don't want readFiles calling AddToListView, you could use fields to store the data rather than local variables, or you could have readFields return the data in a Tuple or some dedicated object.
This seems like a reasonable answer based on the code provided and the actual question asked but it has nothing to do with drag and drop, so I'm not sure whether I'm missing something or you are.
Thank you here's my updated code:
since I want to show first the filename I tried to re-edit the code.
Sub readFiles(ByVal searchdirectory As String)
For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
Dim parentPath As String = Path.GetDirectoryName(FullPath)
Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
Dim srtPath As String = parentPath & "\" & movieName & ".srt"
Dim allPath As String = parentPath & "\" & movieName
If File.Exists(srtPath) Then
LV.BeginUpdate()
Dim lvi As New ListViewItem
With lvi
.Text = movieName & ".ts" 'video filename
.SubItems.Add(movieName & ".srt") 'subtitle filename
.SubItems.Add(movieName & ".mkv") 'output filename
.SubItems.Add(allPath & ".ts") 'video path
.SubItems.Add(allPath & ".srt") 'subtitle path
End With
LV.Items.Add(lvi)
LV.EndUpdate()
Else
MsgBox("srt file not found in the folder", vbInformation, "")
End If
Next
LV.Sorting = SortOrder.Ascending
LV.Sort()
End Sub

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

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

LDAP departmentnumber query

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