How to retrieve properties for an Active Directory user using DirectorySearcher in VB.Net - 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

Related

Request Signature Docusign Rest API vb.net

am trying to use the DocuSign .Net Client to request a signature on a Document I am creating dynamically. So far, I have been able to change the example to vb.net and it works (Exmaple CS). I was converting the "Walkthrough #4 - Request Signature on Document", about 1/2 way down the code. Now I am trying to use the Envelope.Document I've seen in other examples, such as, DocuSign example. But it seems .Document is not part of Envelope, even thought the rest of the code in both examples translates to vb.
My other option is to use the Envelope.AddDocument but I can't seem to figure out what it's expecting. I am supposed to pass fileBytes() as Byte, fileName as String, and index As Integer. I've tried a couple different methods to get the fileBytes but keep getting an error about Invalid_Content_Type Content type is not supported.
Here is the code I've been trying. Any help on how to add a Document to an Envelope would be appreciated. Ultimately I want to be able to add multiple documents to the one envelope. I can get the env.Create(docPath) to work, but that is not helpful.
Thank you in advance for any help you can offer.
Public Function RequestEsignature(email As String, rName As String, docPath As String, strSubject As String) As String
main()
Dim AccountEmail = My.Settings.docusignUserName
Dim AccountPassword = My.Settings.docusignPassword
Dim RecipientEmail = email
Dim RecipientName = rName
Dim documentPath = docPath
Dim msgString As String
Dim acct As Account = New Account()
acct.Email = AccountEmail
acct.Password = AccountPassword
Dim result As Boolean = acct.Login()
If Not result Then
msgString = String.Format("There was an error logging in to DocuSign fo user {0}.\nError Code: {1}\nMessage: {2}", acct.Email, acct.RestError.errorCode, acct.RestError.message)
MsgBox(msgString)
Return Nothing
End If
Dim env As Envelope = New Envelope
env.Login = acct
env.Recipients = New Recipients()
Dim signer(0) As Signer
signer(0) = New Signer()
signer(0).email = email
signer(0).name = RecipientName
signer(0).routingOrder = "1"
signer(0).recipientId = "1"
env.Recipients.signers = signer
Dim envDocs = New Document()
envDocs.documentId = "1"
envDocs.name = "Test Document"
envDocs.uri = docPath
'Dim fileBytes As Byte()
'Dim fileBytes = getByteArrayII(documentPath)
'Dim oFile As FileInfo
'oFile = New FileInfo(documentPath)
'Dim oFileStream As FileStream = oFile.OpenRead()
'Dim lBytes As Long = oFileStream.Length
'If lBytes > 0 Then
' Dim fileData(lBytes - 1) As Byte
' oFileStream.Read(fileData, 0, lBytes)
'If Not env.AddDocument(fileBytes, documentPath, 0) Then
' msgString = String.Format("The was an Error adding the Document." & vbCrLf & "Error Code: {0} " & vbCrLf & "Message: {1}", env.RestError.errorCode, env.RestError.message)
' MsgBox(msgString)
' Return Nothing
'Else
' MsgBox("Doc Successfully Added")
'End If
'oFileStream.Close()
'End If
env.Status = "sent"
env.EmailSubject = strSubject
result = env.Create()
If Not result Then
If Not IsNothing(env.RestError) Then
msgString = String.Format("Error Code: {0}\nMessage: {1}", env.RestError.errorCode, env.RestError.message)
MsgBox(msgString)
Return Nothing
Else
MsgBox("There was a nondescript error while processing this request. \nPLease verify all information is correct before trying again.")
Return Nothing
End If
Else
Return env.EnvelopeId
End If
End Function
Private Function getByteArray(fileName As String) As Byte()
Dim fInfo As New FileInfo(fileName)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
br.Close()
fStream.Close()
Return data
End Function
Private Function getByteArrayII(ByVal fileName As String) As Byte()
Dim tempByte() As Byte = Nothing
If String.IsNullOrEmpty(fileName) Then
Throw New ArgumentNullException("FileName Not Provided")
Return Nothing
End If
Try
Dim fileInfo As New FileInfo(fileName)
Dim numBytes As Long = fileInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim binaryReader As New BinaryReader(fStream)
tempByte = binaryReader.ReadBytes(Convert.ToInt32(numBytes))
fileInfo = Nothing
numBytes = 0
fStream.Close()
fStream.Dispose()
Return tempByte
Catch ex As Exception
Return Nothing
End Try
End Function
HISTORY
I am new to vb.net and programming. Thus far I have been able to make a program that allows users to enter client information with the forms being changed based on certain selections. We have a system that uses our SQL data to do mail merges in Word and then send a PDF for esignature to the client through DocuSign. We are using a SQL backend and a vb.net front end.
Lastly, I have been looking for an answer over the weekend and am now reaching out for help. I have searched google for every possible term(s) I can think to include/exclude. If I am asking publicly that truly means I have exhausted every resource I have. Please do not post links to any DocuSign Documentation as I have already visited all those sites. Thank you.
It doesn't appear that the Envelope class has a Document property, but rather a Documents property which seems to be an array.
The C# example you posted at this link seems to show how to attach a document:
// Attach the document(s) C#
envelope.Documents = new DocuSignWeb.Document[1];
DocuSignWeb.Document doc = new DocuSignWeb.Document();
doc.ID = "1";
doc.Name = "Document Name";
doc.PDFBytes = [Location of Document];
envelope.Documents[0] = doc;
Which in VB would be something like this:
'Attach the document(s) VB
envelope.Documents = new DocuSignWeb.Document(0);
Dim doc As New DocuSignWeb.Document()
doc.ID = "1"
doc.Name = "Document Name"
doc.PDFBytes = [Location of Document]
envelope.Documents(0) = doc
If this is not the problem you are facing, please provide additional details.
Clearly my approach to learning vb, api's and all the other stuff needed to get my program working is extremely daunting. I am not sure if it is my lack of knowledge or just a misunderstanding of the code, but I was finally able to get this figured out.
My function takes an object 'client' that has things like Name and Email, I also pass a list of Document Paths and the Subject line for the email. This loops through the list of documents and adds them to the envelope. I also have some examples of adding Tags which was a learning process in itself. I hope I am the only one unfortunate enough to have to be learning so many different new concepts that something this simple takes months to figure out, but if not here's the code:
'Request Signature - Send Envelope
Public Function RequestEsignature(pClient As iqClient, docPaths As List(Of String), strSubject As String) As DocuSign.Integrations.Client.Envelope
'*****************************************************************
' ENTER VALUES FOR FOLLOWING VARIABLES!
'*****************************************************************
Dim AccountEmail As String = My.Settings.docusignUserName
Dim AccountPassword As String = My.Settings.docusignPassword
Dim RecipientEmail As String = pClient.Email
Dim RecipientName As String = pClient.Name.NameFL
'*****************************************************************
' user credentials
Dim account As New Account()
account = LoginToDocusign()
If Not IsNothing(account) Then
End If
Dim result As Boolean ' = account.Login()
' create envelope object and assign login info
Dim envelope As New Envelope()
Dim recip = New Recipients()
Dim signers = New List(Of Signer)
Dim signer As New Signer()
signer.email = RecipientEmail
signer.name = RecipientName
signer.routingOrder = "1"
signer.recipientId = "1"
Dim fileBytes = New List(Of Byte())
Dim docNames = New List(Of String)
Dim iqDoc As iqPublicClasses.iqDocement
Dim docs = New List(Of Document)
Dim doc As Document
Dim tabs = New List(Of Tab)
Dim tab As New Tab()
Dim iTabs = New List(Of Tab)
Dim iTab As New Tab()
Dim dTabs = New List(Of DateSignedTab)
Dim dTab As New DateSignedTab
Dim rTabs = New List(Of RadioGroupTab)
Dim rTab As New RadioGroupTab()
Dim radios = New List(Of Radios)
Dim radio As New Radios()
tab = New Tab()
tab.anchorIgnoreIfNotPresent = True
tab.anchorString = "\s1\"
tabs.Add(tab)
dTab = New DateSignedTab
dTab.anchorIgnoreIfNotPresent = True
dTab.anchorString = "\d1\"
dTabs.Add(dTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\i1\"
iTab.anchorYOffset = 15
iTabs.Add(iTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\nri1\"
iTabs.Add(iTab)
rTab = New RadioGroupTab()
rTab.groupName = "RG1"
rTab.anchorIgnoreIfNotPresent = True
radio = New Radios()
radio.anchorString = "\rbn\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
radio = New Radios()
radio.anchorString = "\rby\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
rTab.radios = radios.ToArray
rTabs.Add(rTab)
signer.tabs = New Tabs()
signer.tabs.signHereTabs = tabs.ToArray
signer.tabs.dateSignedTabs = dTabs.ToArray
signer.tabs.initialHereTabs = iTabs.ToArray
signer.tabs.radioGroupTabs = rTabs.ToArray
Dim cnt = 0
For Each docName As String In docPaths
cnt += 1
iqDoc = New iqPublicClasses.iqDocement(docName)
doc = New Document()
doc.attachmentDescription = iqDoc.Name
doc.name = String.Format("{0}{1}", iqDoc.Name, iqDoc.Extension)
doc.fileExtension = iqDoc.Extension
doc.uri = iqDoc.FullPath
doc.documentId = cnt
docs.Add(doc)
docNames.Add(iqDoc.FullPath)
fileBytes.Add(File.ReadAllBytes(iqDoc.FullPath))
Next
' create envelope and send the signature request (since status is set to "sent")
envelope.Login = account
signers.Add(signer)
recip.signers = signers.ToArray
envelope.Recipients = recip
envelope.Status = "sent"
envelope.EmailSubject = strSubject
result = envelope.Create(fileBytes, docs)
If Not result Then
If envelope.RestError IsNot Nothing Then
Console.WriteLine("Error code: {0}" & vbLf & "Message: {1}", envelope.RestError.errorCode, envelope.RestError.message)
Return Nothing
Else
Console.WriteLine("Error encountered while requesting signature from template, please review your envelope and recipient data.")
Return Nothing
End If
Else
Console.WriteLine("Signature request has been sent to {0}, envelopeId is {1}.", envelope.Recipients.signers(0).email, envelope.EnvelopeId)
Return envelope
End If
End Function
PS - As I've said I am extremely new to this and am learning as I am going. I understand this may not be the most elegant approach or properly formatted code, but I unfortunately have very little time to go back an update code I've written. Hopefully one day I will be able to go back and fix all the stuff I didn't understand when I first created it.

Searching AD for a printer using 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.

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

Vb.net get username that is running process

I'm making a program that looks for processes and can see which user is using them. I've got the scanning code, but not the username code. The username has to be a string. For example: I have 2 people running some processes and the processes will show in the listview. The first column is for processes and the second is for the username. I want it to be like:
(process here) (username here)
(process here) (username here)....
You get the point I think and there's much more processes than that running on the computer. The question is: How do you get the username for someone using the process?
Edit: The code. This is my code.
For Each pr As Process In Process.GetProcesses
Dim lvi As ListViewItem = ListView1.Items.Add(CStr(pr.ProcessName))
'Now I need something to put for the username
Next
This is the other one that is most common.
Public Function GetProcessOwner(processId As Integer) As String
Dim query As String = "Select * From Win32_Process Where ProcessID = " + processId
Dim searcher As New ManagementObjectSearcher(query)
Dim processList As ManagementObjectCollection = searcher.[Get]()
For Each obj As ManagementObject In processList
Dim argList As String() = New String() {String.Empty, String.Empty}
Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
' argList(0) == User
' argList(1) == DOMAIN
Return argList(0)
End If
Next
Return "NO OWNER"
End Function
This code is taken from here, where you can find more information if you need it. Basically, on a console app this will print the process name and the user to the screen:
Public Shared Sub Main()
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New
ManagementObjectSearcher(selectQuery)
For Each proc As ManagementObject In searcher.Get
Console.WriteLine(proc("Name").ToString)
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Console.WriteLine(("User: " & (s(1) + ("\\" + s(0)))))
Next
Console.ReadLine()
End Sub
This could be implemented as a function, like:
Public Function GetUserName(ByVal ProcessName As String)
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(selectQuery)
Dim y As System.Management.ManagementObjectCollection
y = searcher.Get
For Each proc As ManagementObject In y
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Dim n As String = proc("Name").ToString()
If n = ProcessName & ".exe" Then
Return ("User: " & s(1) & "\\" & s(0))
End If
Next
End Function
Just for reference, proc.InvokeMethod("GetOwner", CType(s, Object())) will return an array like this:
Index 0: Owner/user name
Index 1: Domain
And in our case, will store it in s(1).
Hope this helps :)
Notes:
If the function returns something like User: \\ then the process is probably a special windows process. To see which processes will act like this (for windows users):
Right click on the task bar
Select Start Task Manager
In the Processes tab, in the User Name column, some processes will have a blank cell instead of a user name.
Edit:
The VB.NET function has been edited and should now work, although I have no idea why the console program still worked. At any rate I've left it alone, if it still works why change it?