VB.Net issues calling a validation function - vb.net

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

Related

When i try to login to a created account iy doesnt recognise the username, why is this?

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.

Streamreader not reading all lines

I am working on a little tool that allows the selection of a single file. Where it will calculate the SHA2 hash and shows it in a simple GUI then takes the value and checks if that hash is listed in a blacklist text file. If it is listed then it will flag it as dirty, and if not it will pass it as clean.
But after hitting Google for hours on end and sifting through many online sources I decided let's just ask for advise and help.
That said while my program does work I seem to run into a problem, since no matter what I do ,it only reads the first line of my "blacklist" and refuses to read the whole list or to actually go line by line to see if there is a match.
No matter if I got 100 or 1 SHA2 hash in it.
So example if I were to have 5 files which I add to the so called blacklist. By pre-calculating their SHA2 value. Then no matter what my little tool will only flag one file which is blacklisted as a match.
Yet the moment I use the reset button and I select a different (also blacklisted) file, it passes it as clean while its not. As far as I can tell it is always the first SHA2 hash it seems to flag and ignoring the others. I personally think the program does not even check beyond the first hash.
Now the blacklist file is made up very simple.
*example:
1afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
2afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
4afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
....and so on.
So as you can see these fake example hashes are listed without any details.
Now my program is suppose to calculate the hash from a selected file.
Example:
somefile.exe (or any extension)
Its 5KB in size and its SHA2 value would be:
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
Well as you can see I took the third hash from the example list right?
Now if I select somefile.exe for scanning then it will pass it as clean. While its blacklisted. So if I move this hash to the first position. Then my little program does correctly flag it.
So long story short I assume that something is horrible wrong with my code, even though it seems to be working.
Anyway this is what I got so far:
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports MetroFramework.Forms
Public Class Fsmain
Function SHA256_SIG(ByVal file_name As String)
Return SHA256_engine("SHA-256", file_name)
End Function
Function SHA256_engine(ByRef hash_type As String, ByRef file_name As String)
Dim SIG
SIG = SHA256.Create()
Dim hashValue() As Byte
Dim filestream As FileStream = File.OpenRead(file_name)
filestream.Position = 0
hashValue = SIG.ComputeHash(filestream)
Dim hash_hex = PrintByteArray(hashValue)
Stream.Null.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByRef array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("x2")
Next i
Return hex_value.ToLower
End Function
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog = DialogResult.OK Then
Dim path As String = SampleFetch.FileName
Selectfile.Text = path
Dim Sample As String
Sample = SHA256_SIG(path)
SignatureREF.Text = SHA256_SIG(path)
Using f As System.IO.FileStream = System.IO.File.OpenRead("blacklist.txt")
Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
While Not s.EndOfStream
Dim line As String = s.ReadLine()
If (line = Sample) Then
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Dirty"
Resetme.Visible = True
RemoveMAL.Visible = True
Else
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Clean"
Resetme.Visible = True
RemoveMAL.Visible = False
End If
End While
End Using
End Using
End If
End Sub
Private Sub Fsmain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub Resetme_Click(sender As Object, e As EventArgs) Handles Resetme.Click
Selectfile.Text = Nothing
SignatureREF.Text = Nothing
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub RemoveMAL_Click(sender As Object, e As EventArgs) Handles RemoveMAL.Click
Dim ask As MsgBoxResult = MsgBox("Would you like to remove the Dirty file?", MsgBoxStyle.YesNo, MessageBoxIcon.None)
If ask = MsgBoxResult.Yes Then
System.IO.File.Delete(Selectfile.Text$)
Else
MsgBox("You sure you want to keep this file?")
Dim filepath As String = IO.Path.Combine("c:\Dirty\", "Dirty.txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(" " & DateTime.Now)
sw.WriteLine(" " & Selectfile.Text)
sw.WriteLine(" " & SignatureREF.Text)
sw.WriteLine(" " & Result.Text)
sw.WriteLine("-------------------")
sw.Close()
End Using
End If
End Sub
End Class
So if any of you guys can have a look at it and point out errors, or even can come up with a fix that would be great.
The simplest thing you can do to make your procedure working, is testing whether a defined condition is verified. Terminate the test if that condition is met.
Using a boolean variable, report the result of the test and take action accordingly.
The Using statement takes care of disposing the StreamReader.
You could modify you procedure this way:
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog <> DialogResult.OK Then Exit Sub
Dim sample As String = SHA256_SIG(SampleFetch.FileName)
SignatureREF.Text = sample
Dim isDirty As Boolean = False
Using reader As StreamReader = New StreamReader("blacklist.txt", True)
Dim line As String = String.Empty
While reader.Peek() > 0
line = reader.ReadLine()
If line = sample Then
isDirty = True
Exit While
End If
End While
End Using
If isDirty Then
'(...)
RemoveMAL.Visible = True
Result.Text = "Dirty"
Else
'(...)
RemoveMAL.Visible = False
Result.Text = "Clean"
End If
End Sub
If you have a String and you want to test whether it matches a line of a text file then you can use this simple one-liner:
If IO.File.ReadLines(filePath).Contains(myString) Then

How to show all validation errors as a list in my messagebox

I am having a problem with my code. I am trying to show all the validation errors in a message box. Can anyone tell me why only one of my errors is showing up in the box? I tried a couple more solutions and looked around but I need a little help please.
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
If Data_Validated_ok() = False Then Exit Sub
End Sub
Private Function Data_Validated_ok() As Boolean
Dim intErrCount As Integer
Dim strErrMessage As String = String.Empty
Dim ctrlError As New Collection
' make sure Premium channel is selected
If Me.lstPremium.SelectedIndex < 0 Then
intErrCount = intErrCount + 1
strErrMessage = intErrCount & ". Premium Channels is a required field." _
& vbCrLf
ctrlError.Add(lstPremium.SelectedIndex)
End If
' make sure a customer type is selected in the Radioboxes
If radBusiness.Checked = False And
radResidential.Checked = False Then
intErrCount = intErrCount + 1
strErrMessage = intErrCount & ".Customer Type is a required field." _
& vbCrLf
ctrlError.Add(radBusiness.Checked, radResidential.Checked)
End If
' make sure a business customer checks at least one option in the listbox
If radBusiness.Checked = True And Me.lstConnections.SelectedIndex < 0 Then
intErrCount = intErrCount + 1
strErrMessage = intErrCount & ". Business Customers must select 1 or more Connection." _
& vbCrLf
ctrlError.Add(lstConnections.SelectedIndex)
End If
' show all errors in a messagebox
If intErrCount > 0 Then
MessageBox.Show(strErrMessage, "Validation Rule(s)", MessageBoxButtons.OK, MessageBoxIcon.Information)
Dim ctrl As Control
ctrl = ctrlError.Item(1)
ctrl.Focus()
Return False
Else
Return True
End If
End Function
How about storing each error in a List(Of String)? Your variable ctrlError is not storing controls, but integers and booleans - you should have casting errors there.
Private Function Data_Validated_ok() As Boolean
Dim errorMsgs As New List(Of String)
' make sure Premium channel is selected
If Me.lstPremium.SelectedIndex < 0 Then
errorMsgs.Add("Premium Channels is a required field.")
End If
' make sure a customer type is selected in the Radioboxes
If radBusiness.Checked = False AndAlso
radResidential.Checked = False Then
errorMsgs.Add("Customer Type is a required field.")
End If
' make sure a business customer checks at least one option in the listbox
If radBusiness.Checked = True And Me.lstConnections.SelectedIndex < 0 Then
errorMsgs.Add("Business Customers must select 1 or more Connection.")
End If
' show all errors in a messagebox
If errorMsgs.Count > 0 Then
MessageBox.Show(String.Join(Environment.Newline, errorMsgs.ToArray), "Validation Rule(s)", MessageBoxButtons.OK, MessageBoxIcon.Information)
Return False
Else
Return True
End If
End Function

how to add parameters to a custom command vb.net

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.

Failed to Enable Constraints in SQL

I'm currently working on a bit of homework for school, and am almost done, however I've got an issue with trying to run a query to match some user data. Every time I run the debugging process, it comes up time and again with the issue of 'Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.' I'm not sure what I'm doing wrong, or how to get past it. Is there something up with my query, or with my code?
Public Class Login_Processing
Dim adapter As New RRBCDataSetTableAdapters.LoginTableAdapter
Dim blnPass As Boolean
Public Function Login(ByVal Username As String, ByVal Password As String) As Boolean
Try
If adapter.GetUserNames(Username).ToString = "VViscioni" Or _
adapter.GetUserNames(Username).ToString = "Whiter" Then
If adapter.GetPassword(Username).ToString = Password Then
frmMain.tsiAdmin.Enabled = True
frmMain.tsiEAdmin.Enabled = True
frmMain.tsiEPlayer.Enabled = True
MessageBox.Show("Welcome back!")
blnPass = True
Else
MsgBox("Is this a new user?", MsgBoxStyle.YesNo)
If vbYes Then
AddAUser.ShowDialog()
Else
MessageBox.Show("Please re-input your password.")
blnPass = False
End If
End If
ElseIf adapter.GetUserNames(Username).ToString = Username Then
If adapter.GetPassword(Username).ToString = Password Then
frmMain.tsiEPlayer.Enabled = True
MessageBox.Show("Welcome to the Roadrunners Baseball Club!")
blnPass = True
Else
MessageBox.Show("Please re-input your password.")
blnPass = False
End If
End If
Catch ex As Exception
MessageBox.Show("Please re-input your username/password.")
blnPass = False
End Try
Return blnPass
End Function
End Class
Here's the SQL queries I'm trying to use for the adapters:
GetUserName Query:
SELECT Login FROM Login
WHERE (Login = #Login)
GetPassword Query:
SELECT Password FROM Login
WHERE (Login = #Login)
The parameters in the function relate to a Username and Password entry the user has to input.