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

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

Related

Receive object reference error when iterate the xdocument to retrieve xml element value

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.

Extracting Portion of Url using VB.net

I have this URL
https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607
I am trying to Extract 31.888433,73.263572 from the URL
and send 31.888433 to TextBox 1
and 73.263572 to TextBox 2
Can you give me an example how can i do this with regex or anything else
You can use string.split(). This method takes an array of chars which are the discriminants for the splitting. The better solution is to split by '/', take the string that starts with '#' and then split it by ','. You'll have an array with two string: first latitude, second longitude.
Should be immediate using LINQ
The explanation is in the code comments.
Dim strURL As String = "https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
'Find the index of the first occurance of the # character
Dim index As Integer = strURL.IndexOf("#")
'Get the string from that the next character to the end of the string
Dim firstSubstring As String = strURL.Substring(index + 1)
'Get a Char array of the separators
Dim separators As Char() = {CChar(",")}
'Split the string into an array based on the separator; the separator is not part of the array
Dim strArray As String() = firstSubstring.Split(separators)
'The first and second elements of the array is what you want
Dim strTextBox1 As String = strArray(0)
Dim strTextBox2 As String = strArray(1)
Debug.Print($"{strTextBox1} For TextBox1 and {strTextBox2} for TextBox2")
Finally Made a working Code Myself
Private _reg As Regex = New
Regex("#(-?[\d].[\d]),(-?[\d].[\d])", RegexOptions.IgnoreCase)
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click
Dim url As String = WebBrowser2.Url.AbsoluteUri.ToString()
' The input string.
Dim value As String = WebBrowser2.Url.ToString
Dim myString As String = WebBrowser2.Url.ToString
Dim regex1 = New Regex("#(-?\d+\.\d+)")
Dim regex2 = New Regex(",(-?\d+\.\d+)")
Dim match = regex1.Match(myString)
Dim match2 = regex2.Match(myString)
If match.Success Then
Dim match3 As String = match.Value.Replace("#", "")
Dim match4 As String = match2.Value.Replace(",", "")
Label1.Text = match3
Label2.Text = match4
End If
End Sub
Dim url As String = "www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
Dim temp As String = Regex.Match(url, "#.*,").Value.Replace("#", "")
Dim arrTemp As String() = temp.Split(New String() {","}, StringSplitOptions.None)
Label1.Text = arrTemp(0)
Label2.Text = arrTemp(1)

Create a search bar for hex values

My current code requires me to edit the search value while the project is still in VB. I have not been able to figure out how to code the input value to use a textbox for search. I would really like to be able to build this project and use it without having VB open. Below is my code:
Dim filePath As String = Me.TextBox1.Text 'The path for the file you want to search
Dim fInfo As New FileInfo("C:\MyFile.File")
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream("C:\MyFile.File", FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
Dim pos As Integer = -1
Dim searchItem As String = "b6" 'The hex values of what you want to search
Dim searchItemAsInteger As Integer
Dim locationsFound As New List(Of Integer)
MessageBox.Show("Wait while I Scan?")
br.Close()
fStream.Close()
Integer.TryParse(searchItem, Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture, searchItemAsInteger)
For Each byteItem As Byte In data
pos += 1
If CInt(byteItem) = searchItemAsInteger Then
locationsFound.Add(pos)
Me.ListBox1.Items.Add(Hex(pos))
End If
Next
For i As Integer = 0 To Me.ListBox1.Items.Count - 1
Me.ListBox1.SetSelected(i, True)
Next
End Sub
Place a textbox named "txtHexValueToSearch" inside Form1. And then replaces the code that is commented:
' Dim searchItem As String = "b6" 'The hex values of what you want to search
Dim searchItem As String = Me.txtHexValueToSearch.Text 'The hex values of what you want to search

Split a string in VB.NET

I am trying to split the following into two strings.
"SERVER1.DOMAIN.COM Running"
For this I use the code.
Dim Str As String = "SERVER1.DOMAIN.COM Running"
Dim strarr() As String
strarr = Str.Split(" ")
For Each s As String In strarr
MsgBox(s)
Next
This works fine, and I get two message boxes with "SERVER1.DOMAIN.COM" and "Running".
The issue that I am having is that some of my initial strings have more than one space.
"SERVER1.DOMAIN.COM Off"
There are about eight spaces in-between ".COM" and "Off".
How can I separate this string in the same way?
Try this
Dim array As String() = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
Use this way:
Dim line As String = "SERVER1.DOMAIN.COM Running"
Dim separators() As String = {"Domain:", "Mode:"}
Dim result() As String
result = line.Split(separators, StringSplitOptions.RemoveEmptyEntries)
Here's a method using Regex class:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each s In str
Dim regx = New Regex(" +")
Dim splitString = regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next
And the LINQ way to do it:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each splitString In From s In str Let regx = New Regex(" +") Select regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next

How to select a value from a comma delimited string?

I have a string that contains comma delimited text. The comma delimited text comes from an excel .csv file so there are hundreds of rows of data that are seven columns wide. An example of a row from this file is:
2012-10-01,759.05,765,756.21,761.78,3168000,761.78
I want to search through the hundreds of rows by the date in the first column. Once I find the correct row I want to extract the number in the first position of the comma delimited string so in this case I want to extract the number 759.05 and assign it to variable "Open".
My code so far is:
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
Dim Year As String = 2012
Dim Quarter As String = Q4
If Quarter = "Q4" Then
Dim Open As Integer =
End If
Once I can narrow it down to the right row I think something like row.Split(",")(1).Trim) might work.
I've done quite a bit of research but I can't solve this on my own. Any suggestions!?!
ADDITIONAL INFORMATION:
Private Function RequestWebData(ByVal pstrURL As String) As String
Dim objWReq As WebRequest
Dim objWResp As WebResponse
Dim strBuffer As String
'Contact the website
objWReq = HttpWebRequest.Create(pstrURL)
objWResp = objWReq.GetResponse()
'Read the answer from the Web site and store it into a stream
Dim objSR As StreamReader
objSR = New StreamReader(objWResp.GetResponseStream)
strBuffer = objSR.ReadToEnd
objSR.Close()
objWResp.Close()
Return strBuffer
End Function
MORE ADDITIONAL INFORMATION:
A more complete picture of my code
Dim tickerArray() As String = {"GOOG", "V", "AAPL", "BBBY", "AMZN"}
For Each tickerValue In Form1.tickerArray
Dim strURL As String
Dim strBuffer As String
'Creates the request URL for Yahoo
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
'Create Array
Dim lines As Array = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
'Add Rows to DataTable
dr = dt.NewRow()
dr("Ticker") = tickerValue
For Each columnQuarter As DataColumn In dt.Columns
Dim s As String = columnQuarter.ColumnName
If s.Contains("-") Then
Dim words As String() = s.Split("-")
Dim Year As String = words(0)
Dim Quarter As String = words(1)
Dim MyValue As String
Dim Open As Integer
If Quarter = "Q1" Then MyValue = Year & "-01-01"
If Quarter = "Q2" Then MyValue = Year & "-04-01"
If Quarter = "Q3" Then MyValue = Year & "-07-01"
If Quarter = "Q4" Then MyValue = Year & "-10-01"
For Each line In lines
Debug.WriteLine(line)
If line.Split(",")(0).Trim = MyValue Then Open = line.Split(",")(1).Trim
dr(columnQuarter) = Open
Next
End If
Next
dt.Rows.Add(dr)
Next
Right now in the For Each line in lines loop, Debug.WriteLine(line) outputs 2,131 lines:
From
Date,Open,High,Low,Close,Volume,Adj Close
2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74
2013-02-04,767.69,770.47,758.27,759.02,3040500,759.02
2013-02-01,758.20,776.60,758.10,775.60,3746100,775.60
All the way to...
2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
But, what I expect is for Debug.WriteLine(line) to output one line at a time in the For Each line in lines loop. So I would expect the first output to be Date,Open,High,Low,Close,Volume,Adj Close and the next output to be 2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74. I expect this to happen 2,131 times until the last output is 2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
You could loop through the lines and call String.Split to parse the columns in each line, for instance:
Dim lines() As String = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Next
However, sometimes CSV isn't that simple. For instance, a cell in a spreadsheet could contain a comma character, in which case it would be represented in CSV like this:
example cell 1,"example, with comma",example cell 3
To make sure you're properly handling all possibilities, I'd recommend using the TextFieldParser class. For instance:
Using parser As New TextFieldParser(New StringReader(strBuffer))
parser.TextFieldType = FieldType.Delimited
parser.SetDelimiters(",")
While Not parser.EndOfData
Try
Dim columns As String() = parser.ReadFields()
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Catch ex As MalformedLineException
' Handle the invalid formatting error
End Try
End While
End Using
I would break it up into a List(of string()) - Each row being a new entry in the list.
Then loop through the list and look at Value(0).
If Value(0) = MyValue, then Open = Value(1)
You can use String.Split and this linq query:
Dim Year As Int32 = 2012
Dim Month As Int32 = 10
Dim searchMonth = New Date(Year, Month, 1)
Dim lines = strBuffer.Split({Environment.NewLine}, StringSplitOptions.None)
Dim dt As Date
Dim open As Double
Dim opens = From line In lines
Let tokens = line.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Where Date.TryParse(tokens(0), dt) AndAlso dt.Date = searchMonth AndAlso Double.TryParse(tokens(1), open)
If opens.Any() Then
open = Double.Parse(opens.First().tokens(1))
End If