Remote database connection in VB.net not working - mysql

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

Related

'System.Security.Authentication.AuthenticationException' occurred in MySql.Data.dll

I tried to use this code to login to my vb.net application using mysql. But I have this error
An unhandled exception of type 'System.Security.Authentication.AuthenticationException' occurred in MySql.Data.dll. Additional information: Échec d'un appel à SSPI, consultez l'exception interne. I have this error only with windows 10, there are no problems with Windows 7
I read here a solution.
I tried to add this line
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;" before
Dim Str As String = "SERVER=localhost;
uid =root;
DATABASE =mag;
PASSWORD =;""
but it didn't work.
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Str As String = "SERVER=localhost; uid =root;DATABASE =mag;PASSWORD =;"
Dim cc As New MySqlConnection(Str)
Try
conn.Open()
Dim Sql = "SELECT * FROM tab1 WHERE login='" & TextBox1.Text & "' and password='" & TextBox2.Text & " '"
Dim cmd = New MySqlCommand(Sql, cc)
Dim dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows = 0 Then
MsgBox("Error.", vbQuestion)
Else
Me.Hide()
Form2.Show()
End If
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

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

VB2013 & MySQL not talking properly and program freezing

I have been working on a small project for a while now - it takes a plain text input from an Ardiuno Board (simple text, only a few characters). It's a simple NFC Card tagging program. The program is supposed to take the input from the SerialPort and check the input text against a MySQL database. If it finds the name in the database, then it is to update one column, that's it.
The problem is two fold - first, while I can query the database and get a list of people within the database, the tagging side of the program will not update the database, not matter what input is passed to it. Second - whenever the program receives any input, the program locks up and the GUI becomes unresponsive.
My code is below, and I am happy for any Questions, Comments, or Criticisms. Yes, the MySQL server is on port '8228'. This code is driving me mad, and I apologize as it may seem messy...
Imports System.IO.Ports
Imports System.Threading
Imports System.Text
Imports System.Data.Odbc
Public Class Form1
Dim WithEvents SerialPort As New IO.Ports.SerialPort
Dim ListStr As String
Dim SQLString As String
Dim fstoday As String = Today.Day.ToString + "_" + Today.Month.ToString + "_" + Today.Year.ToString
Dim NextLine As String
Dim PortNum As String
Dim SqlConn As String
Dim sw As StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs)
Timer1.Start()
SerialPort.ReceivedBytesThreshold = 4
PortNum = "COM6"
SqlConn = "mydomain.local"
Call TestSQLConnectionToolStripMenuItem_Click()
Call ConnectSerial()
'create todays log file
Dim filesys As New FileStream("c:\TagLog\Log-" + fstoday + ".txt", FileMode.Append, FileAccess.Write, FileShare.Write)
filesys.Close()
End Sub
Private Sub ConnectSerial()
'set the USB (COM) Port and Bandwidth (BaudRate)
Try
SerialPort.BaudRate = 115200
SerialPort.PortName = PortNum
SerialPort.Open()
LabPort.Text = "Reader OK"
LabPort.ForeColor = Color.Green
Catch
SerialPort.Close()
LabPort.Text = "Reader Not Found"
LabPort.ForeColor = Color.Red
End Try
End Sub
'This handles setting and reading from the serial port
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Dim str As String = SerialPort.ReadExisting()
Invoke(myD1, str)
End Sub
'This makes the serial input into String format
Delegate Sub myMethodDelegate(ByVal [text] As String)
Dim myD1 As New myMethodDelegate(AddressOf myShowStringMethod)
Sub myShowStringMethod(ByVal myString As String)
ListStr = ""
SQLString = ""
'display text to our textbox
TextBox2.AppendText(myString)
'Add the last input to the listbox
ListBox1.Items.Add(TextBox2.Text)
ListStr = ListBox1.Items(ListBox1.Items.Count - 1)
SQLString = "Select * From TagTable where QuickName='" + myString + "';"
Try
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
SQLString = "UPDATE tagtable SET State = NOT State, Time=Now() WHERE QuickName='" + myString + "';"
sw.WriteLine(vbCr + Now() + " " + myString)
Call UpdateSQL()
cn.Close()
Catch ex As Exception
sw.WriteLine(vbCr + Now() + ex.ToString)
End Try
sw.Close()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Once per Tick, check what the COM port is saying.
If SerialPort.IsOpen Then
TextBox2.Text = ""
Else
TextBox2.Text = ""
Call ConnectSerial()
End If
End Sub
Private Function IIf(fileExists As Boolean, p2 As String) As Object
Throw New NotImplementedException
End Function
Private Sub UpdateSQL()
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server and update the records
Dim cmd As OdbcCommand = New OdbcCommand(SQLString, cn)
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
If SQLString <> "" Then
Try
cmd.ExecuteNonQuery()
cn.Close()
LabSQL.ForeColor = Color.Green
Catch ex As Exception
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
sw.WriteLine(vbCr + Now() + " " + ex.ToString)
cn.Close()
End Try
Else
cn.Open()
LabSQL.ForeColor = Color.Green
End If
'If there is a problem, change Sql Label, and clsoe the error'd connection.
cn.Close()
SQLString = ""
End Sub
Private Sub TestSQLConnectionToolStripMenuItem_Click() Handles TestSQLConnectionToolStripMenuItem.Click
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server
Try
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
cn.Close()
'If there is a problem, change Sql Label, display the error in a message box and Close the error'd connection.
Catch ex As OdbcException
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
cn.Close()
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Dim msgans As String
msgans = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, "Exit?")
If msgans = vbYes Then
SerialPort.Close()
Me.Close()
End If
End Sub
Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
PortNum = "COM1"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
PortNum = "COM2"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click
PortNum = "COM3"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
PortNum = "COM4"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem7.Click
PortNum = "COM5"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem8_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem8.Click
PortNum = "COM6"
Call ConnectSerial()
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
MsgBox("Made by Phill C at Epoq IT. Tag Control V2.3")
End Sub
Private Sub LocalMachineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LocalMachineToolStripMenuItem.Click
SqlConn = "localhost"
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub OtherLocationToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OtherLocationToolStripMenuItem.Click
SqlConn = InputBox("Enter the SQL Address or Location.", "SQL Location Input", "localhost").ToString
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub ShowUserListToolStripMenuItem_Click() Handles ShowUserListToolStripMenuItem.Click
Dim cn As OdbcConnection
Dim Outstring As String = ""
SQLString = "Select Person,Quickname from TagTable"
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
Dim Query = cmd.ExecuteReader()
Outstring = "FULL NAME, QUICK NAME" + vbCr
While Query.Read
Outstring = Outstring + Query.Item(0) + " , " + Query.Item(1) + vbCr
End While
MsgBox(Outstring)
Query.Close()
cn.Close()
End Sub
Private Sub AddUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the New Users Full Name.", "New User Input", "New User").ToString
Dim QueryQName = InputBox("Enter the New Users Quick Name / Nickname.", "New User Input", "New User").ToString
SQLString = "Insert Into TagTable (QuickName,Person,State,Time) Values ('" + QueryQName + "','" + QueryFull + "','In', NOW());"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("New User has been setup on the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("New User setup has failed, please contact IT Support")
End Try
End Sub
Private Sub DeleteUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the Users Full Name.", "Delete User Input", "User To be deleted").ToString
Dim QueryQName = InputBox("Enter the Users Quick Name / Nickname.", "Delete User Input", "User To be deleted").ToString
SQLString = "Delete From TagTable Where QuickName='" + QueryQName + "' AND Person='" + QueryFull + "';"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("User has been removed from the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("User revomal has failed, please check the full name and quick names, and try again.")
End Try
End Sub
End Class

InvalidOperationException was unhandled - Easy fix?

Hi could someone please help me, I am a completely new to coding and just following material my teacher has given me.
I am currently making a vb programme connected to xampp-mysql database
I have made the login form where the user/pass is store on the xampp database. I have included some presence checks for the text boxes and now I am trying to implement a feature into my program where the user can change his/her password using their security passphrase.
My XAMPP database is called: ba-solutions
My table is called Login and my fields are Username, Password and Security
I tried looking online, but nothing makes sense or is relevant to me, but this maybe just because I don't understand it as I am new to coding.
I used the sheets from my teacher to write this code for the programme but when I try to run I get the error:
InvalidOperationException was unhandled
An error occurred creating the form. See Exception.InnerException for details. The error is: Format of the initialization string does not conform to specification starting at index 52.
Here is my all my code from my Login form:
Imports MySql.Data
Imports MySql.Data.MySqlClient
Module procedures_and_variables
Public objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password=")
Public objdataadapter As New MySqlDataAdapter
Public objdataset As DataSet
Public objcommandbuilder As New MySqlCommandBuilder
Public objdatatable As New DataTable
Public rowposition As Integer = 0
Public sqlstring As String
Public tablename As String
Public objcommand As MySqlCommand
Public reader As MySqlDataReader
Public database_path As String = "Server=localhost;database=ba-solutions;user id=root;password="
Public path As String
Public backup As New MySqlBackup
'Procedure which checks whether or not the current connection is open and opens it, if it is closed.
Public Sub connection_checker()
If objconnection.State = ConnectionState.Closed Then
Try
objconnection.Open()
Catch ex As MySqlException
MsgBox("Error connecting to database")
End Try
End If
End Sub
'Procedure which executes any SQL query.
Public Sub SQL_executer()
Call connection_checker()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = sqlstring
objcommandbuilder = New MySqlCommandBuilder(objdataadapter)
objdataadapter.Fill(objdatatable)
objdataadapter.SelectCommand.CommandType = CommandType.Text
End Sub
'Procedure used to load data from the database for the selected table.
Public Sub initial_load()
Call connection_checker()
Call SQL_executer()
objdataset = New DataSet
objdataadapter.Fill(objdataset, tablename)
objconnection.Close()
End Sub
'Procedure used to update data in a table with the changes made to the data in the datagrid.
Public Sub update_data()
Call connection_checker()
Try
objdataadapter.Update(objdataset, tablename)
MsgBox("Changes accepted", MsgBoxStyle.Information, "Update successfull")
Catch ex As Exception
MsgBox("Changes declined", MsgBoxStyle.Critical, "Update unsuccessfull")
End Try
End Sub
'Procedures used to bind the relevant data to the data grid, with the correct header titles.
Public Sub bind_dataset_client_details()
'NEEDS TO BE COMPLETED FOR ALL DATASETS
End Sub
End module
Public Class frmLogin
Dim form_type As Form
Dim user_table As String
Dim objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password;")
Dim sqlstring As String
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
objconnection.Open()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = "Select * FROM Login"
End Sub
Private Sub Login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Login.Click
Me.Cursor = Cursors.WaitCursor
'Tries to open the server connection and it will give an error if connection fails.
Try
objconnection.Open()
Catch ex As Exception
MsgBox("Error connecting to database", MsgBoxStyle.Critical, "Database Error")
frmXampp.Show()
End Try
'Checks if the username textbox contains a value, if it does not, it creates an error provider.
If Len(txtUsername.Text) < 1 Then
MsgBox("You must enter a username.", MsgBoxStyle.OkOnly, "Login Error")
End If
'Performs same presence check as above on password textbox.
If Len(txtPassword.Text) < 1 Then
MsgBox("You must enter a password.", MsgBoxStyle.OkOnly, "Login Error")
End If
'SQL query
sqlstring = "SELECT * FROM Login Where username = '" + txtUsername.Text + "' AND password = '" + txtPassword.Text + "'"
'Creates command
objcommand = New MySqlCommand(sqlstring, objconnection)
'Executes command
reader = objcommand.ExecuteReader
'See if user exists
If reader.Read Then
MsgBox("Login Accepted!", MsgBoxStyle.Information, "Login Successful")
'Displays the Main Menu form after a successfull login
frmMainMenu.Show()
Me.Visible = False
Else
'And if authentication has failed, the user will be given an option to retry or exit
reader.Close()
Dim prompt As MsgBoxResult
prompt = MessageBox.Show("Invalid Username or Password. Please make sure your credentials are correct and try again or exit.", "Login Error",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning)
If prompt = MsgBoxResult.Cancel Then
Me.Close()
End If
End If
Me.Cursor = Cursors.Arrow
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Me.Close()
End Sub
Private Sub ForgotPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ForgotPassword.Click
Dim security, newpassword As String
security = InputBox("What is the security passphrase?")
sqlstring = "SELECT security FROM Login WHERE security = '" & security & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newpassword = InputBox("Enter new password")
sqlstring = "UPDATE 'Login' SET 'password' = '" & newpassword &
"' WHERE 'Login' . 'password' = '" & security & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Invalid Security Passphrase or New Password. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
End Class
Please bear in mind I am a complete newbie and I would really appreciate any help. Thank you.
I think you have an invalid connection string
Try this instead:
Server=localhost;Database=ba-solutions;Uid=root;

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