Failed to Enable Constraints in SQL - 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.

Related

How to prevent standard user select one of the data from combo box using vb.net?

I have the code following to load record from database into the combo box :
Private Sub loadcmbReason()
Dim strLeavetype As String = "SELECT leave_type,leave_code FROM leave_types WHERE others = 'Y' AND `status` = 'Y' ORDER BY id ASC"
Dim dt As New DataTable
Try
myconn.OpenConnection()
myconn.FillDataTable(dt, strLeavetype)
myconn.CloseConnection()
cmbReason.TextField = "leave_type"
cmbReason.ValueField = "leave_code"
cmbReason.DataSource = dt
cmbReason.DataBind()
Catch ex As Exception
myconn.CloseConnection()
End Try
End Sub
I have two type of user which Admin and Standard User. My problem is I want to make standard user will get an error when they select this one data from column leave_type which is SPECIAL LEAVE when they click btnSubmit.
Here is code for btnSubmit :
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If ErrorFree() = True Then
If User.IsInRole("Admin") Then
If InsertDetails(lblhdddnuserid.Text, lblhddnEmployeedeptid.Text) = 1 Then
DisplayMessage("success", "Done", "External Work Duty Details succesfully inserted!")
LoadEmployeeByuserid(Membership.GetUser.ProviderUserKey)
End If
Else
If InsertDetails(Membership.GetUser.ProviderUserKey, lblhddnEmployeedeptid.Text) = 1 Then
DisplayMessage("success", "Done", "External Work Duty Details succesfully inserted!")
LoadEmployeeByuserid(Membership.GetUser.ProviderUserKey)
End If
End If
End If
End Sub
Code for the ErrorFree()
Private Function ErrorFree() As Boolean
If lblEmpNO.Text = "" Then
DisplayMessage("error", "ERROR", "Please Select Employee No!")
Return False
Exit Function
End If
If lblemployeename.Text = "" Then
DisplayMessage("error", "ERROR", "Please Select Employee No!")
Return False
Exit Function
End If
If lbldepartment.Text = "" Then
DisplayMessage("error", "ERROR", "Please Select Employee No!")
Return False
Exit Function
End If
If cmbReason.SelectedIndex = -1 Then
DisplayMessage("error", "ERROR", "Please Select The Reason!")
Return False
Exit Function
End If
Return True
End Function

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.

VBA Input Box will not close

I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.
Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?
Here is the code in written form:
Sub Pword()
Dim Ans As Boolean
Const Pword As String = "black2"
Ans = False
Do While Ans = False
If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
Ans = True
End If
Loop
Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""
MsgBox "All data has been cleared."
End Sub
If you need to consider an empty string as a valid input value, the only way to check if the InputBox was actually cancelled isn't to compare its result with vbNullString or "" (both will be True).
So you can use the (undocumented) StrPtr function to determine if the InputBox call returned a legit empty string, or if it was actively cancelled with the [X] or [Cancel] button:
Dim result As String
result = InputBox(...)
If StrPtr(result) = 0 Then
' inputbox was cancelled
Exit Sub
Else
' todo: validate result
End If
Combine that with the other answers to get a reliable "retry" mechanism.
Add a check to see if it's an empty string, like this:
Dim sResult As String
Do While Ans = False
sResult = InputBox("Please enter password to continue.", "Enter Password")
If sResult = Pword Then
Ans = True
ElseIf sResult = "" Then
Exit Do ' or Exit Sub depending on what you want to happen afterwards
End If
Loop
#braX suggestion is an excellent solution.
Also, you can limit the attemps to n in this case I limit the attempts to 3
Dim sResult As String
Dim Attmp As Integer
Attmp = 0
Do While Ans = False
sResult = InputBox("Please enter password to continue.", "Enter Password")
If sResult = Pword Then
Ans = True
ElseIf sResult = "" Then
Attmp = Attmp + 1
If Attmp = 3 Then
Msgbox "Maximum attempts reached."
Exit Do
End If
End If
Loop

VB.Net issues calling a validation function

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

How to solve codes after for loop that do not execute in vb.net?

I have this code under my form_load
checkUser = False
MsgBox("test start")
result = Newtonsoft.Json.JsonConvert.DeserializeObject(Of ArrayList)(getJSon("https://dtitdtr.herokuapp.com/employees"))
MsgBox("test after result before for-each")
For Each value As Object In result
token = JObject.Parse(value.ToString())
id = token.SelectToken("id")
fname = token.SelectToken("fname")
mname = token.SelectToken("mname")
lname = token.SelectToken("lname")
contact = token.SelectToken("contactno")
add = token.SelectToken("address")
user = token.SelectToken("username")
pass = token.SeelectToken("password")
If user.ToString().ToUpper().Equals(GetUName()) Then
checkUser = True
Exit For
Else
checkUser = False
End If
Next value
MsgBox("test after next value")
reader.Close()
response.Close()
and when I run the program, the first two(2) message boxes displayed and the last one, which is after the Next Value, won't display.
I don't quite get what's going on; since yerterday, when I run it, it went just fine and right now after adding codes for update info, which does not suppose to affect the form_load, the codes right after for loop won't execute. What is the problem with this?
I got something here that says "an exception is being thrown" but I don't even have a Try Catch in my code.
Hope that your code throws some Exception inside the For, so i suggest you to include Try.. Catch get the exception details. that helps you to detect the problem.
Try
For Each value As Object In result
token = JObject.Parse(value.ToString())
id = token.SelectToken("id")
fname = token.SelectToken("fname")
mname = token.SelectToken("mname")
lname = token.SelectToken("lname")
contact = token.SelectToken("contactno")
add = token.SelectToken("address")
user = token.SelectToken("username")
pass = token.SeelectToken("password")
If user.ToString().ToUpper().Equals(GetUName()) Then
checkUser = True
Exit For
Else
checkUser = False
End If
Next value
MsgBox("test after next value")
reader.Close()
response.Close()
Catch ex As Exception
MsgBox("Exception :" & ex.ToString)
End Try