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
EDIT: Ok, it's because I'm using 2.0 Framework. Any ideas how I can modify that area or alternatives? I have to, unfortunately, stick with 2.0
Dim dir2 As New DirectoryInfo("d:\input")
Dim sw2 As New StreamWriter("d:\input\reportCond.txt")
For Each fi2 As FileInfo In dir2.GetFiles("report.txt")
Dim sr2 As New StreamReader(fi2.FullName)
While Not sr2.EndOfStream
Dim sLine As String = sr2.ReadLine
Dim myPath As String = sLine
Dim fileName As String =System.IO.Path.GetFileNameWithoutExtension(myPath)
Dim letters As String = fileName.Where(Function(c) Char.IsLetter(c)).ToArray
Dim comp As String = sLine.Substring(28)
sw2.WriteLine(letters)
End While
Next
The Code above was working fine yesterday, today it doesn't and I can't figure out why. The only difference was yesterday I ran it on VS2013, today it doesn't work on VS2010.
I get an error on Function saying "expression expected"
And another one on sw2.WriteLine(letters) saying "Name 'letters' is not declared.
Here is how the linq Where part can be replaced to get the letters variable - which contains characters from the file name.
dim c as char
Dim letters As String
for each c in s
if char.IsLetter(c)
letters += c
end if
next
I would use the StringBuilder class to build the string:
Dim dir2 As New DirectoryInfo("d:\input")
Dim sw2 As New StreamWriter("d:\input\reportCond.txt")
For Each fi2 As FileInfo In dir2.GetFiles("report.txt")
Dim sr2 As New StreamReader(fi2.FullName)
While Not sr2.EndOfStream
Dim sLine As String = sr2.ReadLine
Dim myPath As String = sLine
Dim fileName As String =System.IO.Path.GetFileNameWithoutExtension(myPath)
' Build string
Dim sb As New System.Text.StringBuilder()
For Each c As Char In fileName
If Char.IsLetter(c) Then
sb.Append(c)
End If
Next
Dim comp As String = sLine.Substring(28)
' Here's the string you built
Dim letters As String = sb.ToString()
sw2.WriteLine(letters)
End While
Next
A .Net 2.0 framework alternative to the Where extension method could be:
Dim letters As String = Array.FindAll(fileName.ToCharArray(), AddressOf Char.IsLetter)
This will create a new array of chars whose elementes will be all chars of fileName.ToCharArray for wich Char.IsLetter is True
I have a code where i want to get an stream from an image and convert the memory stream to string array and store in a variable. But my problem is i also want to get the image from the string variable and paint on a picture box.
If i use this like
PictureBox1.Image = image.FromStream(memoryStream)
I am able to print the picture on picture box. But this is not my need. I just want to get the image stream from file and convert the stream as text and store it to some string variable and again i want to use the string variable and convert it to stream to print the image on picture box.
Here is my Code.(Vb Express 2008)
Public Function ImageConversion(ByVal image As System.Drawing.Image) As String
If image Is Nothing Then Return ""
Dim memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif)
Dim value As String = ""
For intCnt As Integer = 0 To memoryStream.ToArray.Length - 1
value = value & memoryStream.ToArray(intCnt) & " "
Next
Dim strAsBytes() As Byte = New System.Text.UTF8Encoding().GetBytes(value)
Dim ms As New System.IO.MemoryStream(strAsBytes)
PictureBox1.Image = image.FromStream(ms)
Return value
End Function
This wouldn`t work in the way you have posted it (at least the part of recreating the image).
See this:
Public Function ImageConversion(ByVal image As System.Drawing.Image) As String
If image Is Nothing Then Return ""
Dim memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif)
Dim value As String = ""
Dim content As Byte() = memoryStream.ToArray()
' instead of repeatingly call memoryStream.ToArray by using
' memoryStream.ToArray(intCnt)
For intCnt As Integer = 0 To content.Length - 1
value = value & content(intCnt) & " "
Next
value = value.TrimEnd()
Return value
End Function
To recreate the image using the created string you can`t use Encoding.GetBytes() like you did, because you would get a bytearray which represents your string. E.g "123 32 123" you would not get a byte array with the elements 123, 32 , 123
Public Function ImageConversion(ByVal stringRepOfImage As String) As System.Drawing.Image
Dim stringBytes As String() = stringRepOfImage.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
Dim bytes As New List(Of Byte)
For intCount = 0 To stringBytes.Length - 1
Dim b As Byte
If Byte.TryParse(stringBytes(intCount), b) Then
bytes.Add(b)
Else
Throw new FormatException("Not a byte value")
End If
Next
Dim ms As New System.IO.MemoryStream(bytes.ToArray)
Return Image.FromStream(ms)
End Function
Reference: Byte.TryParse
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
I need to generate a lot of random 2 character strings for my application. it's a VB console application. basically what I have tried for random strings is this:
Private Function GenerateRandomString(ByVal intLenghtOfString As Integer) As String
'Create a new StrinBuilder that would hold the random string.
Dim randomString As New StringBuilder
'Create a new instance of the class Random
Dim randomNumber As Random = New Random
'Create a variable to hold the generated charater.
Dim appendedChar As Char
'Create a loop that would iterate from 0 to the specified value of intLenghtOfString
For i As Integer = 0 To intLenghtOfString
'Generate the char and assign it to appendedChar
appendedChar = Convert.ToChar(Convert.ToInt32(26 * randomNumber.NextDouble()) + 65)
'Append appendedChar to randomString
randomString.Append(appendedChar)
Next
'Convert randomString to String and return the result.
Return randomString.ToString()
End Function
AND THIS:
Private Function RandomStringGenerator(ByVal intLen As Integer) As String
Dim r As New Random()
Dim i As Integer
Dim strTemp As String = ""
For i = 0 To intLen
strTemp = strTemp & Chr(Int((26 * r.NextDouble()) + 65))
Next
Return r.Next
End Function
But when run, it displays something like this:
SR
SR
SR
SR
SR
SR
SR
SR
SR
SR
BR
BR
BR
BR
BR
BR
BR
KR
KR
KR
KR
and so on.
What is going on? I thought that I used to, a long time ago, be able to just do random.Next.
I've run into similar issues before with the Random object. The problem is that when you instantiate Random it's default seed value is the number of milliseconds since windows started up. And since you are generating random characters at several a millisecond you end up with the same seed number.
Instead you should create a shared random object instead of instantiating a new one on each call.
In another forum I answered a similar question and came up with this generalized function that could be used for your problem. It includes a metric that can be examined to see if there is a bias in the characters being generated.
Dim charUC As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim charLC As String = charUC.ToLower
Dim charNUM As String = "0123456789"
Dim charSPEC As String = "``!##$%^&*()-_=+[{]}\|;:',<.>/?" & ControlChars.Quote
Dim charCounts As New Dictionary(Of Char, Integer)
Dim PRNG As New Random 'note - defined at class level
Private Function GetRandChars(ByVal numChars As Integer, _
Optional ByVal includeUpperCase As Boolean = False, _
Optional ByVal includeLowerCase As Boolean = False, _
Optional ByVal includeNumbers As Boolean = False, _
Optional ByVal includeSpecial As Boolean = False) As String
If numChars <= 0 Then Throw New ArgumentException 'must specify valid character count
Dim includeSel As New System.Text.StringBuilder 'contains set of characters
If includeUpperCase Then includeSel.Append(charUC) 'UC to set
If includeLowerCase Then includeSel.Append(charLC) 'LC to set
If includeNumbers Then includeSel.Append(charNUM) 'numbers to set
If includeSpecial Then includeSel.Append(charSPEC) 'specials to set
If includeSel.Length = 0 Then Throw New ArgumentException 'must tell function at least one include
Dim rv As New System.Text.StringBuilder 'return value
'generate specified number of characters
For ct As Integer = 1 To numChars
Dim chSel As Char = includeSel(PRNG.Next(includeSel.Length)) 'select random character
rv.Append(chSel)
'do counts
If charCounts.ContainsKey(chSel) Then
charCounts(chSel) += 1
Else
charCounts.Add(chSel, 1)
End If
Next
Return rv.ToString 'return the random string
End Function