VB.NET extract data from API - vb.net

I am a beginner in VB.NET and i am trying to extract data from an API and add it to a listview column but i don't know how to extract the data.
[This is the API][1]
[1]: https://tmnf.exchange/api/tracks?author=lolsport&count=40&fields=TrackId%2CTrackName
It is a API for downloading race tracks for Trackmania.
The data is shown as follows {"TrackId":9707620,"TrackName":"lolsport R444"},
Now what i need is the TrackIDs and TrackNames.
i have two columns in my program where i want to sort them into like so.
**TrackID** **TrackName**
9707620 lolsport R444
How can i do this? i googled a lot about regular expressions but i cant seem to find anything that works.

Dim Data As String = "{""TrackId"":9707620,""TrackName"":""lolsport R444""}"
Dim dataaray() As String = Data.Split(",")
Dim dataval() As String
Dim fileloc As String = Environment.CurrentDirectory & "\Test.txt"
If Not File.Exists(fileloc) Then
File.Create(fileloc).Dispose()
Else
File.Delete(fileloc)
File.Create(fileloc).Dispose()
End If
Dim objwriter As New StreamWriter(fileloc, True)
Dim i As Int32 = 0
Dim val As String
objwriter.WriteLine("**TrackID** **TrackName**")
For Each rw As String In dataaray
dataval = rw.Split(":")
val += dataval(1).Replace("""", "").Replace("}", "") & vbTab
If i = 1 Then
objwriter.WriteLine(val.TrimEnd())
val = String.Empty
i = 0
End If
i += 1
Next
objwriter.Close()
objwriter.Dispose()

Related

get full string before first second third etc. split

I have a file location and I need to check if it exists.
The way I wan't to do it is like this:
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
For count2 As Integer = 0 To counting - 1
Dim firstbackslash As Integer = route.IndexOf("\")
Dim backslash As Integer = route.IndexOf("\", firstbackslash + 1)
Dim firstPart As String = route.Substring(0, backslash)
MsgBox(firstPart)
Next
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
But I cant find something like this on the internet nor with some messing around...
Here is an algorithm that that will give you all the paths starting from the root and building up to the final path including the filename. You can use this to check for each folder and create them as you go if they don't exist:
Sub Main()
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
Dim fi As New System.IO.FileInfo(route)
If Not fi.Exists Then
Dim fileName As String = Path.GetFileName(route)
Dim di As DirectoryInfo = fi.Directory
Dim pathStack As New Stack(Of String)()
pathStack.Push(di.Name)
While Not IsNothing(di.Parent)
di = di.Parent
pathStack.Push(di.Name)
End While
Dim curPath As String = ""
While pathStack.Count > 0
curPath = Path.Combine(curPath, pathStack.Pop)
' ... do something with "curPath" in here ...
' ... like check for existence and create it ...
Console.WriteLine(curPath)
End While
curPath = Path.Combine(curPath, fileName)
' ... do something with "curPath" in here ...
' ... this is the full path including the file on the end ...
Console.WriteLine(curPath)
End If
Console.Write("Press Enter to quit...")
Console.ReadLine()
End Sub
Output:
C:\
C:\testing1
C:\testing1\testing2
C:\testing1\testing2\testing3
C:\testing1\testing2\testing3\testing4
C:\testing1\testing2\testing3\testing4\testing5
C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt
Press Enter to quit...
Don't use string mnaipulation to work with file or folder paths. use the Path class.
One option:
Private Function GetExistingSubPath(fullPath As String) As String
If Directory.Exists(fullPath) OrElse File.Exists(fullPath) Then
Return fullPath
End If
Dim subPath = Path.GetDirectoryName(fullPath)
If subPath Is Nothing Then
Return Nothing
End If
Return GetExistingSubPath(subPath)
End Function
Sample usage:
Dim fullPath = "C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt"
Dim existingSubPath = GetExistingSubPath(fullPath)
Console.WriteLine(existingSubPath)
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
Noooooooooooo!
That's not how to do it at all! The file system is volatile: things can change between each of those checks. Moreover, file existence is only one of many things that can stop file access.
It's much better practice to try to access the file in question, and then handle the exception if it fails. Remember, because of the prior paragraph you have to be able to handle exceptions here anyway. .Exists() doesn't save you from writing that code. And each check is another round of disk access, which is about the slowest thing it's possible to do in a computer... even slower than unrolling the stack for an exception, which is the usual objection to this idea.
I fixed it, know I can check if multiple text files are at the locations I need, if there not I place the Textfiles at the location I need them. Then I can add something in it. (I need to put a Location of something else in it.)
Dim een As String = "C:\testing1\testing2\testing7\testing1\testing1\text.txt"
Dim twee As String = "C:\testing1\testing2\testing7\testing2\testing1\text.txt"
Dim drie As String = "C:\testing1\testing2\testing7\testing3\testing1\text.txt"
Dim vier As String = "C:\testing1\testing2\testing7\testing4\testing1\text.txt"
Dim Files As String() = {een, twee, drie, vier}
For Each route As String In Files
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
Dim tel As Integer = route.Substring(route.LastIndexOf("\") + 1).Count
Dim bestandnaam As String = route.Substring(route.LastIndexOf("\") + 1)
For count2 As Integer = 0 To route.Length - tel - 1
Dim firstbackslash As Integer = route.IndexOf("\", count2)
Dim backslash As Integer = route.IndexOf("\", count2)
Dim Mapnaam As String = route.Substring(0, backslash)
count2 = firstbackslash
If System.IO.Directory.Exists(Mapnaam) Then
Else
System.IO.Directory.CreateDirectory(Mapnaam)
End If
Next
If System.IO.File.Exists(route) Then
Else
Dim objStreamWriter As System.IO.StreamWriter
objStreamWriter = New System.IO.StreamWriter(route)
Dim label As String
Select Case route
Case een
label = "een"
Case twee
label = "twee"
Case drie
label = "drie"
Case vier
label = "vier"
End Select
Dim value As String = InputBox("Route invullen naar " & label)
'Dim objStreamWriter As New System.IO.StreamWriter(route)
objStreamWriter.Write(value)
objStreamWriter.Close()
'Using sw As System.IO.StreamWriter = System.IO.File.AppendText(route)
' sw.WriteLine(value)
'End Using
End If
End If
Next route

Retrieve everything after a split in string VB.net

I'm needing to return the value of a string after it's been split in VB.Net.
The string will be something along the lines of:
someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5
The string can't contain more than 3 of these expressions so I need to retrieve everything after someexpression3.
After the split I would need the following "OR someexpression4 OR someexpression5", the full string will always be different lengths so I need something dynamic in order to capture the last part of the string.
Without further information on how danymic your splitting should be the following code will cover your requirement:
'Some UnitTest
Dim toSplit As String = "someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5"
Dim actual = GetLastExpressions(toSplit)
Dim expected = "OR someexpression4 OR someexpression5"
Assert.AreEqual(expected, actual)
toSplit = "requirement OR is OR weird"
actual = GetLastExpressions(toSplit)
expected = ""
Assert.AreEqual(expected, actual)
'...
Private Function GetLastExpressions(expression As String, Optional splitBy As String = "OR", Optional numberToSkip As Integer = 3)
Dim expr As String = ""
Dim lExpressions As IEnumerable(Of String) = Nothing
Dim aSplit = expression.Split({expression}, StringSplitOptions.None)
If aSplit.Length > numberToSkip Then
lExpressions = aSplit.Skip(numberToSkip)
End If
If lExpressions IsNot Nothing Then
expr = splitBy & String.Join(splitBy, lExpressions)
End If
Return expr
End Function
Spoke to a friend of mine who suggested this and it works fine;
Dim sline As String = MyString
Dim iorcount As Integer = 0
Dim ipos As Integer = 1
Do While iorcount < 17
ipos = InStr(ipos, sline, "OR")
ipos = ipos + 2
iorcount = iorcount + 1
Loop
MsgBox(Mid(sline, ipos))

How can I seperate the values in the textbox to show in different labels using button?

i want to be able to separate the values in a textbox and display the separated values in different labels using a button
this is what i want to happen:
input "Ac2O3" on textbox
Be able to separate "Ac", "2", "O", and "3".
Show the separated values in different textboxes using a button
im using visual basic 2012
im sorry im still new to this
thanks in advance!!
You can access different character of the string with the index.
Dim input As String = "Ac2O3"
Dim part1 As String = input(0) & input(1)
Dim part2 As String = input(2)
Dim part3 As String = input(3)
Dim part4 As String = input(4)
If you don't know how to handle the button event or how to display text in a textbox, that would be different questions.
This code creates a structure called Element to make the results from the function clearer - add this to your main class that the function is going to be placed in. The main function takes a string as it's input and produced a list of structures of Element as it's output. There probably are shorter ways to do this, but I'm a fairly basic programmer who likes a puzzle - hope this helps - Dont forget to accept the answer by clicking on the tick. If you have any queries please dont hesitate to ask
Structure Element
Dim symbol As String
Dim elementCount As Int16
End Structure
Function ParseFormula(ByVal compoundString As String) As List(Of Element)
Dim tempParseFormula = New List(Of Element)
Dim firstLetter As String = "[A-Z]"
Dim secondLetter As String = "[a-z]"
Dim number As String = "[0-9]"
Dim tempElementCount As String = ""
Dim maxIndex As String = compoundString.Length - 1
Dim i As Integer = 0
Dim parsedElement As New Element
While i <= maxIndex
Dim tempChar As String = compoundString(i)
Select Case True
Case tempChar Like firstLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like secondLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like number
tempElementCount = tempElementCount & tempChar
End Select
If i = maxIndex Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
Exit While
End If
i += 1
If compoundString(i) Like firstLetter Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
End If
End While
Return tempParseFormula
End Function

Sort text file with delimiter

I have a text file that is 800KB line by line with comma delimiter.
I am trying to sort this text file by the first part which is a date.
when I run this it takes about 2 seconds to complete.
something is really slowing it down, what do you guys see?
Dim sw As New Stopwatch
sw.Start()
Dim sMilli As Integer = 1000
Dim iSortedDates As New SortedDictionary(Of Date, String)
For Each line As String In IO.File.ReadAllLines(iFilePath)
Dim eachPart() As String = line.Split(","c)
Dim eachDate As Date = Date.Parse(eachPart(0)).AddMilliseconds(sMilli)
iSortedDates(eachDate) = line
If sMilli = 5000 Then sMilli = 1
sMilli += 1
Next
Dim iAllData As String = ""
For Each iSNew In iSortedDates.Keys
iAllData += iSortedDates(iSNew) & Environment.NewLine
Next
IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory & iFilePath, iAllData)
sw.Stop()
Debug.Print("Total Milliseconds: " & sw.Elapsed.TotalMilliseconds)
If you are targeting version 4 or higher of the Framework, you may be able to save some time by using IO.File.ReadLines instead of IO.File.ReadAllLines as ReadLines doesn't make you wait until the whole file is read before you can start processing the lines.
You can avoid building that long iAllData string one line at a time by using iSortedDates.Values to create an array that can be written bi IO.File.WriteAllLines.
Dim sw As New Stopwatch
sw.Start()
Dim sMilli As Integer = 1000
Dim iSortedDates As New SortedDictionary(Of Date, String)
For Each line As String In IO.File.ReadLines(iFilePath)
Dim eachPart() As String = line.Split(","c)
Dim eachDate As Date = Date.Parse(eachPart(0)).AddMilliseconds(sMilli)
iSortedDates(eachDate) = line
If sMilli = 5000 Then sMilli = 1
sMilli += 1
Next
Dim iAllData() As String = iSortedDates.Values.ToArray
IO.File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory & iFilePath, iAllData)
sw.Stop()
Debug.Print("Total Milliseconds: " & sw.Elapsed.TotalMilliseconds)
I would look into Linq if you could. Below is a quick query I have done for you, it not only reads all of the lines, but it checks if the split string is a date then order by that and put anything else at the end sorted. I tested this on a 6.73 MB file and came out at 1.97 seconds. If you ask me that is really quick I would say.
You can use this anywhere
Dim nDate As Date
Dim lines As List(Of String) = System.IO.File.ReadAllLines(yourfile).Where(Function(x) Date.TryParse(x.Split(","c)(0), nDate) OrElse Not String.IsNullOrEmpty(x)).OrderBy(Function(line) line.Split(",")(0)).ToList
IO.File.WriteAllText("FILE LOCATION", Concat(lines))
Function to return all lines in a string
Public Shared Function Concat(source As List(Of String)) As String
Dim sb As New System.Text.StringBuilder
For Each s As String In source
sb.AppendLine(s)
Next
Return sb.ToString()
End Function
P.S. Sorry if the Linq query looks long, you can make that top down so it can be easier to read if you want.

How to get an array to display all its values at once

Here is some sample code:
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
How can I display those four values next to each other.
More specifically, given those values how can I make txtValue.Text = 5471
Edit:
The idea I had would be to use some sort of function to append each one to the end using a loop like this:
Dim finalValue
For i As Integer = 3 To 0 Step -1
arrValue(i).appendTo.finalValue
Next
Obviously that code wouldn't work though the premise is sound I don't know the syntax for appending things and I'm sure I wouldn't be able to append an Integer anyway, I would need to convert each individual value to a string first.
Another method is to use String.Join:
Sub Main
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
Dim result As String = String.Join("", arrValue)
Console.WriteLine(result)
End Sub
If I understand your question correctly, you can use StringBuilder to append the values together.
Dim finalValue as StringBuilder
finalValue = new StringBuilder()
For i As Integer = 3 To 0 Step -1
finalValue.Append(arrValue(i))
Next
Then just return the finalValue.ToString()
Convert the integers to strings, and concatenate them:
Dim result as String = ""
For Each value as Integer in arrValue
result += value.ToString()
Next
Note: using += to concatenate strings performs badly if you have many strings. Then you should use a StringBuilder instead:
Dim builder as New StringBuilder()
For Each value as Integer in arrValue
builder.Append(value)
Next
Dim result as String = builder.ToString()
for i = lbound(arrValue) to ubound(arrValue)
ss=ss & arrValue(i)
next i
end for
debug.print ss
Dim value as string = ""
For A As Integer = 1 To Begin.nOfMarks
value += "Mark " & A & ": " & (Begin.Marks(A)) & vbCrLf
Next A