Automatic verify the Fingeprint of a user [BLOB] - mysql

Hi? I have here fingerprint scanner. I want to automatically verified user's fingerprint when they are touching the scanner but I cant.
I have here codes but before you verify the fingerprint if it correct, you need to put first his/her userID.
This is my codes:
Private Sub SaveButton_Click() Handles SaveButton.Click
Using files As New IO.MemoryStream
Template.Serialize(files)
objconn.Open()
If Not Template Is Nothing Then
Dim cmd = New MySqlCommand("INSERT INTO employeefp " +
"SET id=#id, " +
"FP=#FP " +
" ", objconn)
cmd.Parameters.Add(New MySqlParameter("#id", TextBox1.Text))
cmd.Parameters.Add(New MySqlParameter("#FP", Template.Bytes))
cmd.ExecuteNonQuery()
objconn.Close()
MessageBox.Show("Template Successfuly Saved.", "Finger Enrolled")
End If
End Using
End Sub
And this my verify button codes:
Private Sub VerifyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VerifyButton.Click
If TextBox1.Text = "" Then
MsgBox("Please input id no.", MsgBoxStyle.Information)
Else
objconn.Open()
Dim cmd As New MySqlCommand("SELECT * FROM employeefp where id ='" & TextBox1.Text & "'", objconn)
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
rdr.Read()
If rdr.HasRows Then
Dim Verifier As New VerificationForm
Verifier.Verify(Template)
Else
MsgBox("The id doesn`t exist", MsgBoxStyle.Information)
End If
End If
objconn.Close()
End Sub
i thought its all about in templates.bytes but i don't know what will I do.
Thanks in advance. Hope you will help me.

Related

Remote database connection in VB.net not working

I'm currently working on a MySQL connection in my VB.net app. I have a form which has the following code:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form4
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Password As String
Dim Password2 As String
Dim userName As String
Try
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT user_username, user_pass FROM users WHERE (user_username = '" & txtUsername.Text & "' ) AND (user_pass = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
Password = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Password2 = txtPassword.Text()
If Password = Password2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
Form2.Show()
Me.Hide()
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username or Password incorrect...", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
Everytime I run the application, I enter the login details correctly and click on the sign in button (Button2). The problem is, it doesn't do anything. It doesn't throw an exception, doesn't even try to login to the server as far as I can tell. I replaced the login details with that of my own server, so that's not the problem. Did I miss something?
Don't store passwords in clear-text!
Furthermore your code is prone to sql incjection.
Nothing happens because this If will never be true:
...
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
...

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..

MysqlException was unhandled DataReader with this connection must be closed vb.net

I have encountered this problem:
ERROR: There is already an open DataReader associated with this Connection which must be closed first.
Please have a look on my code:
Dim sqlQuery As String = "SELECT * FROM users"
Dim myAdapter As New MySqlDataAdapter
If txtUsername.Text = String.Empty And txtPassword.Text = String.Empty Then
MsgBox("Enter username and password", MsgBoxStyle.Exclamation, "Tea Sparkle POS")
Else
Dim sqlquerry = "Select * From users where username = '" + txtUsername.Text + "' And password= '" + txtPassword.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = SQLConnection
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader()
'To check the Username and password and to validate the login a
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
txtPassword.Clear()
txtUsername.Clear()
Else
Dim authorityid = 0
While mydata.Read()
authorityid = mydata.GetInt32("authorityid")
End While
MsgBox("Welcome " + txtUsername.Text + "!")
If authorityid = 1 Then
MainForm.Show()
Else
MainForm.Show()
End If
Me.Hide()
End If
End If
Private Sub Login_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Else
SQLConnection.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
This error is in this line:
mydata = myCommand.ExecuteReader()
What's wrong with this? Any help is truly appreciated.
What's wrong with this?
Well, it looks like you're reusing an existing connection:
myCommand.Connection = SQLConnection
Don't do that. Create a new connection each time you need to talk to the database, and close it when you've finished, using a Using statement to make sure it gets closed even if an exception is thrown.
Additionally, use a Using statement for your command, and another for your reader - these are all resources you should be closing.
Oh, and it also looks like you're doing this in the UI thread, which is a bad idea as your UI will be unresponsive while the database access is ongoing.

Inserting VB.net Label to mysql table

How to Inserting Label.text data into mySql table.
i have no problem with textbox.text but i can't figure out how it with Label.text
i try the same code with textbox.text
parameterB_Answer.Value = TextBox1.Text
it work find but when i try with
parameterB_Answer.Value = Label1.Text
mySqlReader seems can't read it.
Update:
1.1.1 is label1.text. My Idea is to insert the text "1.1.1" from Label1 as Primary key and the Textbox(textbox1.text) as the following
my code is:
Try
Dim StrSQL As String = "INSERT INTO boranga" & _
"(IdBorangA,Answers)" & _
"VALUES (#B_IdA,#B_Answer);"
Dim myCommand As MySqlCommand = New MySqlCommand(StrSQL, conn.open)
myCommand.CommandType = CommandType.Text
Dim parameterB_IdA As MySqlParameter = New MySqlParameter("#B_IdA", MySqlDbType.VarChar, 300)
parameterB_IdA.Value = Label1.Text
Dim parameterB_Answer As MySqlParameter = New MySqlParameter("#B_Answer", MySqlDbType.VarChar, 300)
parameterB_Answer.Value = TextBox1.Text
With myCommand.Parameters
.Add(parameterB_IdA)
.Add(parameterB_Answer)
End With
Dim result As MySqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
MsgBox("Tersimpan", vbYes, "boranga")
Catch SqlEx As MySqlException
Throw New Exception(SqlEx.Message.ToString())
End Try
but when I change the value of Label1.text (1.1.1) to 111, it works just fine. probably because I put INT for the column for label1.text to fill while "1.1.1" isn't integer
thank a lot
PS:seems i can't post image because low of reputation
Try using this code format first of all:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As MySqlConnection
'Connect to the database using these credentials
conn = New MySqlConnection
conn.ConnectionString = "server=your server site (generally long url); user id=login id for mysql user; password=self explanatory; database=name of the DB you're trying to reach"
'Try and connect (conn.open)
Try
conn.Open()
Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
End Try
'MySQL query (where to call for information)
Dim myAdapter As New MySqlDataAdapter
'Tell where to find the file with the emails/passes stored
Dim sqlquery = "SELECT * FROM the database you selected above WHERE Email = '" & txtEmail.Text & "' AND Password = '" & txtPassword.Text & "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'Start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows = 0 Then
MsgBox("Invalid email address or password.", MsgBoxStyle.Critical)
Else
MsgBox("Logged in as " & txtEmail.Text & ".", MsgBoxStyle.Information)
Me.Close()
End If
End Sub
And to insert label.text try replacing one of the textbox.text fields first and see if it will accept it. If it does, then the answer was all in the formatting.
Also, do not forget to call:
imports mysql.data.mysqlclient
and make sure to add the mysql.data reference.

button not working when i insert new data

when I input data are not yet available. button does not work
but when I enter existing data in the database, the button work for find existing records in the database and msgbox.appear
this my coding. (i am using Microsoft Visual Basic 2008 express edition database mysql)
Imports MySql.Data.MySqlClient
Public Class Form2
Public conn As MySqlConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.DoEvents()
Button1.Focus()
conn = New MySqlConnection
'conn.ConnectionString = "server=localhost;database=ilmu;userid=root;password= ''"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Error1: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost;database=ilmu;userid=root;password= ''")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM visitor WHERE nama = '" & TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = TextBox2.Text Then
command = New MySqlCommand
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES ('" & TextBox1.Text & "','" & tkhupd & "')"
command.ExecuteNonQuery()
MessageBox.Show(" Berjaya, Sila Masuk. ", "Tahniah", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MsgBox("exist")
End If
Else
MsgBox("Failed Login.")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
I am not sure what you are trying to do when there is not matching record in the database, but you don't have any code that would be hit in the case of no matching entries.
If there are no matching records, your while condition isn't met and nothing in the loop happens.
Fixing it likely involves rearranging the order of your loop and your if condition.
Check to see if data.hasRows first.
Example:
If data.HasRows() = True Then
While Data.Read
//code here for found rows
End While
Else
//code for no matching entries
End If
And as has been mentioned in Joel's comment, you really should look at using parameterized queries.
example of your insert command altered:
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)"
command.Parameters.AddWithValue("?noK",TextBox1.Text)
command.Parameters.AddWithValue("?khupd", tkhupd)
command.ExecuteNonQuery()