Best Way to parse File - vb.net

I have a string with following format
Zone: 1 Events: 3
Zone: 2 Events: 7
i am parsing the file with following code
Dim strarr() As String
strarr = Str.Split("/n")
for i = 0 to 2
dim strarrNew() as string
strarrNew = strarr(i)Split(" ")
use value strarrNew(0)
use value strarrNew(1)
next
and i am using values directly but if their is a mistake in the string input
Zone:1Events: 3
spaces are missing than code will not work.
What would be the best way to parse file.

You can adopt this solution only if all the inputs from the file is of the same format:
For Each line As String In File.ReadAllLines("F:\sample.txt")
Dim strarrNew() As String = line.Split(":"c.ToCharArray())
Dim zone As Integer = CInt(Val(strarrNew(1)))
Dim events As Integer = CInt(Val(strarrNew(2)))
'Perform your operations
Next

Related

Getting data from dataset

I have got a problem, I have got a filled dataset, but now i need to get a Column value from it and store it into a variable. On Button 2 click i fill it with this:
tbaGridview.Fill(BlGridview1.vwBLcontainerCargo, Bookingnumber)
Now i want to get the data from it that is inside. I have got a for loop:
For i As Integer = 0 To GridView1.DataRowCount - 1
Dim OriginSealNumber As String = BlGridview1.vwBLcontainerCargo.Tables("SEALNUMBER").Rows(i).Item(0)
Next i
But it says Tables is not a member of windowsapplication1.blgridView.vwBLContainerCargoDataTable. How do i get the data for each column??
To reference the GridView's table use this sintax:
((DataRowView)GridView1.Rows[0].DataBoundItem).DataView.Table
But I recommend that you use a BindingSource object and iterate through it.
I fixed it myself by using this:
For i As Integer = 0 To GridView1.DataRowCount - 1
Dim OriginSealNumber As String = BlGridview1.Tables(0).Rows(i)("SEALNUMBER").ToString()
Dim OriginContainerNumber As String = BlGridview1.Tables(0).Rows(i)("CONTAINERNUMBER").ToString()
Dim OriginContainerType As String = BlGridview1.Tables(0).Rows(i)("CONTAINERTYPE").ToString()
Dim OriginQuantity As String = BlGridview1.Tables(0).Rows(i)("QUANTITY").ToString()
Dim OriginPackageType As String = BlGridview1.Tables(0).Rows(i)("PACKAGETYPE").ToString()
Dim OriginDescription As String = BlGridview1.Tables(0).Rows(i)("DESCRIPTION").ToString()
Dim OriginWeight As String = BlGridview1.Tables(0).Rows(i)("WEIGHT").ToString()
Next i

String Manipulation To Get An Item In The Middle Of A CSV File

I have a csv file I need to parse and get an item out of the middle of it. I have chose string manipulation to do this.
sample input file data would be..
Nick,frog,snake,1234
I can get the last entry "1234" with this code..
line.Substring(line.LastIndexOf(",") + 1)
How would I get the 3rd entry, "snake", with substrings? (what the OP means is: how can I get the third element in the comma-separated string, which happens to be "snake")
If you've stored the text of your file in myInputText, and you want to access the third item, the following will work:
resultString = Strings.Split(myInputText, ",")(2)
You can access any string in the file this way.
How would I get the 3rd entry "snake" with substrings?
The easiest way would obviously be with split:
Dim teststr As String = "Nick,frog,snake,1234"
Dim teststr2 As String = teststr.Split(","c)(2)
A simple function like this, using substring, will do the same thing:
Dim teststr3 As String = GetStr(teststr, 2)
Private Function GetStr(input As String, index As Integer) As String
input += ","
Dim counter As Integer = 0
If index <> 0 Then
Do
input = input.Substring(input.IndexOf(","c)).TrimStart(","c)
counter += 1
Loop Until counter = index
End If
GetStr = input.Substring(0, input.IndexOf(","c))
End Function

how to get the fix substring from dynamic string content?

I am developing VB.NET windows app. in VS 2010.
I want to get the substring
$CostCenterId|4^10
from the below string .
PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$
The position of current string ($CostCenterId|4^10) in the sequence may be change.
but it will always between the two $ sign.
I have written the below code, but confused abt what to write next ?
Public Sub GetSubstringData()
dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
sDiscription.Substring(CostIndex,
End Sub
Have a look into the Split function of a string. This allows you to split a string into substrings based on a specified delimiting character.
You can then do this:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Debug.WriteLine("$" + sfullString.Split("$"c)(3))
Result: $CostCenterId|4^10
You will probably want to do some error checking to make sure the string actually contains the data you expect though.
However looking at the data, what you have is a string containing key-value pairs so you would be better to have a property to hold the CostCenterId and extract the data like this:
Public Property CostCenterId As String
Public Sub Decode(ByVal code As String)
For Each pair As String In code.Split("$"c)
If pair.Length > 0 AndAlso pair.Contains("|") Then
Dim key As String = pair.Split("|"c)(0)
Dim value As String = pair.Split("|"c)(1)
Select Case key
Case "CostCenterId"
Me.CostCenterId = value
End Select
End If
Next
End Sub
Then call it like this:
Decode("PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$")
Why not split() the string by $ into an array, and then look for the element which contains CostCenterId
This should work:
Dim token = "$CostCenterId"
Dim costIndexStart As Integer = sfullString.IndexOf(token)
Dim costIndexEnd As Integer = sfullString.IndexOf("$", costIndexStart + token.Length)
Dim cost As String = sfullString.Substring(costIndexStart, costIndexEnd - costIndexStart + 1)
Result: "$CostCenterId|4^10$"
If you want to omit the dollar-signs:
Substring(costIndexStart + 1, costIndexEnd - costIndexStart - 1)
Try something like this:
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
auxNum = sDiscription.IndexOf("$"c, CostIndex) - CostIndex
sResult = sDiscription.SubString(CostIndex, auxNum)
Your string,
Dim xString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Substring process,
xString = xString.Substring(xString.IndexOf("$CostCenter"), xString.IndexOf("$", xString.IndexOf("$CostCenter") + 1) - xString.IndexOf("$CostCenter"))
Try this Code:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian" _
& "Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim sp() As String = {"$"}
Dim ar() As String = sfullString.Split(sp, StringSplitOptions.RemoveEmptyEntries)
Array.Sort(ar)
MsgBox("$" & ar(0))

Mixed Encoding to String

I have a string in VB.net that may contain something like the following:
This is a 0x000020AC symbol
This is the UTF-32 encoding for the Euro Symbol according to this article http://www.fileformat.info/info/unicode/char/20ac/index.htm
I'd like to convert this into
This is a € symbol
I've tried using UnicodeEncoding() class in VB.net (Framework 2.0, as I'm modifying a legacy application)
When I use this class to encode, and then decode I still get back the original string.
I expected that the UnicodeEncoding would recognise the already encoded part and not encode it against. But it appears to not be the case.
I'm a little lost now as to how I can convert a mixed encoded string into a normal string.
Background: When saving an Excel spreadsheet as CSV, anything outside of the ascii range gets converted to ?. So my idea is that if I can get my client to search/replace a few characters, such as the Euro symbol, into an encoded string such as 0x000020AC. Then I was hoping to convert those encoded parts back into the real symbols before I insert to a SQL database.
I've tried a function such as
Public Function Decode(ByVal s As String) As String
Dim uni As New UnicodeEncoding()
Dim encodedBytes As Byte() = uni.GetBytes(s)
Dim output As String = ""
output = uni.GetString(encodedBytes)
Return output
End Function
Which was based on the examples on the MSDN at http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.aspx
It could be that I have a complete mis-understanding of how this works in VB.net. In C# I can simply use escaped characters such as "\u20AC". But no such thing exists in VB.net.
Based on advice from Heinzi I implemented a Regex.Replace method using the following code, this appear to work for my examples.
Public Function Decode(ByVal s As String) As String
Dim output As String = ""
Dim sRegex As String = "0x[0-9a-zA-Z]{8}"
Dim r As Regex = New Regex(sRegex)
Dim myEvaluator As MatchEvaluator = New MatchEvaluator(AddressOf HexToString)
output = r.Replace(s, myEvaluator)
Return output
End Function
Public Function HexToString(ByVal hexString As Match) As String
Dim uni As New UnicodeEncoding(True, True)
Dim input As String = hexString.ToString
input = input.Substring(2)
input = input.TrimStart("0"c)
Dim output As String
Dim length As Integer = input.Length
Dim upperBound As Integer = length \ 2
If length Mod 2 = 0 Then
upperBound -= 1
Else
input = "0" & input
End If
Dim bytes(upperBound) As Byte
For i As Integer = 0 To upperBound
bytes(i) = Convert.ToByte(input.Substring(i * 2, 2), 16)
Next
output = uni.GetString(bytes)
Return output
End Function
Have you tried:
Public Function Decode(Byval Coded as string) as string
Return StrConv(Coded, vbUnicode)
End Function
Also, your function is invalid. It takes s as an argument, does a load of stuff and then outputs the s that was put into it instead of the stuff that was processed within it.

Split a String into 2 Variables

What I'm trying to do here is Capture 2 Variables from a Textbox
Here is an example of whats going to be in here.
User:Pass
I want to declare everything before the : as user and everything after the : as pass.
I've Googled, and found a few things, but I couldn't seem to get it working fully.
Dim words As String() = textbox1.text.Split(":")
Dim user as String = words(0)
Dim pass as String = words(1)
Dim str = "User:Pass"
Dim split = str.Split(":")
Dim user as String
Dim password as String
If (split.Count = 2) then
user=split(0).ToString()
password = split(1).ToString()
End If
Split on the :, if there are 2 entries in the resulting array, populate the user variable with the first item, and the password variable with the second.
Have a look at the split function.
http://msdn.microsoft.com/en-us/library/6x627e5f%28v=vs.80%29.aspx
Dim user As String
Dim pass As String
Dim iPosEQ As Integer
iPosEQ = textbox1.text.IndexOf(":", System.StringComparison.Ordinal)
kv(0) = textbox1.text.Substring(0, iPosEQ - 1)
kv(1) = textbox1.text.Substring(iPosEQ + 1)
This works even with passwords (or users) with ":"