trying to add a graph through txt file on visual basic - vba

as of now I have been able to get the data to come in and the graph portion set up. The issue is trying to use 2 separate array variables. I am using stream reader. I can not get my command in the loop where it will put all my plots in together. The values in my text file are comma separated and are as follows:
220,92,83,74,65,56,47,38,29,102
dim line (9) as string
for I as Integer = 0 To 9
using reader as StreamReader = New StreamReader("c:\New Folders\graph\small Graph.txt")
line = reader.ReadLine.Split(",")
end using
console.WriteLine(line)
console.Read()
Chart1.Titles.Add("Spectrum")
Chart1.chartAreas.Add("Default")
with chart1.chartareas("Default")
.AxisX.Title = "Channel"
.AxisY.Title = "Counts"
.AxisX. MajorGrid.LineColor = Color.AliceBlue
.AxisY. MajorGrid.LineColor = Color.AliceBlue
end with
chart1.Series.Clear()
chart1.Series.Add("file")
chart1.Series("file").color = Color.Red
chart1.Series("file").ChartType = DataVisualization.Charting.SeriesChartType.Line
Dim n As Integer
n = 10
Dim y as single
Continue For x = 0 To n Step 1
y = line(i)
Chart1.Series("file").Points.AddXY(x, y)
next
`

Related

vb.net efficiently finding byte sequence in byte array

so I am creating a piece of software that in short, has a list of original byte sequences and new sequences that those bytes need to be changed into, kinda like this in text form "original location(currently irrelevant as sequence can be in different places) $ 56,69,71,73,75,77 : 56,69,71,80,50,54"
I already have code that works fine, however there can be up to 600+ of these sequences to find and change and in some cases it is taking a really really long time 15 mins +, i think it is down to how long it is taking to find the sequences to them change so i am trying to find a better way to do this as currently it is unusable due to how long it takes.
I have copied the whole code for this function below in hopes one of you kind souls can have a look and help =)
Dim originalbytes() As Byte
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Select the file"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
If fd.ShowDialog() = DialogResult.OK Then
TextBox2.Text = fd.FileName
originalbytes = File.ReadAllBytes(fd.FileName)
End If
Dim x As Integer = 0
Dim y As Integer = 0
Dim textbox1array() = TextBox1.Lines
Dim changedbytes() = originalbytes
Dim startvalue As Integer = 0
Dim databoxarray() As String
Dim databoxarray2() As String
While x < textbox1array.Length - 1
'for each change to make
databoxarray = textbox1array(x).Replace(" $ ", vbCr).Replace(" : ", vbCr).Split
databoxarray2 = databoxarray(1).Replace(",", vbCr).Split
Dim databox2bytes() As String = databoxarray2
'copy original bytes line to databox2 lines
y = 0
While y < (originalbytes.Length - databox2bytes.Length)
'repeat for all bytes in ori file - size of data to find
If originalbytes(y) = databox2bytes(0) Then
startvalue = y
Dim z As String = 1
Dim samebytecounter As Integer = 1
While z < databox2bytes.Length
'repeat for all ori bytes
If originalbytes(y + z) = databox2bytes(z) Then
samebytecounter = samebytecounter + 1
End If
z = z + 1
End While
If samebytecounter = databox2bytes.Length Then
'same original data found, make changes
Dim bytestoinsert() As String = databoxarray(2).Replace(",", vbCr).Split
Dim t As Integer = 0
While t < bytestoinsert.Length
changedbytes(startvalue + t) = bytestoinsert(t)
t = t + 1
End While
End If
End If
y = y + 1
End While
x = x + 1
End While
File.WriteAllBytes(TextBox2.Text & " modified", changedbytes)
Let 's take a look at that inner while loop in your code, there are some things that can be optimized:
There is no need to check the total length all the time
Dim length as Integer = originalbytes.Length - databox2bytes.Length
While y < length
'repeat for all bytes in ori file - size of data to find
If originalbytes(y) = databox2bytes(0) Then
startvalue = y
z is not necessary, samebytecounter does exactly the same
Dim samebytecounter As Integer = 1
This while loop is a real bottleneck, since you always check the full length of your databox2bytes, you should rather quit the while loop when they don't match
While samebytecounter < databox2bytes.Length AndAlso originalbytes(y + samebytecounter ) = databox2bytes(samebytecounter )
samebytecounter = samebytecounter + 1
End While
This seems fine, but you already splitted the data at the top of your while loop, so, no need to create another array that does the same operation again
If samebytecounter = databox2bytes.Length Then
'same original data found, make changes
Dim t As Integer = 0
While t < databoxarray2.Length
changedbytes(startvalue + t) = databoxarray2(t)
t = t + 1
End While
End If
End If
y = y + 1
End While
For the rest I would agree that the algorithm you created is hugely inefficient, theoretically your code could have been rewritten like eg: (didn't really test this code)
Dim text = System.Text.Encoding.UTF8.GetString(originalbytes, 0, originalbytes.Length)
dim findText = System.Text.Encoding.UTF8.GetString(stringToFind, 0, stringToFind.Length)
dim replaceWith = System.Text.Encoding.UTF8.GetString(stringToSet, 0, stringToSet.Length)
text = text.Replace( findText, replaceWith )
dim outbytes = System.Text.Encoding.UTF8.GetBytes(text)
which would probably be a huge time saver.
For the rest your code seems to be created in such a way that nobody will really understand it if it's laying around for a month or so, I would say, including yourself

For loop not outputting properly when using arrays

I would expect this code when run to output the first line of the array, pause, then output the second line in the array, each line being output with a delay between each character but for some reason it isn't working for me.
Dim IntroText(4) As String
IntroText(0) = "Konrad Czajkowski..."
IntroText(1) = "...Presents"
IntroText(2) = "...A text based game..."
IntroText(3) = "...The Legend of Konrad and The Quest for Skairum"
Dim IntroTextLength As Integer = Nothing
IntroTextLength = IntroText(IntroText.Length - 1)
For IntroCounter1 = 0 To IntroTextLength
For IntroCounter2 = 0 To IntroText(IntroCounter1).Length - 1
Console.Write(IntroText(IntroTextLength)(IntroCounter2))
Threading.Thread.Sleep(50)
Next
Threading.Thread.Sleep(5000)
Console.Clear()
Next
Console.Clear()
P.s I'm using a console application in VB.NET
Try this.
Dim IntroText(4) As String
IntroText(0) = "Konrad Czajkowski..."
IntroText(1) = "...Presents"
IntroText(2) = "...A text based game..."
IntroText(3) = "...The Legend of Konrad and The Quest for Skairum"
Dim IntroTextLength As Integer = Nothing
IntroTextLength = IntroText.Length - 1
For IntroCounter1 = 0 To IntroTextLength - 1
For IntroCounter2 = 0 To IntroText(IntroCounter1).Length - 1
Console.Write(IntroText(IntroCounter1)(IntroCounter2))
'Console.Write(IntroTextLength)
Threading.Thread.Sleep(50)
Next
Threading.Thread.Sleep(500)
Console.Clear()
Next
Console.Clear()

There's a glitch when adding numerals to a line CSV (VB.NET)

All of the number 6's in column 6 (Item(5)) should be deleted, and the rest of the numbers should be increased by 1. However, when the process is completed, I check the file and the file is unchanged.
Dim liness As New List(Of String)(File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv"))
For Each line As String In liness
Dim item() As String = line.Split(","c)
Do
If item(5) = 6 Then
liness.Remove(line)
Else : Exit Do
End If
Exit Do
Loop
Console.WriteLine("Have you already entered the next school years, year 3's? (y/n)")
Dim year3s As String = Console.ReadLine
If year3s = "Y" Or year3s = "y" Then
For i As Integer = 1 To liness.Count - 1 'this will read to the end of the array list once
If item(5) > 3 And item(5) < 6 Then
item(5) = item(5) + 1
End If
Next
ElseIf year3s = "N" Or year3s = "n" Then
For i As Integer = 1 To liness.Count - 1 'this will read to the end of the array list once
If item(5) > 2 And item(5) < 6 Then
item(5) = item(5) + 1
End If
Next
End If
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", liness)
Exit For
Next
Exit Do
ElseIf enter.Key = ConsoleKey.End Then
Console.Clear()
adminmenu()
End If
You are updating the 'item' array, but not the 'liness' list. When you write the new 'liness' list to the file, any changes you made to the 'item' array are ignored.
Also, you are writing the 'liness' list back to the file for every loop iteration - this has to be wrong - you probably want to do that after the loop.
While I don't condone using the Split() function for parsing CSV data, I'll leave that part alone here in order to highlight other improvements in the code:
Dim minYear As Integer = 2
Console.WriteLine("Have you already entered the next school years, year 3's? (y/n)")
If Console.ReadLine().ToUpper().Trim() = "Y" Then minYear = 3
Dim NewLines = File.ReadLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv").
Select(Function(l) l.Split(","c) ).
Where(Function(l) Integer.Parse(l(5)) <> 6 ).
Select(Function(l)
Dim x As Integer = Integer.Parse(l(5))
If x >= minYear Then x += 1
l(5) = x.ToString()
Return String.Join(",", l)
End Function).ToList()
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", NewLines)

VB.NET Error Populating 2d Array with database field

i have a query that contains field "kode_brg"
i want to fill them into array2d, i'm using mysqldatareader to fill the field into array2d, but it seems that the datareader only read once inside the while looping
for more specific, i've added the ss of myproblem belom
i'm pretty sure that i've made a mistake in using the nested for inside the while loop
could somebody help me fix this problem
thanks before
regards, me
EDITED: ADDED A CODE TO A QUESTIONS
'FILL X
Dim nil_x As String = "SELECT max( kode_faktur ) FROM detail"
Dim x As Int32
Dim CMD_X = New MySqlCommand(nil_x, conn.konek)
x = Convert.ToInt32(CMD_X.ExecuteScalar())
'FILL Y
Dim nil_y As String = "select max(x.jumlah) from (select count(*) as jumlah from detail group by kode_faktur)x"
Dim y As Int32
CMD_Y = New MySqlCommand(nil_y, conn.konek)
y = Convert.ToInt32(CMD_Y.ExecuteScalar())
'LOOPING ARRAY TRANS
Dim msql As String = "select kode_brg from detail group by kode_faktur"
Dim i, j As Integer
Dim arayT(,) As String
CMD = New MySqlCommand(msql, conn.konek)
'Try
Dim hasil As MySqlDataReader
hasil = CMD.ExecuteReader()
While hasil.Read()
For i = 0 To x
ReDim Preserve arayT(x, y)
For j = 0 To y
arayT(i, j) = hasil("kode_brg")
'Continue For
Next j
j += 1
'Continue For
Next i
i += 1
Exit While
End While
conn.konek.Close()
dgv2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing
dgv2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dgv2.RowHeadersVisible = False
With Me.dgv2
.DataSource = New Mommo.Data.ArrayDataView(arayT)
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.AllowUserToAddRows = False
.RowHeadersVisible = True
End With
one big note from me
DON'T SUGGEST ME TO USE ARRAYLIST/LIST OF/LINQ/DATASET/DATATABLE
because what i really want to do is filling the 2d array with database field, comparing it with another 1d array, then create a new 2d array from both of them, finally i want to display the newly 2d array into the grid.. that's why i chose 2d array instead using dataset to fill my grid
i don't know how to compare list(of) or arraylist with 1d array, that's why i'm using 2d array (basic)
thanks you before :)
the desired output
Assuming you managed to get array size exactly the same as number of data returned from query, you can try to change the loop to following :
ReDim Preserve arayT(x, y)
For i = 0 To (x-1)
For j = 0 To (y-1)
hasil.Read()
arayT(i, j) = hasil("kode_brg")
'Continue For
Next j
'Continue For
Next i
I have no idea of what you're trying to accomplish, but this is how you should do it:
Dim list As New List(Of String(,))
While hasil.Read()
Dim item(,) As String = New String((x - 1), (y - 1)) {}
Dim value As String = hasil("kode_brg")
For i As Integer = 0 To (x - 1)
For j As Integer = 0 To (y - 1)
item(i, j) = value
Next
Next
list.Add(item)
End While

StreamReader - Reading from lines

I have the following code;
Public Sub writetofile()
' 1: Append playername
Using writer As StreamWriter = New StreamWriter("highscores.txt", True)
writer.WriteLine(PlayerName)
End Using
' 2: Append score
Using writer As StreamWriter = New StreamWriter("highscores.txt", True)
writer.WriteLine(Score)
End Using
End Sub
What I now want to do is read all the odd lines of the file (the player names) and the even lines into two separate list boxes, how would I go about that??
I need to modify;
Using reader As StreamReader = New StreamReader("file.txt")
' Read one line from file
line = reader.ReadLine
End Using
I have used one of the following solutions but cannot get it working :(
Public Sub readfromfile()
Using reader As New StreamReader("scores.txt", True)
Dim line As Integer = 0
While Not reader.EndOfStream
If line Mod 2 = 0 Then
frmHighScores.lstScore.Items.Add(line)
Else
frmHighScores.lstScore.Items.Add(line)
End If
line += 1
End While
End Using
End Sub
You can use the Mod operator for this:
Using reader As New StreamReader("highscores.txt", True)
Dim line As Integer = 0
Dim text As String
Do
text = reader.ReadLine()
If text = Nothing Then
Exit Do
End If
If line Mod 2 = 0 Then
''# even line
Else
''# odd line
End If
line += 1
Loop
End Using
This approach also works for cases when it's not an even/odd pattern, but another number of repetions. Say you have 3 lines for each player:
player name 1
score 1
avatar url 1
player name 2
score 2
avatar url 2
...
Then you can get this pattern by using Mod with 3
Dim subLine As Integer = line Mod 3
If subLine = 0 Then
''# player name
ElseIf subLine = 1 Then
''# score
Else
''# avatar url
End If
line += 1
If you can reliably expect there to be an even number of lines in the file, then you can simplify this by reading two at a time.
Using reader As StreamReader = New StreamReader("file.txt")
While Not reader.EndOfStream
Dim player as String = reader.ReadLine()
Dim otherInfo as String = reader.ReadLine()
'Do whatever you like with player and otherInfo
End While
End Using
I don't really know the syntax of VB but something like this:
dim odd as boolean = True
Using reader As StreamReader = New StreamReader("file.txt")
line = reader.ReadLine
if odd then
' add to list A
else
' add to list B
end
odd = Not Odd
End Using
Another possibility is to just read the whole file as a block into a single string and the SPLIT the string on vbcrlf
Dim buf = My.Computer.FileSystem.ReadAllText(Filename)
Dim Lines() = Split(Buf, vbcrlf)
Then, lines will contain all the lines from the file, indexed.
So you could step through them to get each player and his other info.
For x = 0 to ubound(Lines)
'do whatever with each line
next
If the file was HUGE, you wouldn't necessarily want to do it this way, but for small files, it's a quick and easy way to handle it.