I have three variables declared as strings, is there a way to randomly choose one? [duplicate] - vb.net

This question already has answers here:
How can I randomly select one of three strings?
(2 answers)
Closed 8 years ago.
I have three strings, sUpperCase, sLowerCase and sNumbers. Each have either lower characters, upper characters or numbers. I need to know how to randomly choose one of these strings. I have thought maybe by assigning them a number but I am not sure how do to this without overriding the text inside of them. Maybe even an array but I'm not sure how to do this either. Can anybody help please?
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
ANSWER:
Function GeneratePassword() As String
'
' Declare two strings as the characters which the password can be created from
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
' Create a new random.
' Random is something which gets a random set of characters from a string.
Dim random As New Random
'
' Create sPassword as a new stringbuilder
' A stringbuilder is simply a class which builds a string from multiple characters
Dim sPassword As New StringBuilder
' Not random enough
'For i As Integer = 1 To 4
' Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
' sPassword.Append(sUpperCase.Substring(idxUpper, 1))
' Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
' sPassword.Append(sNumbers.Substring(idxNumber, 1))
' Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
' sPassword.Append(sLowerCase.Substring(idxLower, 1))
'Next
' Random select Upper, lower or numeric
' Check for a max number of this(three if's to check for which one it was, might need or in if)
' If yes randomly select another one
' If no get random char from that type
' Add to password
' Is the password complete?
' If yes return password, if not repeat
Dim iCountUpper As Integer = 0
Dim iCountLower As Integer = 0
Dim iCountNumber As Integer = 0
Do Until sPassword.Length = 10
'Needed help for this bit
Dim x = New Random(Now.GetHashCode)
Dim y = {"sLowerCase", "sUpperCase", "sNumbers"}
Dim z = y(x.Next(0, y.Length))
If z.Contains("sLowerCase") And iCountUpper < 4 Then
Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
sPassword.Append(sUpperCase.Substring(idxUpper, 1))
iCountUpper = iCountUpper + 1
ElseIf z.Contains("sUpperCase") And iCountLower < 4 Then
Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
sPassword.Append(sLowerCase.Substring(idxLower, 1))
iCountLower = iCountLower + 1
ElseIf z.Contains("sNumbers") And iCountNumber < 2 Then
Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
sPassword.Append(sNumbers.Substring(idxNumber, 1))
iCountNumber = iCountNumber + 1
Else
End If
Loop
'
' Return the password as a string
Return sPassword.ToString
End Function

You could do something like this:
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
Dim x = New Random(Now.GetHashCode)
Dim y = {sLowerCase, sUpperCase, sNumbers}
Dim z = y(x.Next(0, y.Length))
Debug.Print(z)

Dim strings = {"qwertyuiopasdfghjklzxcvbnm", "MNBVCXZLKJHGFDSAPOIUYTREWQ", "1234567890"}
Dim selected As String
Dim Generator As System.Random = New System.Random()
selected = strings(Generator.Next(0, strings.GetUpperBound(0)))

Create an array with your strings:
Dim array As String() = New String() {sLowerCase, sUpperCase, sNumbers}
Use Random class to generate random number between 0 and the array lenght:
Dim random As Random = New Random(DateTime.Now.Ticks)
Dim randomChoose As String = array(random.Next(0, array.Length - 1))
Select a random char:
Dim ch As Char = randomChoose(random.Next(0, randomChoose.Length - 1))

Related

Getting the character that inside the brackets

This is my string:
Dim value as string = "IR_10748(1).jpg"
How can I get this number 1 into another variable? I am thinking to use split.
How I can use to get this value in vb.net?
See String.Substring(Integer, Integer) and String.IndexOf(String).
Dim value As String = "IR_10748(1).jpg"
Dim startIndex As Integer = value.IndexOf("(") + 1
Dim length As Integer = value.IndexOf(")") - startIndex
Dim content As String = value.Substring(startIndex, length)
Regular expressions might be cleaner. This should work:
dim Result as string = Regex.Match(value, "(?<=\().*(?=\))").Value
It'll extract one or more characters contained between the parentheses.
Try this:
Dim value as String = "IR_10748(1).jpg"
Dim splitStrings() as String
'Split on either opening or closing parenthesis -
'This will give 3 strings - "IR_10748","1",".jpg"
splitStrings = value.Split(New String() {"(",")"}, StringSplitOptions.None)
'Parse as integer if required
Dim i as Integer
i = Integer.Parse(splitStrings(1))
Demo
It's not the prettiest, but this gets "1" using Remove and Split :
Dim value as String = "IR_10748(1).jpg"
Dim num As String = value.Remove(0, value.IndexOf("(") + 1).Split(")")(0)
That gives num = "1"
You can get the number more reliably than using String.Split. You'll want to use LastIndexOf to get the final opening parenthesis just in case you have a filename like "a(whatever)(1).ext", and you should inspect the filename without its extension, in case you have a filename like "a(1).(9)":
Dim value As String = "IR_10748(1).jpg"
Dim fn = Path.GetFileNameWithoutExtension(value)
Dim lastOpen = fn.LastIndexOf("(")
If lastOpen >= 0 Then
Dim length = fn.IndexOf(")", lastOpen + 1) - lastOpen - 1
If length >= 1 Then
Dim numAsString = fn.Substring(lastOpen + 1, length)
Console.WriteLine(numAsString)
ElseIf length = 0 Then
' do something if required
Console.WriteLine("No number in the parentheses.")
Else
' do something if required
Console.WriteLine("No closing parenthesis.")
End If
Else
' do something if required
Console.WriteLine("No opening parenthesis.")
End If

make my password generator generate 'complex' passwords

I've got a password generator in one of my scripts which generates 2 passwords and writes them to a database.
These passwords are later retrieved and set as the windows logon passwords for 2 users which are automatically created in a virtual machine.
I have a problem whereby my passwords are not always considered to be complex as far as windows is concerned.
I am using the following function to generate my passwords...
Public Function GeneratePassword(ByVal len As Integer) As String
Dim str As String = "1234567890qwertyuio1pa2sd3fg4hj5kl6zx7cv8bn9mQ0WE1RT2YU3IO4PA5SD6FG7HJ8KL9ZX0CVBNM"
Dim N As Integer = str.Length
Dim rnd As New Random((Now.Hour * 3600 + Now.Minute * 60 +
Now.Second) * 1000 + Now.Millisecond)
Dim sb As New StringBuilder
For l As Integer = 1 To len
sb.Append(str.Substring(rnd.Next(0, N), 1))
Next
Return sb.ToString
End Function
Which is then called like this...
Dim vm_password1 As String = GeneratePassword(10)
How would i best go about modifying this code to ensure that each password generated contains 1 uppercase character, 1 lowercase character and one number?
Any help appreciated! :)
Of course you can extend this further, but here's the jist
Public Function fnGenPw() As String
Dim RandomClass As New Random()
Const legalAlpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Const legalNums As String = "1234567890"
Dim strbNewpw As New StringBuilder
For i As Integer = 0 To 2 'first 3 characters are alpha
Dim RandomNumber As Integer = RandomClass.Next(legalAlpha.Length - 1)
strbNewpw.Append(legalAlpha.Chars(RandomNumber))
Next
For i As Integer = 3 To 5 'characters 4,5,6 are numeric
Dim RandomNumber As Integer = RandomClass.Next(legalNums.Length - 1)
strbNewpw.Append(legalNums.Chars(RandomNumber))
Next
For i As Integer = 6 To 9 'characters 7,8,9,10 are alpha
Dim RandomNumber As Integer = RandomClass.Next(legalAlpha.Length - 1)
strbNewpw.Append(legalAlpha.Chars(RandomNumber))
Next
Return strbNewpw.ToString
End Function

Encrypter with Key and Message - VB.Net

Okay, so I am trying to make my program take whatever your key is, and loop through each character of the key, then find the ascii code for each character code, and then loop through each character of the message, finding the ascii code of each of them, and adding the key code to the message code, doing this for each character in the key, to each character in the message. I ran into a little problem, it changes the message right after the first letter is added, and I can't figure out how to fix it, any help would be great!
Basically, all I want is to that the ascii code for the key characters and add them to the ascii code for the message characters, then convert that final code back to the new characters in the message text. Using this:
tbxMessage.Text = (AscW(Mid(tbxMessage.Text, xForMess, 1)) + AscW(vTemp))
Here is everything I've got so far:
Public Class Form1
Function fctEncryptDecrypt(pMess As String, pKey As String) As String
If Len(tbxMessage.Text) > 0 Then
Dim xForKey As Integer
Dim xForMess As Integer
Dim intKey As Integer
Dim intMessage As Integer
Dim strAsciiKeyChar As String
Dim intAsciiKeyChar As Integer
Dim strAsciiMesChar As String
Dim intAsciiMesChar As Integer
Dim vTemp As String
Dim vTempMess As String
intKey = Len(tbxKey.Text)
intMessage = Len(tbxMessage.Text)
For xForKey = 1 To intKey
strAsciiKeyChar = Mid(tbxKey.Text, xForKey, 1)
intAsciiKeyChar = AscW(strAsciiKeyChar)
vTemp = intAsciiKeyChar
For xForMess = 1 To intMessage
strAsciiMesChar = Mid(tbxMessage.Text, xForMess, 1)
intAsciiMesChar = AscW(strAsciiMesChar)
vTempMess = vTemp + intAsciiMesChar
tbxMessage.Text = (AscW(Mid(tbxMessage.Text, xForMess, 1)) + AscW(vTemp))
Next xForMess
Next xForKey
Label1.Text = vTemp
Else
MessageBox.Show("No Message Found")
End If
End Function
Private Sub btnEncrypt_Click(sender As System.Object, e As System.EventArgs) Handles btnEncrypt.Click
fctEncryptDecrypt(tbxMessage.Text, tbxKey.Text)
End Sub
End Class
tbxMessage.Text = (AscW(Mid(tbxMessage.Text, xForMess, 1)) + AscW(vTemp))
in the inner For loop is setting the value of the text box to a number.
I'd expect the use of a temporary string variable that collects
Chr((intAsciiKeyChar + intAsciiMesChar) mod 256)
I'd also expect the key to be applied one letter at a time over the message. Something like:
Dim i as Integer
Dim s as String
Dim sKey as String
Dim sMesg as String
Dim intCharacter as Integer
s = ""
For i = 1 to len(tbxMessage.Text)
sKey = Mid(tbxKey.Text, (i mod Len(tbxKey)) + 1, 1)
sMesg = Mid(tbxMessage.Text, i, 1)
intCharacter = (WAsc(sKey) + WAsc(sMesg)) mod 256
s = s & Chr(intCharacter)
Next
tbxMessage.Text = s

generate random string

well i know that there are a lot of these threads but im new to vb.net yet i cant edit the sources given to make what i really want
so i want a function that will generate random strings which will contain from 15-32 characters each and each of them will have the following chars ( not all at the same string but some of them ) :
A-Z
a-z
0-9
here is my code so far
Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Change the string to include the a-z characters:
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Change the loop to create a random number of characters:
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Note that the upper boundary in the Next method is exclusive, so Next(15, 33) gives you a value that can range from 15 to 32.
Use the length of the string to pick a character from it:
Dim idx As Integer = r.Next(0, s.Length)
As you are going to create random strings, and not a single random string, you should not create the random number generator inside the function. If you call the function twice too close in time, you would end up with the same random string, as the random generator is seeded using the system clock. So, you should send the random generator in to the function:
Function RandomString(r As Random)
So, all in all:
Function RandomString(r As Random)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim sb As New StringBuilder
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Usage example:
Dim r As New Random
Dim strings As New List<string>()
For i As Integer = 1 To 10
strings.Add(RandomString(r))
Next
Try something like this:-
stringToReturn&= Guid.NewGuid.ToString().replace("-","")
You can also check this:-
Sub Main()
Dim KeyGen As RandomKeyGenerator
Dim NumKeys As Integer
Dim i_Keys As Integer
Dim RandomKey As String
''' MODIFY THIS TO GET MORE KEYS - LAITH - 27/07/2005 22:48:30 -
NumKeys = 20
KeyGen = New RandomKeyGenerator
KeyGen.KeyLetters = "abcdefghijklmnopqrstuvwxyz"
KeyGen.KeyNumbers = "0123456789"
KeyGen.KeyChars = 12
For i_Keys = 1 To NumKeys
RandomKey = KeyGen.Generate()
Console.WriteLine(RandomKey)
Next
Console.WriteLine("Press any key to exit...")
Console.Read()
End Sub
Using your function as a guide, I modified it to:
Randomize the length (between minChar & maxCharacters)
Randomize the string produced each time (by using the static Random)
Code:
Function RandomString(minCharacters As Integer, maxCharacters As Integer)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(minCharacters, maxCharacters)
Dim sb As New StringBuilder
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
Return sb.ToString()
End Function
Try this out:
Private Function RandomString(ByRef Length As String) As String
Dim str As String = Nothing
Dim rnd As New Random
For i As Integer = 0 To Length
Dim chrInt As Integer = 0
Do
chrInt = rnd.Next(30, 122)
If (chrInt >= 48 And chrInt <= 57) Or (chrInt >= 65 And chrInt <= 90) Or (chrInt >= 97 And chrInt <= 122) Then
Exit Do
End If
Loop
str &= Chr(chrInt)
Next
Return str
End Function
You need to change the line For i As Integer = 1 To 8 to For i As Integer = 1 To ? where ? is the number of characters long the string should be. This changes the number of times it repeats the code below so more characters are appended to the string.
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
My $.02
Dim prng As New Random
Const minCH As Integer = 15 'minimum chars in random string
Const maxCH As Integer = 35 'maximum chars in random string
'valid chars in random string
Const randCH As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Private Function RandomString() As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To prng.Next(minCH, maxCH + 1)
sb.Append(randCH.Substring(prng.Next(0, randCH.Length), 1))
Next
Return sb.ToString()
End Function
please note that the
r.Next(0, 35)
tend to hang and show the same result Not sure whay; better to use
CInt(Math.Ceiling(Rnd() * N)) + 1
see it here Random integer in VB.NET
I beefed up Nathan Koop's function for my own needs, and thought I'd share.
I added:
Ability to add Prepended and Appended text to the random string
Ability to choose the casing of the allowed characters (letters)
Ability to choose to include/exclude numbers to the allowed characters
NOTE: If strictly looking for an exact length string while also adding pre/appended strings you'll need to deal with that; I left out any logic to handle that.
Example Usages:
' Straight call for a random string of 20 characters
' All Caps + Numbers
String_Random(20, 20, String.Empty, String.Empty, 1, True)
' Call for a 30 char string with prepended string
' Lowercase, no numbers
String_Random(30, 30, "Hey_Now_", String.Empty, 2, False)
' Call for a 15 char string with appended string
' Case insensitive + Numbers
String_Random(15, 15, String.Empty, "_howdy", 3, True)
.
Public Function String_Random(
intMinLength As Integer,
intMaxLength As Integer,
strPrepend As String,
strAppend As String,
intCase As Integer,
bIncludeDigits As Boolean) As String
' Allowed characters variable
Dim s As String = String.Empty
' Set the variable to user's choice of allowed characters
Select Case intCase
Case 1
' Uppercase
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Case 2
' Lowercase
s = "abcdefghijklmnopqrstuvwxyz"
Case Else
' Case Insensitive + Numbers
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
End Select
' Add numbers to the allowed characters if user chose so
If bIncludeDigits = True Then s &= "0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(intMinLength, intMaxLength)
Dim sb As New StringBuilder
' Add the prepend string if one was passed
If String.IsNullOrEmpty(strPrepend) = False Then sb.Append(strPrepend)
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
' Add the append string if one was passed
If String.IsNullOrEmpty(strAppend) = False Then sb.Append(strAppend)
Return sb.ToString()
End Function

Separating Delimited Variable into array elements in VB.NET

I long variable in vb.net which contains the following information,
Dim g As String = "$C:\Program Files\Cavaj Java Decompiler\cavaj.exe$C:\Users\Yoosuf\AppData\Local\Google\Chrome\Application\chrome.exe$C:\Program Files\DVD Maker\dvdmaker.exe$C:\Program Files\Adobe\Adobe Photoshop CS2\ImageReady.exe$C:\Program Files\Java\jre6\bin\javaws.exe$"
The $ symbol is used as a delimiter to separate each item from the other. I need to add the exe file name at the end of each path to a listbox. However the initial process of retrieving the variable to individual array elements is not working properly.
Dim strArr() As String = g.Split("$") 'This variable is empty
For count = 0 To strArr.Length - 1
Dim arr As String = strArr(count).Split("\")
Dim strval As String = ""
For i As Integer = 3 To arr.Length - 1
strval = arr(i)
Dim j As Integer = arr.Length - 1
strval = arr(j)
Dim result As String = strval.Substring(g.Length - 5)
result = g.Substring(g.LastIndexOf("\") + 1)
ListBox1.Items.Add(result)
Next
Next
No need to do all this work. The System.IO.Path class has methods to do this for you. You want to use either System.IO.Path.GetFileName or System.IO.Path.GetFileNameWithoutExtension. Since you've already split all the file paths, just pass those paths to either of the aforementioned methods and add the result to your listbox.
Dim strArr() As String = g.Split("$")
For Each path As String In strArr
ListBox1.Items.Add(System.IO.Path.GetFileName(path))
Next
Please refer to the code below and the associated comments. Also I have comment out some code which I feel is not required based on what you want to do.
Dim strArr() As String = g.Split("$") 'This variable is empty
For count = 0 To strArr.Length - 1
Dim arr() As String = strArr(count).Split("\") ' Split returns an array
Dim strval As String = ""
For i As Integer = 3 To arr.Length - 1
'strval = arr(i)
Dim j As Integer = arr.Length - 1
strval = arr(j)
'Dim result As String = strval.Substring(g.Length - 5)
'result = g.Substring(g.LastIndexOf("\") + 1)
ListBox1.Items.Add(strval)
Next
Next