ask permission,
I created a bot to input data to the web using vb.net and selenium.
Retrieve data from csv .
How to retrieve data from csv as needed, for example, there are 100 rows, only 30-50 rows are taken, for example. The loop code should not be looped at all.
Dim textFieldParser As TextFieldParser = New TextFieldParser(TextBox1.Text) With
{
.TextFieldType = FieldType.Delimited,
.Delimiters = New String() {","}
}
drv = New ChromeDriver(options)
While Not textFieldParser.EndOfData
Try
Dim strArrays As String() = textFieldParser.ReadFields()
Dim name As String = strArrays(0)
Dim alamat As String = strArrays(1)
Dim notlp As String = strArrays(2)
drv.Navigate().GoToUrl("URL")
Dim Nm = drv.FindElement(By.XPath("/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input"))
Nm.SendKeys(name)
Threading.Thread.Sleep(3000)
Catch ex As Exception
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
Thank you
Here's an example of using TextFieldParser to read one specific line and a specific range of lines. Note that I am using zero-based indexes for the lines. You can adjust as required if you want to use 1-based line numbers.
Public Function GetLine(filePath As String, index As Integer) As String()
Using parser As New TextFieldParser(filePath) With {.Delimiters = {","}}
Dim linesDiscarded = 0
Do Until linesDiscarded = index
parser.ReadLine()
linesDiscarded += 1
Loop
Return parser.ReadFields()
End Using
End Function
Public Function GetLines(filePath As String, startIndex As Integer, count As Integer) As List(Of String())
Using parser As New TextFieldParser(filePath) With {.Delimiters = {","}}
Dim linesDiscarded = 0
Do Until linesDiscarded = startIndex
parser.ReadLine()
linesDiscarded += 1
Loop
Dim lines As New List(Of String())
Do Until lines.Count = count
lines.Add(parser.ReadFields())
Loop
Return lines
End Using
End Function
Simple loops to skip and to take lines.
Related
I want merge multiple csv files with same layout from the same folder
example :
csv1.csv
ID, PINA,PINB,PCS
1,100,200,450
2,99,285,300
csv2.csv
ID, PINA,PINB,PCS
1,100,200,999
2,99,285,998
out.csv (The file I want make by VB.net)
ID, PINA,PINB,PCS,PCS
1,100,200,450,999
2,99,285,300,998
my problem code :
Dim FileReader As StreamReader
Dim i As Integer = 0
Dim temp As String
For i = 0 To LstFiles.Items.Count - 1
FileReader = File.OpenText(LstFiles.Items.Item(i))
temp = FileReader.ReadToEnd
File.AppendAllText(SaveFileDialog1.FileName, temp)
Next
Please guide me.
Thanks a lot !
Looks to me like each line in the input files has an identifier based on the first value in that row. You want to combine all the numbers after that identifier, from all the files in your ListBox, into one list of numbers that is sorted and has no duplicates. Then you want to generate an output file that has all those identifiers followed by each set of sorted, unique numbers.
If that is correct, then try this out:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
Dim header As String = ""
Dim combinedLines As New SortedList(Of Integer, List(Of Integer))
For Each filename As String In LstFiles.Items
Dim lines = File.ReadLines(filename)
If header = "" Then
header = lines.First
End If
lines = lines.Skip(1)
For Each line As String In lines
Dim strValues = line.Split(",").AsEnumerable
Try
Dim lineNumber As Integer = Integer.Parse(strValues.First)
strValues = strValues.Skip(1)
Dim numbers = strValues.ToList.ConvertAll(Of Integer)(Function(x) Integer.Parse(x))
If Not combinedLines.ContainsKey(lineNumber) Then
combinedLines.Add(lineNumber, New List(Of Integer)(numbers))
Else
combinedLines(lineNumber).AddRange(numbers)
End If
Catch ex As Exception
MessageBox.Show("Error Parsing Line: " & line)
End Try
Next
Next
Using sw As New StreamWriter(SaveFileDialog1.FileName, False)
sw.WriteLine(header)
For Each numberSet In combinedLines
Dim numbers = numberSet.Value.Distinct.ToList
numbers.Sort()
sw.WriteLine(numberSet.Key & "," & String.Join(",", numbers))
Next
End Using
End If
End Sub
I convert CSV file to DataTable using following code. It is working fine but sometimes it adds invalid character between the string.
Private Shared Function convertToDT(filePath As String) As DataTable
Dim detailDataTable As New DataTable()
Using csvReader As New TextFieldParser(filePath)
csvReader.SetDelimiters(New String() {","})
csvReader.HasFieldsEnclosedInQuotes = True
Dim colFields As String() = csvReader.ReadFields()
For Each column As String In colFields
Dim datecolumn As New DataColumn(column.ToLowerInvariant)
datecolumn.AllowDBNull = True
detailDataTable.Columns.Add(datecolumn)
Next
While Not csvReader.EndOfData
Dim rowData As String() = csvReader.ReadFields //sometimes rowData convert invalid name
For i As Integer = 0 To rowData.Length - 1
//perform operation
Next
If rowData IsNot Nothing AndAlso rowData(0) IsNot Nothing Then
If Not (rowData(0).StartsWith("#") Or String.IsNullOrEmpty(rowData(0))) Then
detailDataTable.Rows.Add(rowData)
End If
End If
End While
End Using
Return detailDataTable
End Function
Sometime it add invalid name. Can anybody please suggest
This code is supposed to output the number of times a word starts with a letter from the alphabet, but just displays zero for each one
I get no errors, but just a text file with all of the letters and zero for each one.
When pressing the debug button, it appears to do nothing. Here's the code
Imports System.IO
Module Module1
Sub Main()
Dim myArray As New List(Of String)
Using myReader As StreamReader = New StreamReader(".\myFile.txt")
'telling VB that we're using a StreamREader, read a line at a time
Dim myLine As String
myLine = myReader.ReadLine 'assigns the line to String Variable myLine
Do While (Not myLine Is Nothing)
myArray.Add(myLine) 'adding it to the list of words in the array
Console.WriteLine(myLine)
myLine = myReader.ReadLine
Loop
End Using
SortMyArray(myArray) 'Calls the new SubRoutine => SortMyArray, passing through the parameter myArray,
'created back on line 7 that stores all of the lines read from the text file.
'Console.ReadLine()
wordCount(myArray)
End Sub
Sub SortMyArray(ByVal mySort As List(Of String))
Dim Tmp As String, writePath As String = ".\sorted.txt"
Dim max As Integer = mySort.Count - 1
Dim myWriter As StreamWriter = New StreamWriter(writePath)
For Loop1 = 0 To max - 1
For Loop2 = Loop1 + 1 To max
If mySort(Loop1) > mySort(Loop2) Then
Tmp = mySort(Loop2)
mySort(Loop2) = mySort(Loop1)
mySort(Loop1) = Tmp
End If
Next
myWriter.WriteLine(mySort.Item(Loop1).ToString())
Next
myWriter.Dispose()
End Sub
Sub wordCount(ByVal stringArray As List(Of String))
Dim alphabet As String = "abcdefghijklmnopqrstuvwxyz", myString As String
Dim writePath As String = ".\counted.txt"
Dim myWriter As StreamWriter = New StreamWriter(writePath)
Dim countOf(25) As Integer, Max As Integer = stringArray.Count - 1
For Loop1 = 0 To 25
myString = alphabet.Substring(Loop1, 1)
For Loop2 = 0 To Max
If stringArray(Loop2).Substring(0, 1) = myString Then
countOf(Loop1) += 1
End If
Next
myWriter.WriteLine(myString & " occured " & countOf(Loop1) & " times ")
Next
myWriter.Dispose()
End Sub
End Module
Any help would be appreciated. Thanks
I have to import products from a denormalized table to Access 97 file. This scheme can't change, so I can't use SQL. I use the following routine to import the products. There are over 7000 products in the file and the function takes a long time. Is there any way to speed it up?
Public Sub ImportToOrders()
Try
'Dim actualFileName As String = IO.Path.GetFileName(filename)
'Dim streamReader As New IO.StreamReader(filename)
'Dim streamWriter As New IO.StreamWriter(filename & ".tsv")
'streamWriter.WriteLine()
'streamWriter.Close()
'streamWriter.Dispose()
Dim strFile As String = "C:\windows\figure.ini"
Dim strRet As String
Dim inifile As New IniFileManager
strRet = inifile.ReadINI(strFile, "DATABASE SECTION", "FILENAME", "")
Dim strPriCatFile As String = ""
strPriCatFile = "C:\three_software\incoming\skechers\Pricat.edi.tsv"
Dim fields As String()
Dim counter As Integer = 0
Dim delimiter As String = ControlChars.Tab
Using parser As New TextFieldParser(strPriCatFile)
parser.SetDelimiters(delimiter)
While Not parser.EndOfData
counter = counter + 1
' Read in the fields for the current line
fields = parser.ReadFields()
If counter = 1 Then
'this will be the header row we want to ignore this
Else
' the fiels we will go ahead and parse
WriteData(fields(1), fields(3), fields(4), fields(6), fields(5), fields(11), fields(8), fields(9), fields(11), fields(10), fields(12), fields(13), fields(14), "t")
End If
Debug.Write("Records Importing" + counter.ToString())
End While
End Using
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Write Data function
Public Function WriteData(sUPCode As String, sColourDescription As String, sSize As String, sColorCode As String, sDivsionDescription As String, sDescription As String, sDepartment As String, sSubDeparment As String, sProductShortDescription As String, sGender As String, sProductDescription As String, sCostPrice As String, sRetailPrice As String, sDiscountedPrice As String)
Try
Dim pricateTableAdapter As New SkechersPricatTableAdapter()
pricateTableAdapter.Insert(1, sUPCode, "stylenumber", sColourDescription, sSize, sColorCode, sDivsionDescription, sDepartment, sSubDeparment, sProductShortDescription, sGender, sProductDescription, sCostPrice, sRetailPrice, sDiscountedPrice)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Function
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