.Net DirectorySearcher not retrieving all values in user object - vb.net

As part of the program I'm writing, I have to retrieve all user data from the current user's AD object.
Here is the code I'm using...
Try
Dim RootEntry As New DirectoryEntry("LDAP://**USER OU**")
RootEntry.AuthenticationType = AuthenticationTypes.Secure
Dim ds As New DirectorySearcher(RootEntry)
ds.SizeLimit = System.Int32.MaxValue
ds.PageSize = System.Int32.MaxValue
ds.PropertiesToLoad.Add("cn") ' Common Name
' Personal
ds.PropertiesToLoad.Add("givenName") ' Given Name
ds.PropertiesToLoad.Add("sn") ' Surname
ds.PropertiesToLoad.Add("fullname") ' Full Name (GN + SN)
' Comms
ds.PropertiesToLoad.Add("telephoneNumber") ' Tel # (from general)
ds.PropertiesToLoad.Add("mail") ' Email (from general)
ds.PropertiesToLoad.Add("mobile") ' Mobile Phone (from Telephone)
' Job Role
ds.PropertiesToLoad.Add("title") ' Job Title (Organisation)
ds.PropertiesToLoad.Add("company") ' Company (Organisation)
ds.PropertiesToLoad.Add("department") ' Department (Organisation)
' Address
ds.PropertiesToLoad.Add("streetAddress")
ds.PropertiesToLoad.Add("l") ' City
ds.PropertiesToLoad.Add("st") ' State
ds.PropertiesToLoad.Add("postalCode") ' Post Code
ds.PropertiesToLoad.Add("co") ' Country
ds.ServerTimeLimit = New TimeSpan(0, 0, 60)
ds.SearchScope = SearchScope.Subtree
ds.Filter = "(&(anr=" & username(1) & ")(objectCategory=person))"
Dim searchresults As SearchResultCollection
searchresults = ds.FindAll()
Debug.Print("Search Results - " & searchresults.Count())
For Each result In searchresults
If Not result.Properties("givenName")(0) Is Nothing Then
strForename = result.Properties("givenName")(0)
Label1.Text = "Hello " & strForename & "!"
End If
If Not result.Properties("sn")(0) Is Nothing Then
strSurname = result.Properties("sn")(0)
End If
If Not strSurname Is Nothing And Not strForename Is Nothing Then
strName = result.Properties("givenName")(0) & " " & result.Properties("sn")(0)
End If
If Not result.Properties("title")(0) Is Nothing Then
strTitle = result.Properties("title")(0)
End If
If Not result.Properties("company")(0) Is Nothing Then
strCompany = result.Properties("company")(0)
End If
If Not result.Properties("department")(0) Is Nothing Then
strDepartment = result.Properties("department")(0)
End If
If Not result.Properties("telephoneNumber")(0) Is Nothing Then
strPhone = result.Properties("telephoneNumber")(0)
End If
If Not result.Properties("mobile")(0) Is Nothing Then
strMobile = result.Properties("mobile")(0)
End If
If Not result.Properties("mail")(0) Is Nothing Then
strEmail = result.Properties("mail")(0)
End If
If Not result.Properties("streetAddress")(0) Is Nothing Then
strStreet = result.Properties("streetAddress")(0)
End If
If Not result.Properties("l")(0) Is Nothing Then
strLocation = result.Properties("l")(0)
End If
If Not result.Properties("st")(0) Is Nothing Then
strCounty = result.Properties("st")(0)
End If
If Not result.Properties("postalCode")(0) Is Nothing Then
strPostCode = result.Properties("postalCode")(0)
End If
If Not result.Properties("co")(0) Is Nothing Then
strCountry = result.Properties("co")(0)
End If
strAddress = strStreet
Next
Catch ex As System.Exception
Debug.Print(ex.Message)
End Try
If I run the program, the system returns all my AD settings, populating each in the box.
If another user runs the program, the system returns only a partial result set, despite the items being completed on his ADUC properties dialog.
The Searcher is only returning 1 entry per user (given it sends the SAMAccountName) but I have set the PageSize and SizeLimit values to avoid the 1000 item issue.
I have also tried a simpler filter of samaccountname= & username(1), but to no avail.
Am I running into some undocumented/unreported AD security issue? My account used to be a Domain Admin, but isn't anymore following a security review.
The problem isn't related to computers, because if I run the program via impersonation on his computer, my details are returned in full and vice-versa (his aren't).

Ok, I traced the problem to the following...
If Not result.Properties("mobile")(0) Is Nothing Then
strMobile = result.Properties("mobile")(0)
Inc_Mob.Checked = True
Mob_TB.Text = strMobile
End If
Many users do not have mobile phone numbers and the DirectorySearcher will not create a null value if it tries to retrieve a value that is blank, it just fails to create it.
I wasn't handling it properly in the code and the Try loop wasn't explicitly stating what the problem was in the error message, instead just returning an ArgumentOutOfRangeException error.

Related

"IF" code is not working inside for each?

so im learning to use socket and thread things in the networking software. so far, the software (which is not created by me) is able to chat in multiple group, but i'm tasked to allow user to code whisper feature. However, im stuck in the coding area, which im sure will work if the "if" function work inside "for each" function, anyhow here is my code mainly
Private clientCollection As New Hashtable()
Private usernameCollection As New Hashtable()
clientCollection.Add(clientID, CData)
usernameCollection.Add(clientID, username)
oh and before i forgot, the code above and below is on the server form page
on the client side, i write the code:
writer.write("PMG" & vbnewline & txtReceiverUsername & Message)
then next is the checking part on the server reading the message:
ElseIf message.Substring(0, 3) = "PMG" Then
'filter the message, check who to send to
Dim newMessage As String = message.Substring(3)
Dim messagearray As String() = newMessage.Split(vbNewLine)
Dim receiver As String = messagearray(1)
'0 = "", 1 = receiver, 2 = message
as i write before, clientcollection contain (clientID , connection data*) and usernamecollection contain (clientID, username). In my case, i only have the username data, and i need to trace it until the connection data on clientcollection hash table.
'find realid from usernamecollection, then loop clientcollection
Dim clientKey As String = 0
For Each de As DictionaryEntry In usernameCollection
'''''
'this if part Is Not working
If de.Value Is receiver Then
clientKey = de.Key
End If
'''''
Next de
'match objKey with clientcollection key
For Each dec As DictionaryEntry In clientCollection
If dec.Key = clientKey Then
Dim clients As ClientData = dec.Value
If clients.structSocket.Connected Then
clients.structWriter.Write("PMG" & messagearray(2))
End If
End If
Next dec
End If
so, how do i know that the if part is the wrong one? simply i tried these code before the "next de" code
For Each client As ClientData In clientCollection.Values
If client.structSocket.Connected Then
client.structWriter.Write("PMG" & "receiver:" & messagearray(1))
client.structWriter.Write("PMG" & "loop username: " & de.Value)
client.structWriter.Write("PMG" & "loop key: " & de.Key)
client.structWriter.Write("PMG" & "receiver key:" & clientKey)
End If
Next
the code allow me to check the de.key and de.value. they were correct, however the only thing that did not work is the code inside the "if" area.
Can anyone suggest other code maybe beside "if de.key = receiver"? I've also tried using the if de.key.equal(receiver) and it did not work too

How to close instance of an XML DOCUMENT

While attempting to issue the SAVE of the XmlDocument class on an XML document, specifically on this line of code:
myXmlDocument.Save(strFileZillaFilePathAndName).
I get... During entry update - save of FileZilla file failed. The process cannot access the file 'C:\Program Files (x86)\FileZilla Server\FileZilla Server.xml' because it is being used by another process.
It occurs in the FindAndUpdateXMLEntries(...) method called from within my UpdateFtpAccountsProcess(...) function.
I thought that this use of the SAVE did not require a close.
It happens on a 2nd execution of the function so it seems that the file is not being closed. It should be closed by the 1st execution and it is not be being used by another process
Public Function UpdateFtpAccountsProcess(ByVal strIpAddress As String, ByVal strPassword As String, ByVal iBackupSpaceId As Integer, ByVal iFtpAccountId As Integer, ByVal strFtpAccountPassword As String, ByVal strAccountType As String) As Boolean Implements IBackupServerService.UpdateFtpAccountsProcess
Dim strErrorMessage As String = ""
' Start the backup service logging.
StartTheLog(iBackupSpaceId)
' Write an log entry.
strInputLogMessage = "In UpdateFtpAccountsProcess method."
LogAnEntry(strInputLogMessage)
' Validate the password arguement in order to use this WCF service method.
' Read the app.config files "appSettings" section to get the backup server password. If it matches, continue.
strEncryptedBackupServerPassword = GetAppSetting(strKeyPassword)
If strEncryptedBackupServerPassword = strPassword Then
' Update the FTP account's encrypted password by "backup space id" and "account type". The accounts are stored in the FileZilla Server.xml file.
' Read the app.config file to get the “FileZilla path and name”.
strFileZillaFilePathAndName = GetAppSetting(strKeyFileZilla)
' Read the app.config file to get the “FileZilla Application path and name”.
strFileZillaFileApplicationPathAndName = GetAppSetting(strKeyFileZillaApplication)
If ((strFileZillaFilePathAndName = "Not Found" Or strFileZillaFilePathAndName = "Error") Or (strFileZillaFileApplicationPathAndName = "Not Found" Or strFileZillaFileApplicationPathAndName = "Error")) Then
strErrorMessage = "During update of FTP accounts - cannot find the FileZilla entries in the app config. Space Id: " & iBackupSpaceId.ToString()
Else
Try
' Read the XML file and update the "password" of 1 of the 2 User entries [ftp accounts] - for the "backup space id".
FindAndUpdateXMLEntries(strFileZillaFilePathAndName, iBackupSpaceId, strFtpAccountPassword, strAccountType)
Try
' Execute command to run the FileZilla application to have FileZilla re-read the configuration.
ReloadFileZillaConfig(strFileZillaFileApplicationPathAndName)
Catch ex As Exception
strErrorMessage = "From: ReloadFileZillaConfig() ---> " & ex.Message
End Try
Catch ex As Exception
' Attach the message coming from the FindAndUpdateXMLEntries() method.
strErrorMessage = "During update of FTP account - Space Id: " & iBackupSpaceId.ToString() & " from: FindAndUpdateXMLEntries() ---> " & ex.Message
End Try
End If
Else
strErrorMessage = "During update of FTP accounts - invalid backup server password. It must match the app.config entry. Space Id: " & iBackupSpaceId.ToString()
End If
If strErrorMessage <> "" Then
Throw New System.Exception(strErrorMessage)
End If
' End the backup service logging.
EndTheLog()
Return bSuccess = True
End Function
Public Sub FindAndUpdateXMLEntries(ByVal strFileZillaFilePathAndName As String, ByVal iBackupSpaceId As Integer, ByVal strFtpAccountPassword As String, ByVal strAccountType As String)
Dim strErrorMessage As String = ""
Dim xmlNode1 As XmlNode
Dim xmlNode2 As XmlNode
Dim xmlNode3 As XmlNode
Dim strUserNodeAtrributeNameValue As String
Dim strUnderUserNodeThisNodesAtrributeNameValue As String
Dim bSuccess As Boolean = False
' The XmlDocument class represents the XML document and has a Load method to load the document from a file, stream, or an XmlReader.
' So load in the XML file.
Dim myXmlDocument As XmlDocument = New XmlDocument()
' Write an log entry.
strInputLogMessage = "In FindAndUpdateXMLEntries method."
LogAnEntry(strInputLogMessage)
Try
' Load in the XML file.
myXmlDocument.Load(strFileZillaFilePathAndName)
' Use the XmlNode object that the DocumentElement property of the XmlDocument returns to manipulate an XML node.
xmlNode1 = myXmlDocument.DocumentElement
' Field to match to under the "Users" node. Building the "#-Private" or "#-Private" User root node.
strUserNodeAtrributeNameValue = iBackupSpaceId.ToString() & "-" & strAccountType.Trim()
' The next field to match to under the "User" node that I find.
strUnderUserNodeThisNodesAtrributeNameValue = "Pass"
' Iterate thru to find the node to update.
For Each xmlNode1 In xmlNode1.ChildNodes
If xmlNode1.Name = "Users" Then
' Find the child nodes in "Users" only.
For Each xmlNode2 In xmlNode1.ChildNodes
' Find the "User" node that I want.
If xmlNode2.Attributes("Name").Value = strUserNodeAtrributeNameValue Then
For Each xmlNode3 In xmlNode2.ChildNodes
' Find the node that I want that is under the "User" node. Looking for: <Option Name="Pass">some value</Option>
If xmlNode3.Attributes("Name").Value = strUnderUserNodeThisNodesAtrributeNameValue Then
' Update the XML to the new password value.
xmlNode3.InnerText = strFtpAccountPassword
bSuccess = True
Exit For
End If
If bSuccess = True Then
Exit For
End If
Next
End If
Next
End If
If bSuccess = True Then
Exit For
End If
Next
If bSuccess = True Then
Try
' Use the Save method of the XmlDocument class to save the altered XML back to the input XML file.
myXmlDocument.Save(strFileZillaFilePathAndName)
Catch ex As Exception
strErrorMessage = "During entry update - save of FileZilla file failed. " & ex.Message
End Try
Else
strErrorMessage = "During entry update - No User node to update"
End If
Catch ex As Exception
strErrorMessage = "During entry update - load of FileZilla file failed. " & ex.Message
End Try
If strErrorMessage <> "" Then
Throw New System.Exception(strErrorMessage)
End If
End Sub

How do I display the value of a shared parameter using an Element collector in Revit?

Thanks in advance for the help. I have no idea what I'm doing wrong and it's becoming very frustrating. First, a little background...
Program: Revit MEP 2015
IDE: VS 2013 Ultimate
I have created a Shared Parameter file and added the parameters in that file to the Project Parameters. These parameters have been applied to Conduit Runs, Conduit Fittings, and Conduits.
I'm using VB.NET to populate the parameters with no issue. After the code runs, I can see the expected text applied in the elements property window. Here is the code used to populate the values:
Populate:
Dim p as Parameter = Nothing
Dim VarName as String = "Parameter Name"
Dim VarVal as String = "Parameter Value"
p = elem.LookupParameter(VarName) <-- elem is passed in to the function as an Element
If p IsNot Nothing Then
p.Set(VarVal)
End if
Here's where I run into the error. When I attempt to retrieve the value, I am able to get the parameter by the parameter's definition name, but the value is always blank. Here is the code used to retrieve...
Try
For Each e As Element In fec.OfCategory(BuiltInCategory.OST_ConduitRun)
sTemp = sTemp & "Name: " & P.Definition.Name & vbCrLf & "Value: " & P.AsString & vbCrLf & "Value As: " & P.AsValueString & vbCrLf & vbCrLf
sTemp2 = sTemp2 & "Name: " & GetParamInfo(P, doc)
Next
MessageBox.Show(sTemp)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
The message box shows all of the parameter names correctly, and for the Revit parameters it gives me a value. The Shared parameters, however, only show the parameter names, the values are always blank. Is there another way that I'm supposed to be going about this? Oddly, I'm able to see the shared parameter values if I use a reference by user selection like so...
Dim uiDoc As UIDocument = app.ActiveUIDocument
Dim Sel As Selection = uiDoc.Selection
Dim pr As Reference = Nothing
Dim doc As Document = uiDoc.Document
Dim fec As New FilteredElementCollector(doc)
Dim filter As New ElementCategoryFilter(BuiltInCategory.OST_ConduitRun)
Dim sTemp As String = "", sTemp2 As String = ""
Dim elemcol As FilteredElementCollector = fec.OfCategory(BuiltInCategory.OST_ConduitRun)
Dim e As Element = Nothing, el As Element = Nothing
Dim P As Parameter
pr = Sel.PickObject(ObjectType.Element)
e = doc.GetElement(pr)
For Each P in e.Paramters
sTemp = sTemp & "Name: " & P.Definition.Name & vbCrLf & "Value: " & P.AsString & vbCrLf & "Value As: " & P.AsValueString & vbCrLf & vbCrLf
sTemp2 = sTemp2 & "Name: " & GetParamInfo(P, doc)
Next
MessageBox.Show(sTemp)
With the method above, when the user selects the object directly, I can see the values and the names of shared parameters. How are they different?
Is there some sort of binding that I should be looking at when the value is set to begin with? Thanks in advance for everyone's help.
Regards,
Glen
Holy Bejeesus... I figured it out, but I'm not sure why the methods are that different from each other... if anyone had any insight, that'd be great.
I wanted to post the answer here, just in case anyone else is fighting with the same thing, so... you can see the method I was using to try to read the parameters above. In the method being used now there are only a couple of things that are different... 1) An element set... 2) An active view Id was added as a parameter to the FilteredElementCollector... 3) A FilteredElementIterator was implemented.
As far as I can tell it's the iterator that's making it different... can anyone explain what it's doing differently?
Below is the method that actually works...
Public Sub Execute(app As UIApplication) Implements IExternalEventHandler.Execute
Dim prompt As String = ""
Dim uiDoc As UIDocument = app.ActiveUIDocument
Dim doc As Document = uiDoc.Document
Dim ElemSet As ElementSet = app.Application.Create.NewElementSet
Dim fec As New FilteredElementCollector(doc, doc.ActiveView.Id)
Dim fec_filter As New ElementCategoryFilter(BuiltInCategory.OST_Conduit)
fec.WhereElementIsNotElementType()
fec.WherePasses(fec_filter1)
Dim fec_i As FilteredElementIterator = fec.GetElementIterator
Dim e As Element = Nothing
fec_i.Reset()
Using trans As New Transaction(doc, "Reading Conduit")
trans.Start()
While (fec_i.MoveNext)
e = TryCast(fec_i.Current, Element)
ElemSet.Insert(e)
End While
Try
For Each ee As Element In ElemSet
GetElementParameterInformation(doc, ee)
Next
Catch ex As Exception
TaskDialog.Show("ERROR", ex.Message.ToString)
End Try
trans.Commit()
End Using
End Sub
At any rate, thanks for any help that was offered. I'm sure it won't be the last time that I post here.
Regards,
Runnin

Display related matches from database to TextBox popup when we enter some word in textbox in vb.net

i have some problem in Vb.net , i done Google since last 2 days but not getting any related answer of my question , qtn is when user type some text in Text Box so related that text how to display popup just like when we enter some word in Google then Google show all related fields .. guys i m attaching a snapshot please help me ..
i m using vb.net as back end
and MS-Access as front end
Hey guys i got the answer
Step by step (vb.net)
1st declare this as a global
Dim lst As New List(Of String)
Dim rdrOLEDB As OleDbDataReader
Dim MySource As New AutoCompleteStringCollection()
2nd on form load or as per u r logic but make sure it comes only at one time means dont include this code in 3rd step( that is key down)
If ComboBox1.SelectedItem <> "" Then
ComboBox4.Enabled = True
cmdOLEDB.CommandText = "SELECT studentname FROM StudentDetail WHERE std = '" & ComboBox1.SelectedItem & "' "
cmdOLEDB.Connection = cnnOLEDB
rdrOLEDB = cmdOLEDB.ExecuteReader
If rdrOLEDB.Read = True Then
lst.Add(rdrOLEDB.Item(0).ToString)
While rdrOLEDB.Read
lst.Add(rdrOLEDB.Item(0).ToString)
End While
End If
rdrOLEDB.Close()
MySource.AddRange(lst.ToArray)
TextBox2.AutoCompleteCustomSource = MySource
'Auto complete mode set to suggest append so that it will sugesst one
'or more suggested completion strings it has bith ‘Suggest’ and
'‘Append’ functionality
TextBox2.AutoCompleteMode = AutoCompleteMode.SuggestAppend
'Set to Custom source we have filled already
TextBox2.AutoCompleteSource = AutoCompleteSource.CustomSource
Else
MsgBox("please select std.")
End If
3rd step that is text box key down
If e.KeyCode = Keys.Enter Then ' On enter I planned to add it the list
If Not lst.Contains(TextBox2.Text) Then ' If item not present already
' Add to the source directly
TextBox2.AutoCompleteCustomSource.Add(TextBox2.Text)
End If
ElseIf e.KeyCode = Keys.Delete Then 'On delete key, planned to remove entry
' declare a dummy source
Dim coll As AutoCompleteStringCollection = TextBox2.AutoCompleteCustomSource
' remove item from new source
coll.Remove(TextBox2.Text)
' Bind the updates
TextBox2.AutoCompleteCustomSource = coll
' Clear textbox
TextBox2.Clear()
End If ' End of ‘KeyCode’ condition
if its help full then please dont forget to click on point for other peaople search ( parden me for my bad english)

Use a variable in file path in .vbs

Is it possible to usa variable in a path in .vbs. My basic situation is I have a vbs script that will often be run on a computer with one person logged in and run by an admin with a completely different user name (assume the file will be right clicked and "Run As").
The script edits an ini file that is located in the user directory for the person logged in. I know in batch I could simply insert the variable "C:\Users\%Logger%\AppData\Local\stat.ini" and the variable would be replaced. But I can't do this in .vbs. My script thus far. Or look at the bulk of it in an answer here.
Dim blnRes: blnRes = 0
Dim strOld, strNew, logger
strOld = "frogg"
strNew = "frog"
logger = Inputbox("What is your Domain ID exactly as entered when you log into this machine?","Domain ID")
On Error Resume Next
Call update("C:\Users\logger\AppData\Local\stat.ini", strOld, strNew)
blnRes = blnRes Or (Err.Number = 0): Err.Clear
Is there some way I can flag logger as a variable, or is there an easier way to do this?
I guess you meant a script variable. Try this:
logger = Inputbox("What is ID?","Domain ID")
Call update("C:\Users\"& logger &"\AppData\Local\stat.ini", strOld, strNew)
You can use command line arguments with vbs. See the following technet site:
http://technet.microsoft.com/en-us/library/ee156618.aspx
using the example vbs at the bottom, you can have Ping.vbs reply based on the computer name entered after the script name when its called (C:\scripts\Ping.vbs Hostname)
Here's more info on WScript.Aurguments
https://www.google.com/search?q=WScript.Arguments&sourceid=ie7&rls=com.microsoft:en-us:IE-Address&ie=&oe=
'Ping.vbs:
Dim arArguments, strArgument
Set arArguments = WScript.Arguments
WScript.Echo WScript.Arguments.Count
For Each strArgument in arArguments
If Ping(strArgument) Then
WScript.Echo strArgument & " is available."
Else
WScript.Echo strArgument & " is not available."
End If
Next
Function Ping( myHostName )
Dim colPingResults, objPingResult, strQuery
strQuery = "SELECT * FROM Win32_PingStatus WHERE Address = '" & myHostName & "'"
Set colPingResults = GetObject("winmgmts://./root/cimv2").ExecQuery( strQuery )
For Each objPingResult In colPingResults
If Not IsObject( objPingResult ) Then
Ping = False
ElseIf objPingResult.StatusCode = 0 Then
Ping = True
Else
Ping = False
End If
Next
Set colPingResults = Nothing
End Function
If I understand what you're after correctly, you're either going to need to do a string concatenation where you build a string like "string part 1" & logger & "string part 2" or use the replace function to replace %Logger% (e.g. Replace(templateString, "%Logger%", logger)) with your logger variable. There's not a direct equivalent to the %1 sort of format used in batch files.
This worked for me:
Dim fs, ws, Path
Set ws = CreateObject( "WScript.Shell" )
Path = ws.ExpandEnvironmentStrings( "%UserProfile%\testfile.txt" )
ws = Nothing
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile (Path, True)
f.WriteLine("This is a test")
f.Close()
f = Nothing
Don't assume "C:\Users" will be valid on every system. There are times when you may want to use a different location for user profiles. I also looked at the %AppData% environment variable, but in my case that pointed to AppData\Roaming, and you want AppData\Local.