Receive object reference error when iterate the xdocument to retrieve xml element value - vb.net

Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")
Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
If Not lobXnode Is Nothing Then
Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
Select Nam
Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")
End If
Next
When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.

Related

Looking for a way to populate listview from String array

I have a problem populating a ListView with an I have created. All of the data goes to one column instead of rows. Could you help me to populate it correctly?
Dim finalas() As String = arrf.ToArray(GetType(System.String))
For Each element As String In finalas
Dim item As New ListViewItem(element)
ListView1.Items.Add(item)
Next
I have found a solution myself, if some one needs it, here you go:
Sub readTextFile()
' Create new StreamReader instance with Using block.
Dim path As String = "D:\data.txt"
Dim st() As String = File.ReadAllLines(path) 'read the file into array of
Dim p_1 As String = ""
Dim p_2 As String = ""
Dim arrl As Integer = 11
For Each itm As String In st 'loop the array of string item by item
Dim Arr() As String = itm.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries) 'split the string
Dim name() As String = itm.Split(New String() {"'"}, StringSplitOptions.RemoveEmptyEntries)
' Arr.Skip(1).ToArray -nenuskaito pirmojo
' Arr = Arr.Take(Arr.Length - 1).ToArray - nenuskaito paskutinio
'galutinis array
p_1 = Arr(1)
p_2 = Arr(2)
Dim finarr As New List(Of String)
finarr.Add(p_1)
finarr.Add(p_2)
finarr.Add(name(1))
For i As Integer = 4 To arrl
finarr.Add(Arr(((Arr.Length - 1) - arrl) + i))
Next
'MsgBox(finarr(0) & finarr(1) & finarr(2) & finarr(3) & finarr(4) & finarr(5) & finarr(6) & finarr(7) & finarr(8) & finarr(9) & finarr(10))
Dim items As New List(Of ListViewItem)
Dim lvItem = New ListViewItem(finarr(0))
For i = 1 To 10
lvItem.SubItems.Add(finarr(i))
Next i
items.Add(lvItem)
ListView1.Items.AddRange(items.ToArray)
Next
Return
End Sub

How to display a structure's instance as a string vb.net?

My goal is be able to print out a Structure as a receipt without using a SortedList.
Structure:
Private Structure Facture
Dim noClient As String
Dim nom As String
Dim prenom As String
Dim adresse As String
Dim ville As String
Dim province As String
Dim codePostal As String
Dim courriel As String
Dim noTel As String
Dim noProduit As String
Dim marque As String
Dim modele As String
Dim annee As String
Dim couleur As String
Dim categorie As String
Dim noSerie As String
Dim prix As String
Dim dateVente As String
End Structure
Structure Instance :
Private Function getFacture(ByVal ID As Integer) As Facture
Dim receipt As Facture
receipt.noClient = mtxtNoClient.Text
receipt.nom = txtNom.Text
receipt.prenom = txtPrenom.Text
receipt.adresse = txtAdresse.Text
receipt.ville = txtVille.Text
receipt.province = CboProvince.Text
receipt.codePostal = mtxtCodePostal.Text
receipt.courriel = txtCourriel.Text
receipt.noTel = mtxtNoTel.Text
receipt.noProduit = mtxtNoProduit.Text
receipt.marque = txtMarque.Text
receipt.modele = txtModele.Text
receipt.annee = mtxtAnnee.Text
receipt.couleur = txtCouleur.Text
receipt.categorie = txtCategorie.Text
receipt.noSerie = txtNoSerie.Text
receipt.prix = mtxtPrix.Text
receipt.dateVente = dtpickerDateVente.Text
Return (receipt)
End Function
And I need to print this along side an Array of Strings.
FORMAT :
Private Sub btnAfficherVente_Click(sender As Object, e As EventArgs) Handles btnAfficherVente.Click
' gotta read each line and print them as toString formatted for facturation
Dim infoProduit As String() = New String() {"No de client:", "Nom:", "Prénom:", "Adresse:", "Ville:", "Province:", "Code Postal:", "Courriel:", "Téléphone:",
"No de produit:", "Marque:", "Modèle:", "Année:", "Couleur:", "Catégorie:", "No de série:", "Prix:", "Date de vente:"}
'Output in facturation formatted text
Dim i As Integer = 0
Do While i < infoProduit.Length
If i = 9 Then
txtFacturation.Text += vbCrLf + "==============================================" + vbCrLf
End If
txtFacturation.Text += String.Format("{0, -20}", infoProduit(i)) & vbTab & getFacture(i).ToString & vbCrLf
i += 1
Loop
End Sub
OUTPUT :
I have looked at the documentation and multiple questions on StackOverflow. Most of the answers are in regards of using a Dictionnary, Collection or SortedList.
In the documentation, the only thing I found was to Override the ToString() in the Structure, which would no work for me because that would mean I have to individually format them in ToString but that would mess the final output since I have to print it along side an Array of Strings.
I would use a class instead of a structure. But you'll need a method inside the structure that will return the wanted text.
Private Structure Facture
Dim noClient As String
Dim nom As String
Dim prenom As String
Dim adresse As String
Dim ville As String
Dim province As String
Dim codePostal As String
Dim courriel As String
Dim noTel As String
Dim noProduit As String
Dim marque As String
Dim modele As String
Dim annee As String
Dim couleur As String
Dim categorie As String
Dim noSerie As String
Dim prix As String
Dim dateVente As String
Function obtenirFactureTexte() As String
Dim resultat As String = ""
resultat &= "No de client: " & noClient & vbCrLf
resultat &= "Nom: " & nom & vbCrLf
resultat &= "Prénom: " & prenom & vbCrLf
' ...
Return resultat
End Function
End Structure
Sub Main()
Dim nouvelleFacture As New Facture
nouvelleFacture.noClient = "123"
nouvelleFacture.nom = "Lagare"
nouvelleFacture.prenom = "Bob"
Console.Write(nouvelleFacture.obtenirFactureTexte())
End Sub
You can then use that method to output the result anywhere.
txtFacturation.Text = getFacture(i).obtenirFactureTexte()

Error in displaying read message from modem to listview(index was outside the bounds of the array)

I am trying to develop an SMS application in VB.NET that sends and receives using a modem. The system is able to read the messages on the sim card all right but is not able to display them in the listview. I keep on getting the error index was outside the bounds of the array.
This is my code for loading the respective columns like status,date and messages into the listview. All works except the message column. Thanks.
Private Sub ReadMsg()
Try
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
lineoftext = rcvdata.ToString
arytextfile = Split(lineoftext, "+CMGL", , CompareMethod.Text)
For i = 2 To UBound(arytextfile)
Dim input As String = arytextfile(i)
Dim result() As String
Dim pattern As String = "(:)|(,"")|("","")"
result = Regex.Split(input, pattern)
Dim lvi As New ListViewItem
Dim concat() As String
With ListView1.Items.Add("null")
'index
.SubItems.AddRange(New String() {result(2)})
'status
.SubItems.AddRange(New String() {result(4)})
'number
Dim my_string, position As String
my_string = result(6)
position = my_string.Length - 2
my_string = my_string.Remove(position, 2)
.SubItems.Add(my_string)
'for date and time
concat = New String() {result(8) & result(9) & result(10) & result(11) & result(12).Substring(0, 2)}
.SubItems.AddRange(concat)
**'for the message**
Dim lineoftexts As String
Dim arytextfiles() As String
lineoftexts = arytextfile(i)
arytextfiles = Split(lineoftexts, "+32", , CompareMethod.Text)
.SubItems.Add(arytextfiles(1))
End With
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try

JSObject to JSArray

I'm trying to read all URLs from a html document.
I am using the following code:
Dim html As String =
"var linksArray = new Array(); " &
"for (var i = 0; i < document.links.length; i++) {" &
"linksArray[i] = [String(document.links[i].innerHTML), String(document.links[i].innerText), String(document.links[i].href)];" &
"} " &
"return linksArray;"
Try
Dim linksArray As JSObject = _Browser.WebView.EvalScript(String.Format("(function(){{ {0} }})()", html))
If linksArray Is Nothing Then
Stop 'this line is not reached, so it should be fine so far
End If
'the following line throws an error
Dim urls As JSArray = linksArray.ToArray()
For Each link As JSObject In urls
Dim sInnerHTML As String = link(0).ToString().Trim()
Dim sInnerText As String = link(1).ToString().Trim()
Dim sHRef As String = link(2).ToString().Trim()
If sHRef <> "undefined" Then
Dim nItem As New clsURL
nItem.HRef = sHRef
nItem.InnerHTML = sInnerHTML
nItem.InnerText = sInnerText
nList.Add(nItem)
End If
Next
Catch ex As Exception
Debug.Print(ex.Message.ToString)
Stop
End Try
However, the line
Dim urls As JSArray = linksArray.ToArray()
throws the error "The object reference was not set to an object instance".
Does anybody know how to do it correctly?
Thank you!
Got it:
Dim linksArray As JSArray = _Browser.WebView.EvalScript(String.Format("(function(){{ {0} }})()", html))
For Each obj As Object In linksArray
Dim sInnerHTML As String = obj(0).ToString().Trim()
Dim sInnerText As String = obj(1).ToString().Trim()
Dim sHRef As String = obj(2).ToString().Trim()
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