Have a Function which is converting string to hex. its fine working with a textbox and a button. But in my project theres a console form and theres a richtext box as output and a textbox as inputbox. users have to type commands and press enter to execute orders.
i'm trying to make it like : hex "string"
here is current state of inputbox code:
Private Sub consoleinputbox_KeyDown(sender As Object, e As KeyEventArgs) Handles consoleinputbox.KeyDown
Dim Command As String = consoleinputbox.Text
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
Output(Command)
CallCommand(Command)
End If
End Sub
output function is appending text to richtextbox. CallCommand function is like this:
Public Function CallCommand(s As String) 'seperate commands as func.
Dim ss As String = s.ToLower()
ss = ss.Trim
Select Case ss
Case "cls"
GetRtb.rtb.Clear()
Case "help cls"
GetRtb.rtb.AppendText("Obviusly clear your console screen..." & vbCrLf)
Return True
Case "ping"
GetRtb.rtb.AppendText("insufficient parameters. type help ping for more information..." & vbCrLf)
Return True
Case "help ping"
GetRtb.rtb.AppendText("usage: ping [hostname or ip]" & vbCrLf)
Return True
Case "help"
GetRtb.rtb.AppendText("Avaliable commands:" & vbCrLf)
GetRtb.rtb.AppendText(avaliablecommands(s))
Return True
Case Else
GetRtb.rtb.AppendText("Bad command or filename..." & vbCrLf)
Return False
End Select
End Function
how can i check consoleinputbox.text if it have spaces and
if there is spaces how can i seperate first word as command and rest as parameters?
as you can see like "ping www.me.com" or "hex asdasd"
Thank you!
i think this is solved problem but if i need more parameters i have to make more functions like Callcommand2 etc...
inputbox code:
Private Sub consoleinputbox_KeyDown(sender As Object, e As KeyEventArgs) Handles consoleinputbox.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
Dim text As String = consoleinputbox.Text
Dim Command As String()
Command = text.Split(" ")
If Command.Length = 1 Then
text.Trim()
Output(text)
CallCommand(Command(0))
ElseIf Command.Length = 2 Then
Output(text)
CallCommand1(Command(0), Command(1))
End If
End If
End Sub
and rest of module;
Public Sub Output(s As String)
If s <> "" Then
GetRtb.rtb.AppendText(s & vbCrLf)
GetTb.tb.Clear()
GetTb.tb.Focus()
End If
End Sub
Public Function CallCommand(c1 As String)
c1.ToLower()
Select Case c1
Case "cls"
GetRtb.rtb.Clear()
Case "help"
Output("Avaliable Commands")
Call avaliablecommands()
Case "hex"
Output("insufficent parameters. use: help hex")
Case "ascii"
Output("insufficent parameters. use: help ascii")
Case Else
Output("Bad command or filename...")
End Select
Return True
End Function
Public Function CallCommand1(c1 As String, p2 As String)
c1.ToLower()
p2.ToLower()
Select Case c1
Case "help"
help_par(p2)
Case "hex"
hex_par(p2)
Case "ascii"
ascii_par(p2)
End Select
Return True
End Function
Function help_par(p As String)
Select Case p
Case "ping"
Output("usage: ping [hostname or ip]")
Case "cls"
Output("obviusly clears you console...")
Case "hex"
Output("converts string to hexcimal code. usage: hex <string>")
Case "ascii"
Output("converts hexcimal code to string. usage: ascii <hexcode>")
End Select
Return True
End Function
Function hex_par(p As String)
Dim sth As String = StringToHex(p)
Output(sth)
Return True
End Function
Function ascii_par(p As String)
Dim tostring As String = HexToString(p)
Output(tostring)
Return True
End Function
Public Sub avaliablecommands()
Output("help, cls, ping, hex, ascii")
End Sub
End Module
im very very new to programming so please need ideas.
Related
Module Module1
Dim database As New Dictionary(Of String, String)
Dim ulist As New List(Of String)
Dim plist As New List(Of String)
Dim newname As String
Dim passw As String
Sub main()
menu() '
End Sub
Sub menu()
Console.WriteLine("type 1, 2 or 3")
Console.WriteLine("1 : create a new account")
Console.WriteLine("2: log in ")
Console.WriteLine("3 : quit program")
Dim choice As String
choice = Console.ReadLine()
If choice = "1" Then
create()
ElseIf choice = "2" Then
login()
ElseIf choice = "3" Then
Console.WriteLine("quitting...")
Console.Clear()
End If
End Sub
Sub login()
Dim unamever As String
Dim passwvari
Dim veri3 As Boolean = False
While veri3 = False
Console.WriteLine("please enter you username")
unamever = Console.ReadLine()
If ulist.Contains(unamever) Then
Console.WriteLine("please enter your password : ")
passwvari = Console.ReadLine()
If plist.Contains(passwvari) Then
Console.WriteLine("logging you in...")
veri3 = True
Else
Console.WriteLine("password incorrect try again")
veri3 = False
End If
Else
Console.WriteLine("username not registered try again")
veri3 = False
End If
End While
End Sub
Sub create()
Dim veri As Boolean = False
Dim attempts As Integer = 1
Do Until veri = True
Console.WriteLine("enter a new username")
newname = Console.ReadLine()
If ulist.Contains(newname) Then
Console.WriteLine("that username is already taken, try again")
attempts = attempts + 1
veri = False
Else
ulist.Add(newname)
Console.WriteLine("your new username has been stored")
notused()
veri = True
database.Add(newname, passw)
Console.WriteLine("succes you have made an account you username :" & newname & " and password: " & passw)
FileOpen(1, "C:\Users\iivix\OneDrive\Documents\A LEVEL\passws.txt", OpenMode.Output)
PrintLine(1, newname & passw)
End If
If attempts > 4 Then
Console.WriteLine("you have had more than 3 tries, BYE")
Console.Clear()
End If
Loop
End Sub
Sub notused()
Dim veri2 As Boolean = False
While veri2 = False
Console.WriteLine("create a password " & newname)
passw = Console.ReadLine
Dim passwlen = Len(passw)
If passwlen > 12 Then
Console.WriteLine("your password has been stored ")
plist.Add(passw)
veri2 = True
Else
Console.WriteLine("try again password must be greater than 12 characters")
veri2 = False
End If
End While
End Sub
End Module
This code is for a login system, I am a vb beginner and this is my code so far I have come across a problem: why aren't the usernames being stored when I try to log in later, how can I fix this? I want the user to be able to log back into an account when it is created another problem when writing usernames and passwords to a text file the new username overwrites the last, I want the usernames to be consecutively listed along with passwords'
BTW this isn't homework, its a beginners programming challenge
I have updated your code to use .net methods rather than obsolete VB6 methods. I made the LoginPath a Module level variable so it can be seen my all the methods in the Module. I am using a Dictionary rather than your 2 List(Of String)s. This way the username is the key and the password in the value. Dictionary lookup is very fast.
The first thing to do is to read the file and and fill the dictionary. If the file doesn't yet exist the user is informed.
The Create method changes a bit with the use of the Dictionary. I used the .net File class to write to the text file.
File.AppendAllLines(LoginPath, {$"{newname},{passw}"})
This is a very clever method. If the file doesn't exist, it creates it. It opens the file writes to the file and closes it. The first parameter is the path. The second parameter is what to write to the file, a String array. Notice the method names ends with AllLines, plural. The outer braces indicate that this is an array. Our array has only one element. I used an interpolated string indicated by the $ preceding the string. We can then insert variables directly into the string surrounded by braces. The comma is a literal in the string. We use the comma as a delimiter when the string is split into name and password.
Private LoginPath As String = "C:\Users\iivix\OneDrive\Documents\A LEVEL\passws.txt"
Private LoginDict As New Dictionary(Of String, String)
Sub Main()
ReadLoginFileAndFillDictionary()
menu()
Console.ReadKey()
End Sub
Private Sub Menu() 'Names of Subs, Functions etc. should begin with capital letters
Console.WriteLine("type 1, 2 or 3")
Console.WriteLine("1 : create a new account")
Console.WriteLine("2: log in ")
Console.WriteLine("3 : quit program")
Dim choice As String
choice = Console.ReadLine()
If choice = "1" Then
Create()
ElseIf choice = "2" Then
Login()
ElseIf choice = "3" Then
Console.WriteLine("quitting...")
Environment.Exit(0)
End If
End Sub
Private Sub Create()
Dim veri As Boolean 'Default value is False, value types initialize automatically
Dim attempts As Integer
Dim newname As String = ""
Dim passw As String = ""
Do Until veri = True
Console.WriteLine("enter a new username")
newname = Console.ReadLine()
If LoginDict.ContainsKey(newname) Then 'Searches the Keys in the Dictionary and returns True or False
Console.WriteLine("that username is already taken, try again")
attempts += 1 'new syntax for updating the value of a variable, saves a bit of typing
Else
veri = True
End If
If attempts > 4 Then
Console.WriteLine("you have had more than 3 tries, BYE")
Console.Clear()
Environment.Exit(0) 'To end the application
End If
Loop
veri = False 'You can use the same variable just reset its value
While veri = False
Console.WriteLine("create a password " & newname)
passw = Console.ReadLine
Dim passwlen = passw.Length 'Don't use the old VB6 Len
If passwlen > 12 Then
LoginDict.Add(newname, passw) 'Here is where the new user is added to the Dictionary
veri = True
Else
Console.WriteLine("try again, password must be greater than 12 characters")
End If
End While
Console.WriteLine("your new username and password have been stored")
Console.WriteLine("succes, you have made an account your username :" & newname & " and password: " & passw)
File.AppendAllLines(LoginPath, {$"{newname},{passw}"}) 'Adds the new user to the text file
End Sub
Private Sub Login()
Dim unamever As String = ""
Dim passwvari As String = ""
Dim veri As Boolean 'You don't need a different name for a variable in a another method.
While veri = False
Console.WriteLine("please enter you username")
unamever = Console.ReadLine()
If LoginDict.ContainsKey(unamever) Then 'Searches the Keys in the Dictionary and returns True or False
passwvari = LoginDict(unamever) 'Gets the value associated with the username
Console.WriteLine("please enter your password : ")
If passwvari = Console.ReadLine Then 'Compares the value found in the Dictionary to the string entered by the user.
Console.WriteLine("logging you in...")
veri = True
Else
Console.WriteLine("password incorrect, try again")
End If
Else
Console.WriteLine("username not registered, try again")
End If
End While
End Sub
Private Sub ReadLoginFileAndFillDictionary()
If File.Exists(LoginPath) Then
Dim lines = File.ReadAllLines(LoginPath) 'Read the file into an array of lines
For Each line In lines
Dim splits = line.Split(","c) 'Split each line by the comma into an array of 2 strings
LoginDict.Add(splits(0), splits(1)) 'The first element is the username and the second element is the password.
Next
Else
Console.WriteLine("There are currently no registered users. Please begin with Option 1.")
End If
End Sub
In a real application you would NEVER store passwords as plain text.
i have written code to save data to a database, this code works fine. However, when it comes to validating the code, i have been encountering some issues despite the validation code working in console mode. The issue is that when i call the functions (seen below in the code) CheckValidPassword() etc. they dont seem to return the correct value and when it comes to the If statement in the savebutton click event, the code kind of skips it and just saves the data to the database via a datagridview.
Here is the code.
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim ValidUserName, ValidPassword, ValidTeacherUsername As Boolean
Dim Username, Password, TeacherUsername As String
Username = txtStudentID.Text
Password = txtStudentPassword.Text
TeacherUsername = txtTeacherID.Text
ValidUsernameCheck(ValidUserName, Username)
ValidPasswordCheck(ValidPassword, Password)
ValidTeacherUsernameCheck(ValidTeacherUsername, TeacherUsername)
If ValidUsernameCheck(ValidUserName, Username) <> True Or ValidPasswordCheck(ValidPassword, Password) <> True Or ValidTeacherUsernameCheck(ValidTeacherUsername, TeacherUsername) <> True Then
MsgBox("Saving failed", MsgBoxStyle.OkOnly)
'Exit Sub
Else
Try
Dim dataAdapter As New OleDbDataAdapter
Dim DataTable As New DataTable
Dim DataSet As New DataSet
Connection.Open() ' the following decleration are used to save content to the table.
DataSet.Tables.Add(DataTable)
Dim SQLQuery As String = (<sql>SELECT * FROM Students</sql>)
dataAdapter = New OleDbDataAdapter(SQLQuery, Connection)
dataAdapter.Fill(DataTable)
Dim newRow As DataRow = DataTable.NewRow
With newRow ' the with statement allows you do repeatedly apply a property to a certain object
.Item("StudentID") = txtStudentID.Text ' these statements add the content of the text boxes to these respective fields in the database
.Item("TeacherID") = txtTeacherID.Text
.Item("StudentFirstName") = txtStudentFirstname.Text
.Item("StudentSurname") = txtStudentSurname.Text
.Item("StudentPassword") = txtStudentPassword.Text
.Item("StudentGroup") = cbxStudentGroup.Text
End With
DataTable.Rows.Add(newRow)
Dim Command As New OleDbCommandBuilder(dataAdapter)
dataAdapter.Update(DataTable) 'updates the table
Connection.Close()
ShowItems() ' displays the table
Catch ex As Exception
MessageBox.Show(ex.Message)
Connection.Close()
End Try
End If
End Sub
Here are the three functions used to validate the three critical bits of data.
Function ValidUsernameCheck(ByRef ValidUserName As Boolean, ByVal Username As String) As Boolean
Dim Valid1, Valid2 As Boolean
If Char.IsLetter(Mid(Username, 1, 3)) Then ' takes the first 3 characters of a user name to see if they are
' letters
Valid1 = True
Else
Valid1 = False
End If
If Char.IsNumber(Mid(Username, 4, 8)) Then 'does the same with numbers, starting at char(4) and taking 8.
Valid2 = True
Else
Valid2 = False
End If
If Valid1 = True And Valid2 = True Then
ValidUsernameCheck = True
Else
ValidUsernameCheck = False
End If
Return ValidUsernameCheck
End Function
Function ValidTeacherUsernameCheck(ByRef ValidTeacherUsername As Boolean, ByVal TeacherUsername As String) As Boolean
Dim Valid1, Valid2 As Boolean
If Char.IsLetter(Mid(TeacherUsername, 1, 3)) Then ' takes the first 3 characters of a user name to see if they are
' letters
Valid1 = True
Else
Valid1 = False
End If
If Char.IsNumber(Mid(TeacherUsername, 4, 8)) Then 'does the same with numbers, starting at char(4) and taking 8.
Valid2 = True
Else
Valid2 = False
End If
If Valid1 = True And Valid2 = True Then
ValidTeacherUsernameCheck = True
Else
ValidTeacherUsernameCheck = False
End If
Return ValidTeacherUsernameCheck
End Function
Function ValidPasswordCheck(ByRef ValidPassword As Boolean, ByVal Password As String) As Boolean
If System.Text.RegularExpressions.Regex.Match(Password, "\d").Success Then
ValidPasswordCheck = True
Else
ValidPasswordCheck = False
End If
Return ValidPasswordCheck
End Function
Any help will be appreciated.
Your code appears to be a bit too complicated. You can return from a function at any point with a Return statement - as soon as you detect an input value is incorrect, you can Return False because any further validation checks are usually not needed.
It looks like you have at least some familiarity with regexes, so you could use one to check the usernames as well as the password.
The code appears to be setting credentials for a student, so there is no harm in letting the user know which entry had a problem, if any. Also, it is a good idea to tell the user what format the entry should be in.
You are checking the IDs, not the names - you should name the functions appropriately.
So, your code could look like this:
Private Function IsIdFormatCorrect(ID As String) As Boolean
If String.IsNullOrEmpty(ID) OrElse ID.Length <> 11 Then
Return False
End If
' require name to be exactly (three letters followed by eight digits)
Return Regex.IsMatch(ID, "^[A-Za-z]{3}[0-9]{8}$")
End Function
Private Function IsPasswordFormatCorrect(password As String) As Boolean
If String.IsNullOrEmpty(password) Then
Return False
End If
' require password to be only digits and at least four of them
Return Regex.IsMatch(password, "^[0-9]{4,}$")
End Function
Private Sub bnSave_Click(sender As Object, e As EventArgs) Handles bnSave.Click
Dim errorText As String = ""
If Not IsIdFormatCorrect(txtStudentID.Text) Then
errorText = "Student ID not in correct format (""ABC12345678"")." & vbCrLf
End If
If Not IsIdFormatCorrect(txtTeacherID.Text) Then
errorText &= "Teacher ID not in correct format (""ABC12345678"")." & vbCrLf
End If
If Not IsPasswordFormatCorrect(txtStudentPassword.Text) Then
errorText &= "Student password not in correct format (at least four digits)."
End If
If errorText.Length > 0 Then
MessageBox.Show(errorText, "Data entry problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
' save to database
End If
End Sub
having trouble working out why this won't check the textbox too as well as the selected color. If I do not put a color it flags up the "please enter fields" message, however if I do select a color but do not put anything in the name textbox then it carries on and just outputs a blank string in the msgbox.
Code is:
Dim newColor As Color
Dim userName As String
Dim notEnoughArguments As String = "Please fill out the fields"
'Click event for button
Private Sub enterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enterBtn.Click
If (userName Is "") Then
MsgBox(notEnoughArguments)
ElseIf (userName Is "" And colorLtb.SelectedItem Is Nothing) Then
MsgBox(notEnoughArguments)
ElseIf (colorLtb.SelectedItem Is Nothing) Then
MsgBox(notEnoughArguments)
Else
userName = txt1.Text
Dim selectedColor As String = colorLtb.SelectedItem.ToString
newColor = Color.FromName(selectedColor)
Dim msgBoxText As String = "Hello " + txt1.Text + "." & vbCrLf + "Changing your color to " + selectedColor + "."
MsgBox(msgBoxText)
Me.BackColor = newColor
End If
End Sub
For strings (like your textbox contents) use String.IsNullOrWhitespace as a test. Also you want both arguments, right? So a single statement should do:
If String.IsNullOrEmpty(userName) OrElse colorLtb.SelectedItem Is Nothing Then
MessageBox.Show(notEnoughArguments)
Return
End If
The problem is that Dim userName As String means the variable has nothing at all and that is not the same as an empty string. I always declare strings and immediately set them to String.Empty to avoid null reference exceptions, but using String.IsNullOrEmpty is a clean and robust way to test the contents of a string variable.
Normally to test for equality in VB, you use a single = rather than Is
If (userName = "") Then
When testing for Nothing, you have to use Is
If (userName Is Nothing) Then
IsNullOrEmpty combines both tests. As the accepted answer suggests:
If (String.IsNullOrEmpty(userName)) Then
I'm trying to use this script to compare a users input from a text box with the 22 correct words. I'm not looking for multiple cases, such as VICE is in ADVICE so it would be 2 values; I want it to have the string values to accept only equal values.
At the moment, it is only recognizing the first word TIED and displays a message box "found", but it doesn't not recognize any other word in the list.
I am writing in visual basic script
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
Dim Find As String = userinput
For Each Str As String In StrCorrect
If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
MsgBox("Found" & userinput)
Return
Else : MsgBox("incorrect word")
Return
End If
Next
End Sub
The problem is that your loop is explicitly returning if the first item isn't a match. You only know you don't have a match if your loop completes without finding one, so try something like this instead:
For Each Str As String In StrCorrect
If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
MsgBox("Found" & userinput)
Return
End If
Next
MsgBox("incorrect word")
This will only display "incorrect word" if all of the items in your list fail the first test.
Why STRCOMP? Why not a direct comparision if you want an exact match?
For Each Str As String In StrCorrect
If Str = Find Then
MessageBox.Show("Found :" & Str)
End If
Next
Try like below, It will help you...
Sample :
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
MsgBox("Found : " & userinput)
Else
MsgBox("incorrect word")
End If
Full Code :
Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
Dim Find As String = userinput
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
MsgBox("Found : " & userinput)
Else
MsgBox("incorrect word")
End If
I would use a for loop, something like
For i As Integer = 0 To StrCorrect.Length - 1
If StrCorrect(i) = Find Then
MsgBox("Found" & Find)
Return
'End if
'The else statement simply alerting that it didnt find the right word on this iteration
'The else can be removed if you dont want this alert
Else
MsgBox("incorrect word")
'Return
End If
Next
I have two TextBoxes..
I want to extract/duplicate ALL CAPITAL LETTERS to be inputted by the user to another TextBox during an event of KeyPress.
Logic :
Private Sub TextBox1_KeyPress()
'If the Character is a Capital Letter Then
' Copy and Concatenate it to the second TextBox
'End If
End Sub
You can try this:
For i = 0 To TextBox1.Text.Length - 1
Dim c As Char = TextBox1.Text.Chars(i)
If Char.IsUpper(c) Then
TextBox2.AppendText(c)
End If
Next
If you need it as a function:
Private Function ExtractUppers(ByVal txt As TextBox) As String
Dim sExtract As String = ""
For i = 0 To txt.Text.Length - 1
Dim c As Char = txt.Text.Chars(i)
If Char.IsUpper(c) Then
sExtract = sExtract & c
End If
Next
Return sExtract
End Function
And in your button:
TextBox2.Text = ExtractUppers(TextBox1)
It was solved by my friend! :) Thanks for your replies!
Private Sub TextBox1_TextChange()
CapitalLetter = Regex.Replace(TextBox1.Text, "[^A-Z]", String.Empty)
TextBox2.Text = CapitalLetter
End Sub
Maybe you can use this trick:
If letterVar = letterVar.ToUpper() then
TextBox2.Text &= letterVar
End if