Check if record already exists - mysql

I am creating a program in VB.NET where, before creating a user I want to check that if that record already exists.
Here is my code:
Imports MySql.Data.MySqlClient
Public Class WindowsAdvancedStudyStartingForms
Dim FirstName As String = ""
Dim SecondName As String = ""
Dim FullName As String = ""
Dim StudentClassReal As String = ""
Dim StudentClassValue As String = ""
Dim Address As String = ""
Dim Username As String = ""
Dim Password As String = ""
Dim SuccessfulMessage As Integer = 0
'MySql
Dim ServerString As String = "Server=myServer;User ID=myID;Passwordmy=Password;Database=myDatabase;SSLMode=None"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FirstName = AFirstNameTextBox.Text
SecondName = ASecondNameTextBox.Text
FullName = FirstName + " " + SecondName
StudentClassValue = ASelectClassComboBox.SelectedItem
Address = AAddressTextBox.Text
Username = AUsernameTextBox.Text
Password = APasswordTextBox.Text
If StudentClassValue = "Class IX" Then
StudentClassReal = 9
Else
MessageBox.Show("You have selected a Wrong Class", "Wrong Class", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If FirstName = "" And FirstName.Count = 1 Then
MessageBox.Show("You didn't enter your First Name", "First Name", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If SecondName = "" Then
MessageBox.Show("You didn't enter your Second Name", "Second Name", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If Address = "" Then
MessageBox.Show("You didn't enter your Address", "Address", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If Username = "" Then
MessageBox.Show("You didn't enter your Username", "Username", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If Password = "" Then
MessageBox.Show("You didn't enter your Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If StudentClassReal = "9" Then
Dim StudentInformationVerification As Integer = MessageBox.Show("Are you sure that these are your information?" & vbCrLf & "I am " + FullName + ", and I study at Class " + StudentClassReal + ". I live in " + Address + ". My Advanced Windows Study Username is " + Username + ", and my password is " + Password, "Information Verification", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If StudentInformationVerification = DialogResult.Yes Then
Dim SQLStatement As String = "INSERT INTO people(FirstName, SecondName, Class, Address, Username, Password) VALUES('" & FirstName & "','" & SecondName & "', '" & StudentClassReal & "', '" & Address & "', '" & Username & "', '" & Password & "')"
SaveName(SQLStatement)
My.Computer.Registry.LocalMachine.SetValue("Study", "1")
SuccessfulMessage = 1
Me.Close()
End If
If StudentInformationVerification = DialogResult.No Then
End If
Else
'Nothing
End If
End Sub
'MYSQL Connection
Private Sub WindowsAdvancedStudyStartingForms_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim RegistryCheck As String = My.Computer.Registry.LocalMachine.GetValue("Study")
If RegistryCheck = 1 Then
LoginForm1.Show()
Me.Close()
End If
APasswordTextBox.UseSystemPasswordChar = True
SQLConnection:
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
If SuccessfulMessage = 0 Then
MessageBox.Show("Connected to Windows Advanced Study Database", "Connection to Database Passed", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Else
SQLConnection.Close()
MessageBox.Show("Could not Connect to Windows Advanced Study Database", "Connection to Database Failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)
If DialogResult.Retry Then
GoTo SqlConnection
End If
If DialogResult.Cancel Then
Close()
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveName(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MessageBox.Show("Welcome to Advanced Windows Studying", "Authentication Successful", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
End Class

Use parameters. Turn on Option Strict.
You won't need all those Dim's for the student info.
You can pass your connection string to the constructor of the MySQLConnection.
Move your validation code to the Validat event of the various controls. Look up how to cancel the event so focus stays on the appropriate control.
You can pass your SQL string and the connection directly to the connection constructor.
Using...EndUsing statements will ensure that objects are closed and disposed properly even if there is an error. This is very important to ensure that connections are closed.
Don't use GoTo. This is only in the language for backward compatibility and should not be used in new code. (leads to spaghetti code)
In a real application, passwords would never be stored as plain text but that is a topic for another day.
In your SQL statements you need to surround and MySQL reserved words with back ticks (`) This is the character below the tilde (~) and is the quoted identifier for MySQL. Actually, it doesn't hurt to surrond all table names and column names with the back tick to be safe.
I cannot test this code because I don't have your database.
Imports MySql.Data.MySqlClient
Public Class MySQLStudent
Dim strConnection As String = "Server=myServer;User ID=myID;Passwordmy=Password;Database=myDatabase;SSLMode=None"
Private Sub RegisterStudent()
Using cn As New MySqlConnection(strConnection)
Dim SQLStatement As String = "Select Count(*) From people where Username = #UserName;"
Using cmdV As New MySqlCommand(SQLStatement, cn)
cn.Open()
Dim rowCount As Integer = CInt(cmdV.ExecuteScalar())
cn.Close()
If rowCount > 0 Then
MessageBox.Show("Sorry that username is in use; please enter another one.")
AUsernameTextBox.Focus
Exit Sub
End If
End Using
SQLStatement = "INSERT INTO people(FirstName, SecondName, `Class`, Address, `Username`, `Password`) VALUES(#FirstName, #SecondName', #StudentClassValue, #Address, #UserName, #Password);"
Using cmd As New MySqlCommand(SQLStatement, cn)
cmd.Parameters.Add("#FirstName", MySqlDbType.String).Value = AFirstNameTextBox.Text
cmd.Parameters.Add("#SecondName", MySqlDbType.String).Value = ASecondNameTextBox.Text
cmd.Parameters.Add("#StudentClassValue", MySqlDbType.String).Value = ASelectClassComboBox.SelectedItem
cmd.Parameters.Add("#Address", MySqlDbType.String).Value = AAddressTextBox.Text
cmd.Parameters.Add("#Username", MySqlDbType.String).Value = AUsernameTextBox.Text
cmd.Parameters.Add("#Password", MySqlDbType.String).Value = APasswordTextBox.Text
cn.Open()
With cmd
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
End Using
End Using
MessageBox.Show("Welcome to Advanced Windows Studying", "Registration Successful", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Private Sub LogInStudent()
Using cn As New MySqlConnection(strConnection)
Using cmd As New MySqlCommand("Select Count(*) From people Where `Username` = #UserName And `Password` = #Password;", cn)
cmd.Parameters.Add("#UserName", MySqlDbType.String).Value = AUsernameTextBox.Text
cmd.Parameters.Add("#Password", MySqlDbType.String).Value = APasswordTextBox.Text
cn.Open()
Dim rowCount As Integer = CInt(cmd.ExecuteScalar)
cn.Close()
If rowCount <> 1 Then
MessageBox.Show("Sorry, invalid login.")
Exit Sub
End If
MessageBox.Show("Successful login.")
'Show the next form of the application
End Using
End Using
End Sub
End Class

Related

SqlDataAdapter#Fill: `SelectCommand.connection` property has not been initilized

I am making a Student Management System for our thesis. When I click the login button after I put the username and password, this error shows up in da.Fill(dt):
InvalidOperationException was unhandled
Fill: SelectCommand.connection property has not been initilized.
Here is my code in login button
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
con = New SqlConnection(cs)
Dim username As String = TextBox1.Text
Dim password As String = TextBox2.Text
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ")
da = New SqlDataAdapter(cmd)
dt = New DataTable()
da.Fill(dt)
If (dt.Rows.Count > 0) Then
name = TextBox1.Text
MessageBox.Show("Login Successful", "success!",
MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MsgBox("Invalid Login Information!", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End If
End Sub
End Class
When I click the login button I should get to the home page.
This is the login:
and this is the home:
You have to specify which connection to use in your command.
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ", con)
Please note, you are concatenating string to build your SQL Query. This is VERY unsecure. This lead to SQL Injection! Please at least double quote in string variable, and check int variable that are variable. But I strongly suggest you to use parametrized variable (See sp_executeSql).
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text.replace("'", "''") + "'and password'" + TextBox2.Text.replace("'", "''") + "' ", con)
Comments and explanations in-line.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
Dim Exists As Boolean
'The Using block ensures that your database objects are closed and disposed
'even if there is an error.
Using con = New SqlConnection(cs)
'All you need to know is if the record exists. You do not need to return
'the values you just entered.
'Pass the connection to the constructor of the command
Using cmd = New SqlCommand("If Exists (Select username, password From login Where
username=#User and password = #Password;", con)
'Use parameters. It not only helps protect your database against SQL Injection but
'simplifies your SQL statement
cmd.Parameters.Add("#User", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = TextBox2.Text
'You do not need a data adapter or data table for this
'Use execute scalar when you are returning a single value
con.Open()
Exists = CBool(cmd.ExecuteScalar)
End Using
End Using
If Exists Then
Name = TextBox1.Text
MessageBox.Show("Login Successful", "success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MessageBox.Show("Invalid Login Information!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
EDIT
Never store passwords as plain text.

Verifying StudentId and StudentPassword with mySql Database using Visual Basic

I am working on a school voting system. I Have tried this several times and there is no error but my login button doesn't work if I enter details and click login.
I use Visual Studio 2013 and would be glad if anyone can be of assistance.
Thank you
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ConnectToSQL()
End Sub
'connecting to sql method
Private Sub ConnectToSQL()
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim StudentId As String
Dim StudentPassword As String
Try
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT StudentId, StudentPassword, StudentName FROM members"
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
TextBox1.Text = ""
TextBox2.Text = ""
End If
End While
Else
MsgBox("Username and password do not match")
TextBox2.Text = ""
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox1.Focus()
End Sub
End Class
From what I can see your problem is your first if statement:
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
This checks if the connectionstring is set to this value and will most definitely evaluate to false.
I assume that you want to set these settings and then open the connection to the database and not check if these settings are the set to a specific string
To make it work just remove this if statement and just set the connectionstring like this and then open the connection
con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
First, I'm going to assume you have a typo here, as it's using the username and password as the same textbox:
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
Password is probably the 2nd one, forming this:
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
Since you are a student and new to this, not going to get into the parameters discussion, or SQL parameters or filtering, hashing passwords or anything like that, but a couple changes:
Your else on the not hasrows:
MsgBox("Username and password do not match")
TextBox2.Text = ""
The problem with this is that in your case, having no rows just means there's no members in the database, not really information you need, or should tell someone.
Also, you don't need to blank out the username and password if you are going to hide the form anyway. The studentFound var below is used to identify if a match was found. We want to display an error if no match was found.
So, that gives us this:
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
studentFound = True
End If
End While
If Not studentFound Then
MsgBox("Username/Password Combination Not Found")
TextBox1.Text = ""
TextBox2.Text = ""
End If

VB.net not working with SQL

I have a problem that is eating my brains out.
I have a project with 2 forms : 1 that extracts the data from my database ( name and surname) and another one that checks out if the user input of the user is correct (matching name and surname) . The code for the 1'st form is :
http://pastebin.com/rg5GMuu6
The code for the second is pasted here
I have no idea whatsoever how to repair this error. I've heard something about some sort of an adapter or something......Help
Ty in advance
I am using MySQL (Easy PHP);
Uploading some pics:
The first form is working without any problems, the second one gives me this error
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'just a message
MsgBox(" You are searching for the users: " & vbCrLf & "Name: " & TextBox1.Text & vbCrLf & "Surname: " & TextBox2.Text)
' connecting to the database
dbCon = New MySqlConnection("Server = localhost; Database = users; Uid = root; Pwd = password")
strQuery = "SELECT users.name, users.surname FROM users" & _
" WHERE users.name = #Username AND users.surname = #UserPassword"
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.Parameters.AddWithValue("#Username ", TextBox1.Text)
SQLCmd.Parameters.AddWithValue("#UserPassword", TextBox2.Text)
'Database open
dbCon.Open()
DR = SQLCmd.ExecuteReader
If DR.HasRows = 0 Then
MsgBox("Not a match", MsgBoxStyle.Critical)
Else
MsgBox("You guessed the correct name: " & TextBox1.Text & "and the surname: " & TextBox2.Text)
End If
'Close
DR.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate " & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class
Captured all the errors with the debugger
There seems to be odd situations with the .AddWithValue statement. I have found it better to set parameter values with the following two lines of code.
cmd.Parameters.Add(New SqlParameter("#UserName", Data.SqlDbType.NVarChar)).Direction = ParameterDirection.Input
cmd.Parameters("#UserName").Value = textbox1.text'obviously don't need this if it is an Output Param

Limiting the time in and time out in a day in VB.NET?

I have developed a time monitoring system using fingerprint where the employee will scan his/her finger then it will record the time in and time out. But my problem is logging in and logging out by the employee is unlimited. Is there a solution where the employee can log in and log out ONCE IN A DAY? Every employee will log in and log out once. Here is my code for my Daily Time Record Form: (Im using visual studio 2010/Digital Persona UareU for my scanner)
Imports MySql.Data.MySqlClient
Imports System.Windows.Forms
Imports DPFP
Public Class frmDTR
Dim counter As Integer = 0
Dim oConn As New MySqlConnection(ConnectionString.ConnString)
Private matcher As DPFP.Verification.Verification
Private matchResult As DPFP.Verification.Verification.Result
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Me.Close()
End Sub
Public Sub SEARCH_EMPLOYEE()
Try
'Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_records WHERE ID_Number='" & strid & "'" 'check tag number if existing
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
With Me
'plot the data into controls
.txtID.Text = reader(1).ToString
.txtFirst.Text = reader(2).ToString
.txtMiddle.Text = reader(3).ToString
.txtLast.Text = reader(4).ToString
.txtAge.Text = reader(5).ToString
.txtBday.Text = reader(6).ToString
.txtDepartment.Text = reader(7).ToString
.txtYear.Text = reader(8).ToString
.txtGender.Text = reader(9).ToString
.txtContact.Text = reader(10).ToString
.txtMobile.Text = reader(11).ToString
.txtEmail.Text = reader(12).ToString
'fetch image from database
Dim imgBytes() As Byte = reader("image") 'image field
Dim image As Bitmap = New Bitmap(New System.IO.MemoryStream(imgBytes)) 'convert binary to image
.ProfilePic.Image = image 'show picture to picture box
End With
Call LOG_EMP() 'look up if login /log out
Timer1.Enabled = True
End While
Else
'Me.lblStatus.Text = "ID not recognized!"
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
Public Sub LOG_EMP()
Try
' Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_logs WHERE ID_Number='" & strid & "' AND Time_Out='Null'"
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
End While
'logout
Call EMP_LOGOUT()
Else
'log in
Call EMPT_LOGIN()
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
'insert login data
Public Sub EMPT_LOGIN()
' Connect to Database
GlobalFunctions.db_connect()
Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
command = New MySqlCommand("INSERT INTO employee_logs values('','" & txtID.Text & "','" & txtFirst.Text & "','" & txtMiddle.Text & "','" & txtLast.Text & "','" & txtDepartment.Text & "','" & Date.Today & "','" & TimeOfDay & "','Null') ", GlobalFunctions.connection, transaction)
command.ExecuteNonQuery()
transaction.Commit()
'sms = txtFirst.Text & " Enter the Building Premises #" & Now 'actual sms
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Welcome!" & txtFirst.Text)
Me.lblStatus.Text = "Successfully Logged IN! Welcome!" 'set status to login
'Will_SendSMS() 'send sms to number
Catch ex As MySqlException
MessageBox.Show("Error in inserting new record! Error: " & ex.Message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
'close connections
GlobalFunctions.connection.Close()
End Sub
Public Sub EMP_LOGOUT()
' Connect to Database
GlobalFunctions.db_connect()
' Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
GlobalFunctions.execute_nonquery("Update employee_logs set Time_Out='" & TimeOfDay & "' WHERE ID_Number='" & strid & "' AND Time_Out='Null' AND Date='" & Date.Today & "'")
transaction.Commit()
'sms = txtFirst.Text & " Left the Building Premises #" & Now & "Powered by: " ' actual sms to be sent
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Goodbye!" & txtFirst.Text)
lblStatus.Text = "Successfully Logged OUT! Goodbye!" ' set status to logout
'Will_SendSMS() 'send sms
Catch ex As MySqlException
MessageBox.Show("Error in updating a record! Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
' close connections
GlobalFunctions.connection.Close()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'counter for display
counter += 1
If counter = 6 Then
Call ClearTextBox(Me)
lblStatus.ForeColor = Color.Lime
Me.lblStatus.Text = "Please scan your finger....."
Lblverify.ForeColor = Color.Black
Lblverify.Text = "Status"
ProfilePic.Image = Nothing
Timer1.Enabled = False
counter = 0
End If
End Sub
Private Sub frmDTR_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
Try
Me.VerificationControl.Focus()
Catch ex As MySqlException
MessageBox.Show("System Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub frmDTR_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
matcher = New Verification.Verification()
matchResult = New Verification.Verification.Result
Me.VerificationControl.Focus()
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Please scan your finger")
End Sub
Private Sub VerificationControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus) Handles VerificationControl.OnComplete
Dim strSQL As String = "Select * from finger_template"
Dim oDa As New MySqlDataAdapter(strSQL, oConn)
Dim dt As New DataTable
Dim dr As DataRow
Try
oDa.Fill(dt)
For Each dr In dt.Rows
Lblverify.ForeColor = Color.Red
Lblverify.Visible = True
Dim bytes As Byte() = Nothing
bytes = dr.Item("byte_template")
Dim tmplate = New DPFP.Template()
tmplate.DeSerialize(bytes)
matcher.Verify(FeatureSet, tmplate, matchResult)
If matchResult.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
strid = dr.Item("Account_ID")
Call SEARCH_EMPLOYEE()
Exit For ' success
End If
If Not matchResult.Verified Then EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
Lblverify.Text = "Status"
lblStatus.Text = "Unrecognize fingerprint....."
Lblverify.ForeColor = Color.Red
lblStatus.ForeColor = Color.Red
Timer1.Start()
Next
Catch ex As Exception
End Try
End Sub
End Class
This is very nice that you are developing this logic. Actually I have come a crossed YOUR question. Now I can recommend you some vb.net code using back end MS ACCESS 2007 .well You just validate when an employee logged in then put this code after log In button or what ever you are using .
Dim cmd1 as oledbcommond
cmd1 = New OleDbCommand("SELECT * FROM LOGTIME WHERE timein<>null and timeout<>null and dt='" & Label8.Text & "' and eid='" & txtemid.Text & "' ", cn)
dr = cmd1.ExecuteReader()
If dr.Read Then
MessageBox.Show("Already this Employee ID contains today's attendance,now you can't Log again", "Information On Your ID", MessageBoxButtons.OK, MessageBoxIcon.Information)
cmd1.Dispose()
cn.Close()
Exit Sub
End If
just follow the steps
Use normal login button which will validate for user
then if the authenticate user then show his login time in another textbox in the same form.and
use one more textbox to show the logout time ,now
1)use two buttons a)button1 as logintime button and b)button2 as logout time button
2)Then write code to add the login time into the data base,and for ur better understanding put one message box too which will shows the"Time in added to the database" and after that put the above code which will validate the current day attendance if the employee wants to login twice or thrice in a day this code will not allow him to login again only once he/she can ... and code the above behind the login button
note:-keep in mind that all the procedure will work after the employee log out ..Hope this will help you out..

What's Causing My If Statement To Be Skipped?

I have an embedded IF statement that should execute following a Database query. However, I noticed at run-time that the entire statement is not being evaluated at all (the one right after While dbData.Read()). What am I doing wrong?
HERE'S THE CODE:
Private Sub ButtonNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonNew.Click
If TextBoxSearch.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxSearch.Focus()
Else
Try
Dim dbConn As MySqlConnection
dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=parts;Password=parts;Database=accounting")
Dim account As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM customer WHERE accountNumber = '" & TextBoxSearch.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows Then
'MessageBox.Show("Customer record already exists!")
Call recordExists()
account = False
Call lockForm()
TextBoxSearch.Focus()
Me.Refresh()
Else
'dbData.Close()
account = True
TextBoxAccount.Text = TextBoxSearch.Text
TextBoxAccount.BackColor = Color.LightGray
TextBoxAccount.TabStop = False
Call unlockForm()
TextBoxLastName.Focus()
ButtonSubmit.Visible = True
Me.Refresh()
End If
End While
dbData.Close()
dbCmd.Dispose()
dbAdapter.Dispose()
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
End If
End Sub
If dbData.Read() returns False, then it will not enter your loop and therefore the If statement will not be executed. If there are no rows to be read, then Read always returns False, so the If statement is useless where it's at. You need to move that If statement up so that the while loop is inside the If block:
If dbData.HasRows Then
While dbData.Read()
' ...
End While
Else
' ...
End If