visual basic 2012 connection must be valid and open - mysql

What I have is a small messaging function that basically can send a message to one user or to a group of users. There are two mysql tables; one called users for the users who use the system, and another messages where the messages are stored. The system can send to specific users but when sending to a group of people, VB gives me the
InvalidOperationException was handled: connection should be open and valid
The code is given below.
Dim receiver, subject, message As String
Dim user As Integer
Dim MySqlConnection As New MySqlConnection
Dim MyAdapter As New MySqlDataAdapter
Dim command As New MySqlCommand
Dim mydata As MySqlDataReader
Private Sub sendButton_Click(sender As Object, e As EventArgs) Handles sendButton.Click
user = loginForm.user
If recieverTextBox.Text = "" And studentCheckBox.Checked = False And facultyCheckBox.Checked = True Then
subject = subjectTextBox.Text
message = messageRichTextBox.Text
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server=localhost; User ID=root; password=''; database=sis_db"
Dim query = "insert into messages (date, sender, receiver, subject, message) select CURRENT_DATE, '" & user & "',user_id,'" & subject & "', '" & message & "' from users where user_type='faculty';"
Try
MySqlConnection.Open()
command.CommandText = query
MyAdapter.SelectCommand = command
mydata = command.ExecuteReader 'the error message points here'
MsgBox("Messages sent", MsgBoxStyle.OkOnly, Title:="SUCCESS!")
recieverTextBox.Clear()
subjectTextBox.Clear()
messageRichTextBox.Clear()
Catch ex As MySqlException
MsgBox("DATABASE ERROR!")
End Try
MySqlConnection.Close()
ElseIf

you can replace the select current_date with DateTime.Now instead
have you tested the connection ? its probably just a typo

Related

VB.net Login with MySQL

I do not know what went wrong. Im new to vb. Can someone help me? Maybe correct my codes cause I've been spending so much time with this login form of mine. Thanks! here's my code.
By the way, I have a table with 3 columns. Username, Password and Privilege. Whenever I input my Login credentials, it only display the Msgbox Try again.
Imports MySql.Data.MySqlClient
Public Class LoginForm
Dim cn As New MySqlConnection
Dim cmd As MySqlCommand
Dim reader As MySqlDataAdapter
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim tblUser As New DataTable
Try
If PasswordTextBox.Text = "" Or UsernameTextBox.Text = "" Then
MessageBox.Show("Please provide your login credentials!")
Else
Dim sql As String
sql = "SELECT * from user_account where username = '" & UsernameTextBox.Text & "' and password = '" & PasswordTextBox.Text & "'"
Using con As New MySqlConnection(My.Settings.ConnectionString)
With cmd
.Connection = con
.CommandText = sql
End With
reader.SelectCommand = cmd
reader.Fill(tblUser)
If tblUser.Rows.Count > 0 Then
Dim userType As String
userType = tblUser.Rows(0).Item(2)
If userType = "admin" Then
MsgBox("Welcome, Admin!")
frmAdminMain.Show()
ElseIf userType = "encoder" Then
MsgBox("Welcome, User!")
MainForm.Show()
End If
Else
MsgBox("Invalid Credentials!")
End If
reader.Dispose()
End Using
End If
Catch ex As Exception
MsgBox("Try Again!")
End Try
End Sub
Add the "New" key word to your command declaration
Dim cmd As New MySqlCommand
"With" just set the properties, it does not initialize the object.

Connection must be valid and open VB.Net

I want to connect my MySQL to my VB.net.
I am only using Login Form.
I have given the code but the code gives me this error message: Connection must be valid and open
This is my code:
Imports MySql.Data.MySqlClient
Public Class Login
Dim MysqlConn As MySqlConnection
Dim Command As MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString ="server=db4free.net;port=3306;userid=exd****;password=****;database=exd****"
Dim Reader As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' "
Command = New MySqlCommand
Reader = Command.ExecuteReader
Dim count As Integer
count = 0
While Reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Correct !")
ElseIf count > 1 Then
MessageBox.Show("Duplicate !")
Else
MessageBox.Show("Not Correct !")
End If
MysqlConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
Can anyone help me to fix that? Thanks.
To associate your Query and Command with the connection you need to do this:
Command = New MySqlCommand(Query, MysqlConn)
You can then perform operations to retrieve the data you need.
At no point do you associate your MysqlConn nor Query to your Command before trying to call ExecuteReader on it. As such, it doesn't have a valid connection at that time.
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' ", nombredelaconexion

restrict access to a .net page without a valid session vb.net

I currently have a login page login.aspx that copies "affID" into a session and uses it on another page dashboard.aspx
login.aspx file looks like this :
Dim Query As String
Query = "select * from mdxmain.taffiliate where affID = '" & username.Text & "' and affPassword = '" & password.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
Session("affID") = username.Text
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
If count = 1 Then
Response.Redirect("dashboard.aspx")
Else
Literal1.Text = "Invalid credentials"
End If
MysqlConn.Close()
Finally
End Try
MysqlConn.Dispose()
dashboard.aspx session load file looks like this :
Dim userid As String = HttpContext.Current.Session("affID")
I need help with not allowing access to the dashboard.aspx file without having a valid session. Also how to timeout the session after 2minutes
In your dashboard page_load event, check if the session variable is nothing, if it is, then redirect to your login page.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim userid As String = HttpContext.Current.Session("affID")
if ( userid is Nothing) then
Response.Redirect("login.aspx")
end if
End Sub
Update
For the timeout there is some good information here

String from Database set as public string

Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
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
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)

MySqlDataReader giving error at build

I have a function in VB.NET that authenticates a user towards a MySQL database before launching the main application. Here's the code of the function:
Public Function authConnect() As Boolean
Dim dbserver As String
Dim dbuser As String
Dim dbpass As String
dbserver = My.Settings.dbserver.ToString
dbuser = My.Settings.dbuser.ToString
dbpass = My.Settings.dbpass.ToString
conn = New MySqlConnection
myConnString = "server=" & dbserver & ";" & "user id=" & dbuser & ";" & "password=" & dbpass & ";" & "database=rtadmin"
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim myDataReader As New MySqlDataReader
Dim query As String
myCommand.Parameters.Add(New MySqlParameter("?Username", login_usr_txt.Text))
myCommand.Parameters.Add(New MySqlParameter("?Password", login_pass_txt.Text))
query = "select * from users where user = ?Username and passwd = ?Password"
conn.ConnectionString = myConnString
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = query
myAdapter.SelectCommand = myCommand
myDataReader = myCommand.ExecuteReader
If myDataReader.HasRows() Then
MessageBox.Show("You've been logged in.", "RT Live! Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
End Try
Catch ex As Exception
End Try
End Function
The function is not yet complete, there are a few other things that need to be done before launching the application, since I'm using a MessageBox to display the result of the login attempt.
The error that I'm getting is the following:
Error 1 'MySql.Data.MySqlClient.MySqlDataReader.Friend Sub New(cmd As MySql.Data.MySqlClient.MySqlCommand, statement As MySql.Data.MySqlClient.PreparableStatement, behavior As System.Data.CommandBehavior)' is not accessible in this context because it is 'Friend'. C:\Users\Mario\documents\visual studio 2010\Projects\Remote Techs Live!\Remote Techs Live!\Login.vb 43 13 Remote Techs Live!
Any ideas?
It makes no sense to try to create a MySqlDataReader and then throw it away!
First you do this to attempt to create a reader:
Dim myDataReader As New MySqlDataReader
Then later you attempt to throw that away when you do this:
myDataReader = myCommand.ExecuteReader
Just remove the New from your initial declaration. I suspect that the constructor for the MySqlDataReader is not publicly accessible.
You could try the .AddWithValue instead of .Add.
For example:
cmd.Parameters.AddWithValue("?Username", login_usr_txt.Text)