Random String in VB - vb.net

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

Related

how to read a specific csv line vb.net

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.

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

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

Create a search bar for hex values

My current code requires me to edit the search value while the project is still in VB. I have not been able to figure out how to code the input value to use a textbox for search. I would really like to be able to build this project and use it without having VB open. Below is my code:
Dim filePath As String = Me.TextBox1.Text 'The path for the file you want to search
Dim fInfo As New FileInfo("C:\MyFile.File")
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream("C:\MyFile.File", FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
Dim pos As Integer = -1
Dim searchItem As String = "b6" 'The hex values of what you want to search
Dim searchItemAsInteger As Integer
Dim locationsFound As New List(Of Integer)
MessageBox.Show("Wait while I Scan?")
br.Close()
fStream.Close()
Integer.TryParse(searchItem, Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture, searchItemAsInteger)
For Each byteItem As Byte In data
pos += 1
If CInt(byteItem) = searchItemAsInteger Then
locationsFound.Add(pos)
Me.ListBox1.Items.Add(Hex(pos))
End If
Next
For i As Integer = 0 To Me.ListBox1.Items.Count - 1
Me.ListBox1.SetSelected(i, True)
Next
End Sub
Place a textbox named "txtHexValueToSearch" inside Form1. And then replaces the code that is commented:
' Dim searchItem As String = "b6" 'The hex values of what you want to search
Dim searchItem As String = Me.txtHexValueToSearch.Text 'The hex values of what you want to search

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help

Generate random alphanumeric string

I am trying to generate a random code in vb.net like this
Dim r As New Random
Response.Write(r.Next())
But I want to generate code with 6 digits and should be alphanumeric like thie A12RV1 and all codes should be like this.
I have tried vb.net random class but I am unable to do that like as I want. I want to get the alphanumeric code each time when I execute the code. How can i achieve this in vb.net?
Try something like this:
Public Function GetRandomString(ByVal iLength As Integer) As String
Dim sResult As String = ""
Dim rdm As New Random()
For i As Integer = 1 To iLength
sResult &= ChrW(rdm.Next(32, 126))
Next
Return sResult
End Function
Or you can do the common random string defining the valid caracters:
Public Function GenerateRandomString(ByRef iLength As Integer) As String
Dim rdm As New Random()
Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
Dim sResult As String = ""
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End Function
I think this will suits your requirement,
Private sub GenerateString()
Dim xCharArray() As Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray
Dim xNoArray() As Char = "0123456789".ToCharArray
Dim xGenerator As System.Random = New System.Random()
Dim xStr As String = String.Empty
While xStr.Length < 6
If xGenerator.Next(0, 2) = 0 Then
xStr &= xCharArray(xGenerator.Next(0, xCharArray.Length))
Else
xStr &= xNoArray(xGenerator.Next(0, xNoArray.Length))
End If
End While
MsgBox(xStr)
End Sub
Note: Tested With IDE
EDIT: Modified according to SYSDRAGON's Comment