Retrieve certain data from XML File - vb.net

My XML File:
<?xml version="1.0" encoding="utf-8"?>
<DisksLibrary>
<Disk>
<DiskName>Test</DiskName>
<DiskPath>testpath</DiskPath>
</Disk>
<Disk>
<DiskName>Test1</DiskName>
<DiskPath>testpath1</DiskPath>
</Disk>
<Disk>
<DiskName>Test2</DiskName>
<DiskPath>testpath2</DiskPath>
</Disk>
</DisksLibrary>
I was wondering since I have multiple tags with the same name such as and in My XML File, is it possible to retrieve a particular set of data from the XML File? For example, if I want to retrieve the DiskPath innertext which is under the same set as the one with the InnerText of "Test". In other words, the DiskPath I should retrieve is "testpath1". How do I ensure it does not confuse with other DiskPath innertext?
I tried searching online but either no solution was provided or the solution provided does not work for me. I found one solution which seem to work but after reading the code I don't think it works if there are multiple tags with the same name.
The solution I found which I am not sure if it resolves my problem is:
Dim document As XmlReader = New XmlTextReader("MyXML.xml")
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name = "FirstName") Then
TextBox1.Text = document.ReadInnerXml.ToString()
End If
If (document.Name = "LastName") Then
TextBox2.Text = document.ReadInnerXml.ToString()
End If
End If
End While
Thank you for your help. Appreciate it.

Reading about XPath and Predicates (http://www.w3schools.com/xpath/xpath_syntax.asp) would be very useful to you. In your instance you want to return the inner text of any "DiskPath" elements whose sibling "DiskName" has a value of "Test". As Styxxy described the XPath /DisksLibrary/Disk[DiskName="Test"]/DiskPath would achieve this:
Dim doc As New XmlDocument
Dim targetPath As String
doc.Load("MyXML.xml")
Dim foundNode As XmlNode = doc.SelectSingleNode("/DisksLibrary/Disk[DiskName='Test']/DiskPath")
If Not (foundNode Is Nothing) Then
targetPath = foundNode.InnerText
End If

I would consider parameterizing the XPath approach to make it scalable.
Imports System.Xml
Module Module1
Sub Main()
Dim xml As String = _
"<?xml version=""1.0"" encoding=""utf-8""?>" & _
"<DisksLibrary>" & _
" <Disk>" & _
" <DiskName>Test1</DiskName>" & _
" <DiskPath>testpath1</DiskPath>" & _
" </Disk>" & _
" <Disk>" & _
" <DiskName>Test2</DiskName>" & _
" <DiskPath>testpath2</DiskPath>" & _
" </Disk>" & _
" <Disk>" & _
" <DiskName>Test3</DiskName>" & _
" <DiskPath>testpath3</DiskPath>" & _
" </Disk>" & _
"</DisksLibrary>"
Dim doc As New XmlDocument
doc.LoadXml(xml)
For i = 1 To 4
Dim foundNode = FindSiblingNode(doc, "Test" & i, "DiskPath")
Console.WriteLine(If(Not foundNode Is Nothing, foundNode.InnerText, "Node not found"))
Next
Console.ReadLine()
End Sub
Public Function FindSiblingNode(ByVal doc As XmlDocument, _
ByVal siblingNodeInnerText As String, _
ByVal searchNodeName As String) As XmlNode
Return doc.SelectSingleNode(String.Format("/DisksLibrary/Disk[DiskName='{0}']/{1}", siblingNodeInnerText, searchNodeName))
End Function
End Module
Results:
testpath1
testpath2
testpath3
Node not found

Here's another option using LINQ to XML and XML literals:
Dim document = XDocument.Load("MyXML.xml")
Dim path As String = (
From disk In document...<Disk>
Where disk.<DiskName>.Value = "Test"
Select disk.<DiskPath>.Value
).SingleOrDefault()
path will either be the value of the matching <DiskPath> element, or Nothing if not found.

Related

Application freeze when I use an external library

My application contains a main file allowing to generate an executable using Codedom. This executable is make from my file Source.vb.
I would like to use an external library in the latter. In particular, this is Rebex: this will allow me to download a file from a server sFTP.
Here are my Codedom settings:
Public Shared Function compile_Stub(ByVal input As String, ByVal output As String, ByVal resources As String, ByVal showError As Boolean, Optional ByVal icon_Path As String = Nothing) As Boolean
Dim provider_Args As New Dictionary(Of String, String)()
provider_Args.Add("CompilerVersion", "v3.5")
Dim provider As New Microsoft.VisualBasic.VBCodeProvider(provider_Args)
Dim c_Param As New Compiler.CompilerParameters
Dim c_Args As String = " /target:winexe /platform:x86 /optimize "
If Not icon_Path = Nothing Then
c_Args = c_Args & "/win32icon:" & icon_Path
End If
c_Param.GenerateExecutable = True
c_Param.OutputAssembly = output
c_Param.EmbeddedResources.Add(resources)
c_Param.CompilerOptions = c_Args
c_Param.IncludeDebugInformation = False
c_Param.ReferencedAssemblies.AddRange({"C:\Users\marsh\Desktop\project\Galaxy\packages\Rebex.Common.5.0.7119\lib\net35\Rebex.Common.dll", "C:\Users\marsh\Desktop\project\Galaxy\packages\Rebex.Networking.5.0.7119\lib\net35\Rebex.Networking.dll", "C:\Users\marsh\Desktop\project\Galaxy\packages\Rebex.Sftp.5.0.7119\lib\net35\Rebex.Sftp.dll", "mscorlib.dll", "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Management.dll", "System.Dll", "System.Drawing.Dll", "System.Windows.Forms.Dll", "System.Data.Dll", "System.Xml.Dll"})
c_Param.GenerateInMemory = True
Dim c_Result As Compiler.CompilerResults = provider.CompileAssemblyFromSource(c_Param, input)
If c_Result.Errors.Count = 0 Then
Return True
Else
If showError Then
For Each _Error As Compiler.CompilerError In c_Result.Errors
MessageBox.Show("ERREUR de compilation" & vbNewLine &
"FileName: " & _Error.FileName & vbNewLine &
"Ligne: " & _Error.Line & vbNewLine & "ErrorText: " &
_Error.ErrorText & vbNewLine &
"Column: " &
_Error.Column & vbNewLine &
"Type d'erreur (True = avertissement, False = Erreur ): " &
_Error.IsWarning & vbNewLine & "ErrorNumber: " &
_Error.ErrorNumber)
Next
Return False
End If
Return False
End If
End Function
Despite having correctly implemented the libraries in question in my Codedom settings, nothing happens when I try to use them: no error, my application stops at the execution. The Rebex libraries are provided by the NuGet installation: Rebex.Common.dll, Rebex.Networking.dll, Rebex.Sftp.dll. The parameters that I have written in my code to import these libraries are however in agreement with this documentation.
My executable freeze when I implement this part of the code in my Stub Source.vb:
Dim sftp As New Rebex.Net.Sftp()
sftp.Connect(hostname)
' log in
sftp.Login(username, password)
I really do not understand where this problem comes from. The fact that no error appears blocks me more: I do not know which way to go to solve the error. Could you help me?

Check if file exists and copy it if it does

I've been searching the net and have tried all the code found. My code should be simple but it's not working. I'm using a list to store image strings (but they do not have the extension on them). I want to test if the image file exists in a folder and if it does copy it. If it doesn't write to a file with the image name. The result I'm getting is all the files do not exists. But I checked and the files are there.
For Each image In GraphicList
ImgFile = ImgLocation & "\" & image & ".*"
Dim MoveFile As String
MoveFile = createFigFolder & "\" & image & ".*"
If Not System.IO.File.Exists(ImgFile) Then
Debug.Write("File does not exists : " & ImgFile & vbCrLf)
' file does not exist
Else
Debug.Write("File EXISTS : " & ImgFile & vbCrLf)
System.IO.File.Copy(ImgFile, MoveFile)
End If
Next
Here's the code that writes the GraphicList
Private Sub CreateGraphicsFunction(sender As Object, e As EventArgs)
Dim Regex = New Regex("infoEntityIdent=""(ICN.+?)[""].*?[>]")
Dim ICNFiles = Directory.EnumerateFiles(MoveToPath, "*.*", SearchOption.AllDirectories)
For Each tFile In ICNFiles
Dim input = File.ReadAllText(tFile)
Dim match = Regex.Match(input)
If match.Success Then
GraphicList.Add(match.Groups(1).Value)
Dim Regex2 = New Regex("<!ENTITY " & match.Groups(1).Value & " SYSTEM ""(ICN.*?[.]\w.+)")
Dim sysFileMatch = Regex2.Match(input)
If sysFileMatch.Success Then
ICNList.Add(sysFileMatch.Groups(1).Value)
Debug.Write("found ICN " & sysFileMatch.Groups(1).Value)
End If
End If
Next
End Sub
New Code to cycle through array and see if its entries match strings in Graphic Lists. This code doesn't work, but I think it's similar to what I want.
Dim fileEntries As String() = Directory.GetFiles(ImgLocation, ".*")
' Process the list of files found in the directory. '
Dim fileName As String
For Each fileName In fileEntries
If ICNList.Contains(fileName) Then
Debug.Write("File EXISTS : " & fileName & vbCrLf)
Else
Debug.Write("File does not exists : " & fileName & vbCrLf)
End If
Next
Join the list of filenames on the source list of files, using the filename without extension as the key. Then iterate over the results and copy each one
Dim fileNames = System.IO.Directory.GetFiles(imgLocation).Join(
graphicList,
Function(p) Path.GetFileNameWithoutExtension(p),
Function(f) f,
Function(p, f) p)
' create the directory first (does nothing if it already exists)
Directory.CreateDirectory(newLocation)
' copy each file
For Each fileName In fileNames
System.IO.File.Copy(fileName, Path.Combine(newLocation, Path.GetFileName(fileName)))
Next

VB.net get bitlocker Password ID from Active Directory

I have a VB.net program that I am trying to add a bitlocker lookup tool that will search active directory for the machine name, and display the "Password ID" as well as the "Recovery Password"
So far my script/code works flawlessly for the lookup and displaying the Recovery Password, but I cannot get it to display the Password ID.
I've tried:
Item.Properties("msFVE-RecoveryGuid")(0)
Which returns the error "System.InvalidCastException: Conversion from type 'Byte()' to type 'String' is not valid."
Item.Properties("msFVE-RecoveryGuid")(0).ToString
Which returns "System.Byte[]"
Item.Properties("msFVE-RecoveryGuid").ToString
Which returns "System.DirectoryServices.ResultPropertyValueCollection"
So far in my searching I've only seen C# examples, and I haven't been able to translate.
The same for Recovery Password works however:
(Item.Properties("msFVE-RecoveryPassword")(0))
Here is the larger snippet of what I have for context:
Dim RootDSE As New DirectoryEntry("LDAP://RootDSE")
Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
Dim ADsearch As New DirectorySearcher("LDAP://" & DomainDN)
ADsearch.Filter = ("(&(objectClass=computer)(name=" & MachineName & "))")
Dim ADresult As SearchResult = ADsearch.FindOne
Dim ADpath As String = ADresult.Path
Dim BTsearch As New DirectorySearcher()
BTsearch.SearchRoot = New DirectoryEntry(ADpath)
BTsearch.Filter = "(&(objectClass=msFVE-RecoveryInformation))"
Dim BitLockers As SearchResultCollection = BTsearch.FindAll()
Dim Item As SearchResult
Dim longTempstring As String = ""
For Each Item In BitLockers
If Item.Properties.Contains("msFVE-RecoveryGuid") Then
Dim tempstring As String = Item.Properties("msFVE-RecoveryGuid")(0).ToString
longTempstring = longTempstring & tempstring & vbNewLine
'ListBox2.Items.Add(Item.Properties("msFVE-RecoveryGuid")(0))
End If
If Item.Properties.Contains("msFVE-RecoveryPassword") Then
ListBox1.Items.Add(Item.Properties("msFVE-RecoveryPassword")(0))
End If
Next
MsgBox(longTempstring)
So I figured out that I needed to convert the bytes to hex in order to get them to match what is viewed in the Microsoft Management Console. Once I began doing that the only problem I ran into is that I discovered the indexing of the byte arrays are not in the same order as they are in Active Directory. -- so instead of looping I had to list out each index of the Byte array and sort them to their proper positions so that they match how they show up in AD.
My end function is:
Function bitread(ByVal GUID As Byte())
Dim tempVar As String
tempVar = GUID(3).ToString("X02") & GUID(2).ToString("X02") _
& GUID(1).ToString("X02") & GUID(0).ToString("X02") & "-" _
& GUID(5).ToString("X02") & GUID(4).ToString("X02") & "-" _
& GUID(7).ToString("X02") & GUID(6).ToString("X02") & "-" _
& GUID(8).ToString("X02") & GUID(9).ToString("X02") & "-" _
& GUID(10).ToString("X02") & GUID(11).ToString("X02") _
& GUID(12).ToString("X02") & GUID(13).ToString("X02") _
& GUID(14).ToString("X02") & GUID(15).ToString("X02")
Return tempVar
End Function
Called with:
bitread(Item.Properties("msFVE-RecoveryGUID")(0))

Getting BC31019 excepetion while compiling vb.net at runtime on Windows 10

we are generating a mass of documents very dynamically. Therefore we concatenate source code and build a dll at runtime. This is running since windows XP.
Now we are in tests of windows 10 and it fails compiling this dll with the error "BC31019: Unable to write to output file 'C:\Users[name]AppData\Local\Temp\xyz.dll': The specified image file did not contain a resource section"
For testing purposes we remove all generated source code and replace it by a rudimental class with only one function (throwing an exception with specified text) and no referenced assemblies.
This is also running on all machines except windows 10. Same error.
Can anybody guess why?
This is the rudimental method
Public Sub Compile()
Dim lSourceCode = "Namespace DynamicOutput" & vbCrLf &
" Public Class Template" & vbCrLf &
" Sub New()" & vbCrLf &
" End Sub" & vbCrLf &
" Public Sub Generate(ByVal spoolJob As Object, ByVal print As Object)" & vbCrLf &
" Throw New System.Exception(""Generate reached"")" & vbCrLf &
" End Sub" & vbCrLf &
"" & vbCrLf &
" End Class" & vbCrLf &
"End Namespace"
Dim lParams As CodeDom.Compiler.CompilerParameters = New CodeDom.Compiler.CompilerParameters
lParams.CompilerOptions = "/target:library /rootnamespace:CompanyName /d:TRACE=TRUE /optimize "
lParams.IncludeDebugInformation = True
lParams.GenerateExecutable = False
lParams.TreatWarningsAsErrors = False
lParams.GenerateInMemory = True
Dim lProviderOptions As New Dictionary(Of String, String) From {{"CompilerVersion", "v4.0"}}
Dim lResult As CodeDom.Compiler.CompilerResults = Nothing
Using provider As New VBCodeProvider(lProviderOptions)
lResult = provider.CompileAssemblyFromSource(lParams, lSourceCode)
End Using
' ... check for errors
Dim lInstance As Object = lResult.CompiledAssembly.CreateInstance("CompanyName.DynamicOutput.Template")
lInstance.GetType.GetMethod("Generate").Invoke(lInstance, New Object() {Me.SpoolJob, Me.Print})
End Sub

Is it possible to build .RDL file into an .EXE for deployment?

I have a few .RDL reports that I run in a (VB) Windows Forms application.
I'd like to distribute it as a single .EXE file.
Is it possible to build the .RDL files into the .EXE?
There's this tasty property called LocalReport.ReportEmbeddedResource, but this doesn't build the .RDL into the final file.
Yes. The LocalReport.LoadReportDefinition(TextReader) method can accept a stream. You can use a StringReader to load the report from your resources or from a constant (string) embedded in your code.
http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.localreport.loadreportdefinition(v=vs.100).aspx
http://msdn.microsoft.com/en-us/library/system.io.stringreader(v=vs.110).aspx
Example:
Const rdl As String = "<Report>" & _
" <DataSets>" & _
" <DataSet Name=""IrrelevantToThisExample"">" & _
" <Query>" & _
" <DataSourceName>DataTableName</DataSourceName>" & _
" <CommandText>SELECT * FROM sys.Tables</CommandText>" & _
" </Query>" & _
" </DataSet>" & _
" </DataSets>" & _
"</Report>"
'the LocalReport.LoadReportDefinition needs to read the string from a stream
'Create a string reader to convert the string into a stream
Using sr As New System.IO.StringReader(rdl)
MyReportViewer.LocalReport.LoadReportDefinition(sr)
sr.Close()
End Using
This was the final solution, based on Wil Burton's reply at http://social.msdn.microsoft.com/Forums/en-US/f7f92d61-2c23-47e7-b2a3-12ee4ed9fa9a/loading-an-embedded-resource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' This is a simplest-possible self-contained example that works!!
Dim data() As Byte = My.Resources.aSimpleReport
Dim reportStream As New IO.MemoryStream
reportStream.Write(data, 0, data.Length)
reportStream.Position = 0
ReportViewer1.ProcessingMode = ProcessingMode.Local
ReportViewer1.LocalReport.LoadReportDefinition(reportStream)
ReportViewer1.RefreshReport()
End Sub
Just to clarify the setup: a very simple (just a text box) .RDL file called aSimpleReport.RDL was added as "An Existing File" to the project's Resources.