InvalidOperationException was unhandled - Easy fix? - mysql

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;

Related

Is there any way to fix this error in VBNET?

I'm working on a discord bot.
I'm currently working on the login panel (the classic MySQL login way, with the SELECT statement.).
But I've started doing a thing called 2FA, and the way that it works, is the following: If the login was successful the application should set the readytotwofactor column (in MySQL) to true. If it's true, the discord bot generates a 10 letter code, which is appearing in the twofactorcode column. The BOT knows who to send the message to by watching the username entered in the TextBox when logging in. It looks for this in MySQL, and each column (registered username) is associated with a discord ID. Based on this, the BOT knows to whom to send the code that is checked in the MySQL column, the application can identify whether the code is correct or not. Once the code has been sent, the readytotwofactor column will automatically change to false, and the code I wrote should change the value in the twofactorcode column to 0.
My problem, though, is that it doesn't work.
Here is the source code: (Form3 is the login form, and Form4 is the 2FA form.).
Imports MySql.Data.MySqlClient
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim connection As New MySqlConnection("just the login stuff")
Dim command As New MySqlCommand("SELECT * FROM karolyguilogin WHERE username=#username AND pass=#password", connection)
command.Parameters.Add("#username", MySqlDbType.VarChar).Value = TextBox1.Text
command.Parameters.Add("#password", MySqlDbType.VarChar).Value = TextBox2.Text
Dim command1 As New MySqlCommand("UPDATE `karolyguilogin` readytotwofactor SET readytotwofactor=#readytotwofactor WHERE username=#username", connection)
Dim Adapter As New MySqlDataAdapter(command)
Dim table As New DataTable()
Adapter.Fill(table)
connection.Open()
If TextBox1.Text = "" Then
MessageBox.Show("írj be valamit!")
Me.Close()
End If
If TextBox2.Text = "" Then
MessageBox.Show("írj be valamit!")
Me.Close()
End If
If table.Rows.Count() <= 0 Then
MessageBox.Show("Helytelen felhasználónév, vagy jelszó!")
Else
command1.Parameters.Add("#readytotwofactor", MySqlDbType.VarChar).Value = "true"
MessageBox.Show("Hamarosan megkapod a 2FA kódod!")
Me.Hide()
Form4.Show()
Me.Close()
End If
connection.Close()
End Sub
End Class
Imports MySql.Data.MySqlClient
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New MySqlConnection("just the login stuff")
Dim command As New MySqlCommand("SELECT twofactorcode FROM karolyguilogin WHERE twofactorcode = #twofactorcode <> NULL", connection)
command.Parameters.Add("#twofactorcode", MySqlDbType.VarChar).Value = TextBox1.Text
connection.Open()
If TextBox1.Text = "" Then
MessageBox.Show("írj be valamit!")
Me.Close()
End If
Dim Adapter As New MySqlDataAdapter(command)
Dim table As New DataTable()
Adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show("A kódod helytelen, próbálkozz újra!")
Else
Dim command1 As New MySqlCommand("UPDATE `karolyguilogin` twofactorcode SET twofactorcode=#twofactorcode WHERE twofactorcode <> NULL", connection)
MessageBox.Show("A kódod helyes! Beléphetsz a felületre!")
command1.Parameters.Add("#twofactorcode", MySqlDbType.VarChar).Value = "NULL"
Me.Hide()
Form3.Hide()
Form1.Show()
Me.Close()
Form3.Close()
End If
connection.Close()
End Sub
End Class
In the first place, passwords should never be stored as plain text. I am hoping you have omitted the encryption code for brevity.
In ADO.net connections and commands need to be disposed, not just closed. A Using block will handle this for you even if there is an error.
Don't pull down the entire record. You only need to know if it exists. You don't need a DataAdapter to do this.
Do your validation outside the Using block before any database objects are created. Also, how to you expect the user to "Enter something" when you close the Form?
Use the same command for the second query, just change the CommandText. Note that we already have the #username parameter and the #readytotwofactor parameter is not needed because it can be hardcoded in the sql string.
Why hide the Form and then close it 2 lines later?
Perhaps your code doesn't work because you never execute the second command.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Validate first before the database code
If TextBox1.Text = "" OrElse TextBox2.Text = "" Then
MessageBox.Show("írj be valamit!")
Exit Sub
End If
Dim ReturnCount As Integer
Using connection As New MySqlConnection("datasource=sql11.freemysqlhosting.net;port=3306;username=sql11396664;password=eG1IbxNzLR;database=sql11396664"),
command As New MySqlCommand("SELECT Count(*) FROM karolyguilogin WHERE username=#username AND pass=#password", connection)
command.Parameters.Add("#username", MySqlDbType.VarChar).Value = TextBox1.Text
command.Parameters.Add("#password", MySqlDbType.VarChar).Value = TextBox2.Text
connection.Open()
ReturnCount = CInt(command.ExecuteScalar())
If ReturnCount = 0 Then
MessageBox.Show("Helytelen felhasználónév, vagy jelszó!")
Else
command.CommandText = "UPDATE `karolyguilogin` readytotwofactor SET readytotwofactor='true' WHERE username=#username"
command.ExecuteNonQuery()
MessageBox.Show("Hamarosan megkapod a 2FA kódod!")
Form4.Show()
Me.Close()
End If
End Using 'Closes and disposes both the command and the connection
End Sub
I assume there is some sort of trigger in the database when readytotwofactor is set to true.
You realize your Update will set all records in the karolyguilogin table to the string "NULL" not just the the user attempting to log in. If this is a multiuser database this could cause a problem.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox1.Text = "" Then
MessageBox.Show("írj be valamit!")
Exit Sub
End If
Dim ReturnCount As Integer
Using connection As New MySqlConnection("datasource=sql11.freemysqlhosting.net;port=3306;username=sql11396664;password=eG1IbxNzLR;database=sql11396664"),
command As New MySqlCommand("SELECT Count(*) FROM karolyguilogin WHERE twofactorcode = #twofactorcode", connection)
command.Parameters.Add("#twofactorcode", MySqlDbType.VarChar).Value = TextBox1.Text
connection.Open()
ReturnCount = CInt(command.ExecuteScalar())
If ReturnCount = 0 Then
MessageBox.Show("A kódod helytelen, próbálkozz újra!")
Else
command.CommandText = "UPDATE `karolyguilogin` SET twofactorcode='NULL' WHERE twofactorcode <> 'NULL';"
MessageBox.Show("A kódod helyes! Beléphetsz a felületre!")
Form1.Show()
Me.Close()
End If
End Using 'Closes and disposes both the command and the connection
End Sub
I had fun translating the Hungarian message boxes so I could better understand your code.

vb.net cannot connect to sql server

I am trying to make a login database using vb.net. I am using this code to connect but it doesn't work!:
Public Class Form1
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = "Data Source=localhost; Initial Catalog=user; Integrated Security= true"
cmd.Connection = con
con.Open()
cmd.CommandText = "select login, password from auth where login= '" & TextBox1.Text & "' and password = '" & TextBox2.Text & "' "
rd = cmd.ExecuteReader
If rd.HasRows Then
Welcome.Show()
Else
MessageBox.Show("Login Failed", "error")
End If
End Sub
End Class
I have a data base on my sql server called "user" and in user there is a table named "dbo.auth". When I click Label2, visual basic says "con cannot be opened" I am using MySQL server workbench. Is there any way I can fix this? The server is also running on my local network.
Does this work for you?
Imports System.Data.SqlClient
Public Class LoginForm1
Dim conn As SqlConnection
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
conn = New SqlConnection
conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
Try
conn.Open()
MsgBox("Connected!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Also, I think you should bookmark the link below.
https://www.connectionstrings.com/

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

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

VB.NET Cannot attach database query

I've a problem with connection VB.NET to Sql Server 2008 databases. I've already try to create a connection string and it still cannot attach and detect database query yet. It's show an error like this
This is my code I use:
Public Class Authentification
Private Sub Authentification_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
buka()
End Sub
Private Sub btlogin_Click(sender As System.Object, e As System.EventArgs) Handles btlogin.Click
Dim Sql, user, pass As String
user = txtusername.Text
pass = txtpassword.Text
koneksi.Close()
Call buka()
Sql = "SELECT * FROM tAdmin WHERE username = '" + user + "' AND password='" + pass + "'"
cmd = New SqlCommand(Sql, koneksi)
baca = cmd.ExecuteReader()
If baca.Hasrows = True Then
MenuUtama.Show()
Me.Hide()
Else
MessageBox.Show("Username atau password salah", "Konfirmasi", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtusername.Focus()
End If
txtusername.Text = ""
txtpassword.Text = ""
baca.Close()
cmd.Dispose()
End Sub
End Class
And this is the code for module buka:
Module Module1
Public koneksi As SqlConnection
Public data As DataSet
Public baca As SqlDataReader
Public adaptor As SqlDataAdapter
Public cmd As SqlCommand
Public ass As DataTable
Public str, sql As String
Public Sub buka()
str = "Data Source=DON-PC\SQLEXPRESS;Initial Catalog=dbFutsal;Persist Security Info=True;User ID=sa;Password=******"
koneksi = New SqlConnection(str)
Try
If koneksi.State = ConnectionState.Closed Then
koneksi.Open()
End If
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical, "Error")
End Try
End Sub
End Module
Can someone tell me what i'm wrong? Thanks before
Please check if you have the login user "sa" in your database. Also try removing "persist security info" from the connection string.
Firstly, probably not a good idea to publicly post your sa password.
But, let's keep it simple. Try this and see if it connects. if it doesn't work, please post error message.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conDB As New SqlClient.SqlConnection
Dim strConnectionString As String = "Data Source=ServerName;" & _
"Database=DatabaseName;" & _
"User Id=UserName;" & _
"Password=Password;" & _
"Connect Timeout=90;"
Debug.WriteLine(strConnectionString)
conDB.ConnectionString = strConnectionString
Try
conDB.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
' Do something
End Sub
Also, if this is not the same computer with the SQL database on it, try turning firewalls off and connecting again (on both the server and your client).
Only other thing I can suggest is to ensure you have the SQL Server Services running.
go to control Panel, Services, sort alphabetically and look for SQL Server. Start all services that aren't started already.
If it's a local db (like you said earlier) try Data Source=(local); instead of Data Source=DON-PC\SQLEXPRESS;