Searching AD for a printer using VB.net - vb.net

I am using VB.net, trying to query Active Directory to check and see if a printer exists there. I have an AD connection but it doesn't seem to return any values when I run the code. Here is the snippet of my code
Dim searchResults As New ArrayList
Dim myDirectorySearcher As New DirectorySearcher(myDirectoryEntry))
Dim targetObject as string = "printerName"
Dim searchFilter as string = "cn"
Dim strFilter = "(&(objectClass=printer)(" & searchFilter & "=" & targetObject & "))"
myDirectorySearcher.Filter = strFilter
myDirectorySearcher.CacheResults = False
For i = 0 To searchCriteria.Count - 1
myDirectorySearcher.PropertiesToLoad.Add(searchCriteria(i).ToString)
Next
Dim mySearchResult As SearchResult = myDirectorySearcher.FindOne()
Tried various methods but nothing seems to be working, any advice would be much appreciated.

I had to do something similar to this with a project I was working on at work. In short, I think you might be searching under the wrong objectClass in ActiveDirectory.
Printers sometimes get added under printQueue.
Your code would then be something like:
Dim searchResults As New ArrayList
Dim myDirectorySearcher As New DirectorySearcher(myDirectoryEntry))
Dim targetObject as string = "printerName"
Dim strFilter = "(&(objectClass=printQueue)(cn=" & targetObject & "))"
myDirectorySearcher.Filter = strFilter
myDirectorySearcher.CacheResults = False
For i = 0 To searchCriteria.Count - 1
myDirectorySearcher.PropertiesToLoad.Add(searchCriteria(i).ToString)
Next
Dim mySearchResult As SearchResult = myDirectorySearcher.FindOne()
It is also worth bearing in mind that sometimes the printerName will have the domain appended to the end, so your query may not always return the results you would expect.
For example your printer name may be PRINTER-RECEPTION but is referenced on your domain with PRINTER-RECEPTION.MYCOMPANY.DOMAIN.
Hope this helps you.

Related

recursive reading for files in folder using vb.net

I wrote a program which is not checking the file update time but its not checking recursive folder files.kindly help for recursive folder files as well.
My code is here :
Sub getfilestat1()
Dim fileName As String
Dim CurrCyleTime As Date
Dim PrevCycleTime As Date
Dim DBCycleTime As Date
Dim connectionString As String, sql As String
Dim _SQLConnection As AseConnection
Dim _SQLCommand As AseCommand
Dim _SQLAdapter As AseDataAdapter
Dim _DataSet As DataSet
Dim _SQLReader As AseDataReader
_SQLConnection = New AseConnection
_SQLCommand = New AseCommand
_SQLConnection.ConnectionString = "Data Source='10.49.196.97';Port=9713;Database=db_print;Uid=kuat199;Pwd=testing1; "
_SQLCommand.Connection = _SQLConnection
_SQLCommand.CommandText = ""
_SQLCommand.CommandType = CommandType.Text
_SQLCommand.CommandTimeout = 900000000
_SQLConnection.Open()
Dim command As New AseCommand("select * from Kampachi_Cycle", _SQLConnection)
Dim reader As AseDataReader = command.ExecuteReader()
While reader.Read()
' Console.WriteLine(reader("pol_no").ToString() & " " & Convert.ToString(reader("image_return")) & " " & Convert.ToString(reader("no_of_images")))
DBCycleTime = reader("CYCLE").ToString()
End While
' Dim asSettings As AppSettingsSection = cAppConfig.AppSettings
'Dim fi As New System.IO.DirectoryInfo("D:\Vimal\test")
Dim fi As New System.IO.DirectoryInfo("\\kaip3r7ciwf01\BicorData\report\kam\")
Dim files = fi.GetFiles("*", SearchOption.AllDirectories).ToList()
'For Each filename As String In IO.Directory.GetFiles(Directory, "*", IO.SearchOption.AllDirectories)
'For Each file In files Select file Order By file.CreationTime Descending
''Dim first = (From file In files Select file Order By file.CreationTime Ascending).FirstOrDefault
'Count the number files in network path
Dim fcount = files.Count()
'Fetching the previous cycle run time from config file
PrevCycleTime = ConfigurationManager.AppSettings("PrevCycleTime")
CurrCyleTime = Now()
ConfigurationManager.AppSettings("PrevCycleTime") = CurrCyleTime
''''My.Settings.Save()
For i As Integer = 0 To fcount - 1
If files(i).LastWriteTime > DBCycleTime.AddMinutes(-20) Then
fileName = files(i).Name.ToString()
Dim insertCmd As New AseCommand("INSERT INTO Kampachi_FilesProcess " + " ( FILENAME, FileReadStatus) " + " VALUES( #file_name, #read_stat )", _SQLConnection)
Dim parm As New AseParameter("#file_name", AseDbType.VarChar, 1000)
insertCmd.Parameters.Add(parm)
parm = New AseParameter("#read_stat", AseDbType.VarChar, 12)
insertCmd.Parameters.Add(parm)
Dim recordsAffected As Integer
insertCmd.Parameters(0).Value = fileName
insertCmd.Parameters(1).Value = "Y"
recordsAffected = insertCmd.ExecuteNonQuery()
If i = 0 Then
fileName = files(i).Name.ToString()
Dim updCmd As New AseCommand("update Kampachi_Cycle set CYCLE = Getdate()", _SQLConnection)
Dim updparm As New AseParameter("#file_name", AseDbType.VarChar, 1000)
recordsAffected = updCmd.ExecuteNonQuery()
End If
End If
Next
End Sub
After these changes it looks fine and giving out properly.
It is giving recursive reading as well.
Change this line:
Dim files = fi.GetFileSystemInfos.ToList()
To:
Dim files = fi.GetFiles("*", SearchOption.AllDirectories).ToList()
To answer below question about the If not checking all of the files: You are correct, but your code explicitly used the FirstOrDefault method so it would only ever examine the first file. I don't know what you're doing with the rest of your program here, and your question didn't specify, but the above answered your question about recursive file searching.
To get a list of all the files that are older than 25 minutes use this code:
Dim files As List(Of FileInfo) = fi.GetFiles("*", SearchOption.AllDirectories).ToList
Dim oldFileTimeStamp As DateTime = DateTime.Now.AddMinutes(-25)
Dim olderFiles As List(Of FileInfo) = files.Where(Function(fi2) fi2.LastWriteTime > oldFileTimeStamp).ToList()
Please, if this answered this specific question, please click the accepted answer button. If you have additional questions, unrelated to the original question, please open a new Stackoverflow question, and do not add new questions to an existing Stackoverflow question. This makes it easier for future viewers to find answers to your follow up question(s) (ie: search won't find questions inside of question, it only finds the original question).

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 Splitting string lines into new strings

I want to split a string - which includes multiple lines - into new strings.
As it seems that people dont understand my problem here some further informations:
I read out values into strings from a XML-file. Some of those strings countain multiple lines. Now I need every single value of that string on a new string(variable) so that I can tell Homer to drink a beer and tell Lenny to go to bed and not tell the whole Team to go to bed. (Hopefully this story helps you :D )
To keep this simple I'll define a "static" string for this sample.
I'll put 3 of my tries down below. I'd love to hear what's wrong with them. I also tried it with lists and enums where I could split the string but no define a new one..
But I assume that there is a much easier solution for my problem...
Dim team As String = "Simpson, Homer" & vbCrLf & "Leonard, Lenny" & vbCrLf & "Carlson, Carl"
1.
Dim objReader As New StringReader(team)
Dim tm() As String
Dim i As Integer = 1
Do While objReader.Peek() <> -1
tm(i) = objReader.ReadLine() & vbNewLine
i = i + 1
Loop
Dim i As Integer = 0
For Each Line As String In team.Split(New [Char]() {CChar(vbTab)})
Dim tm(i) As String = ReadLine(team, i)
i = i + 1
Next
3.
Dim tm() As String
Dim i As Integer = 0
Dim objReader As New StringReader(team)
Do While objReader.Peek() <> -1
tm(i) = ReadLine(team, i)
i = i + 1
Loop
And the function used in 2. and 3.
Public Function ReadLine(ByVal sFile As String, Optional ByVal nLine As Long = 1) As String
Dim sLines() As String
Dim oFSO As Object
Dim oFile As Object
On Error GoTo ErrHandler
oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FileExists(sFile) Then
oFile = oFSO.OpenTextFile(sFile)
sLines = Split(oFile.ReadAll, vbCrLf)
oFile.Close()
Select Case Math.Sign(nLine)
Case 1
ReadLine = sLines(nLine - 1)
Case -1
ReadLine = sLines(UBound(sLines) + nLine + 1)
End Select
End If
ErrHandler:
oFile = Nothing
oFSO = Nothing
End Function
Thanks in advance for any shared thoughts.
There is in fact an easy solution for my problem. Sorry if I caused confusion.
Module Module1
Dim team As String = "Simpson, Homer" & vbCrLf & "Leonard, Lenny" & vbCrLf & "Carlson, Carl"
Sub Main()
Dim tm As String() = team.Split(vbLf)
'Test
Console.WriteLine(tm(0)) 'Homer
Console.WriteLine(tm(1)) 'Lenny
Console.WriteLine(tm(2)) 'Carl
End Sub
End Module

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