I am almost about to finish this. I have taken code from aspsnippets. Just added some of my code to check the conditions. There are two buttons One do login from facebook & fetch information which is working Then on second button click it checks whether userid(got from fb) is exist in my db or not? If not then Insert it in db. But at the end of execution I am getting this exception
MySql.Data.MySqlClient.MySqlException (0x80004005): There is already an open DataReader associated with this Connection which must be closed first. at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception) at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.CheckState() at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader() at login.Button1_Click(Object sender, EventArgs e) in C:\Users\Suraj\Desktop\fbLoginTest\login.aspx.vb:line 43
UPDATED
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
con.Close()
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
str2 = command.ExecuteReader
command.Dispose()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End If
End Sub
You already opened the connection with:
Dim con As New MySqlConnection("Data Source="server";port=3306;Initial Catalog=db;User Id=user;password=password;")
con.Open()
So, remove the con.Open() calls from within your try..catch clauses.
Related
I'm trying to make fb login for my website. So I put condition if user already exist then it will do login & if not then it perform insert user data.
In following code if string is Not Null Or Empty then I am trying to execute code but by putting breakpoint on my statement I see that if string has value then rest code not executing. What could be the reason? Is I am doing something wrong? My first block of code is working fine(users data fetching from facebook). Problem is in second block where I am checking condition.
Private Sub login_Load(sender As Object, e As EventArgs) Handles Me.Load
FaceBookConnect.API_Key = "XXXXXXX"
FaceBookConnect.API_Secret = "XXXXXXX"
If Not IsPostBack Then
If Request.QueryString("error") = "access_denied" Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('User has denied access.')", True)
Return
End If
Dim code As String = Request.QueryString("code")
If Not String.IsNullOrEmpty(code) Then
Dim data As String = FaceBookConnect.Fetch(code, "me")
Dim faceBookUser As FaceBookUser = New JavaScriptSerializer().Deserialize(Of FaceBookUser)(data)
faceBookUser.PictureUrl = String.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id)
pnlFaceBookUser.Visible = True
lblId.Text = faceBookUser.Id
lblUserName.Text = faceBookUser.UserName
lblName.Text = faceBookUser.Name
lblEmail.Text = faceBookUser.Email
ProfileImage.ImageUrl = faceBookUser.PictureUrl
btnLogin.Enabled = False
End If
End If
If IsPostBack Then
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 50000
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Response.Write("User Already Exist")
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Response.Write("User Added")
Catch ex As Exception
Response.Write(ex)
End Try
End If
con.Close()
End If
End If
End Sub
End Class
Can anyone please tell me what is wrong with my code? I am new in vb.net development hence taking some reference codes online & tried to write this code but getting error. Please tell me where I am doing wrong & correct my code.
ERROR
There is already an open DataReader associated with this Connection which must be closed first.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End If
con.Close()
End Sub
So no one given me solution I tried to resolve it from my own. Hence people suggested to close data reader but that was my question where I need to close data reader since I am a new developer. I closed my datareader in else clause before it's command gets executed..
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End If
con.Close()
End Sub
Stack community now getting worst. The moderators are arrogant
For my asp.net website I was trying put feature of FB & Google Login. I found tutorial from ASPSNIPPETS. Now in this what I have done is If user click on Facebook Login button then It first authorize the user & get user details in panel. Then I put my code to check whether user already exist in my db or not. If not then it Inserts user & then put login code. My Problem is after executing first line of code it stops executing further so that It is unable to check whether user is logged in or not & so on. I think it may be because of redirect url which stops further codes o execute. How Can I eliminate this problem?
Protected Sub Login(sender As Object, e As EventArgs)
FaceBookConnect.Authorize("user_photos,email", Request.Url.AbsoluteUri.Split("?"c)(0))
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
Dim con2 As New MySqlConnection("connectionstring")
con2.Open()
Dim cmd3 As New MySqlCommand("Select ID, email From users where ID=#id", con2)
cmd3.Parameters.AddWithValue("#id", lblId.Text)
Dim dr2 As MySqlDataReader = cmd3.ExecuteReader()
If dr2.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con2)
con2.Open()
Dim da As New MySqlDataAdapter(cmd3)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
con2.Close()
End Try
con.Close()
End If
End If
End If
con.Close()
End Sub
First you can optimise your code :
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim str As String = "select * from users where ID=#id"
con.Open()
Dim cmd2 As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim da As New Common.DataAdapter(cmd2)
Dim ds As New Data.DataSet()
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
'Do Login Code here
Try
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values(#id, #img,#name)"
Dim cmd As New MySqlCommand
cmd = New SqlCommand(req, con)
cmd.Parameters.Add(New SqlParameter("#id", lblId.Text))
cmd.Parameters.Add(New SqlParameter("#img", ProfileImage.ImageUrl.ToString))
cmd.Parameters.Add(New SqlParameter("#name", lblName.Text))
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
'After insertion you don't have to select from database just send the parameters to cookies
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
End If
con.Close()
End If
I'm kinda new to asp.net but I'm learning fast, tho I cant find any good web forms tutorial for login page written in vb, I'm using the offline application tutorials to learn and I just change the commands,
So i've come to a simple error for you guys, the problem is with the dsc.sqlclient, probably there's not such command, but what should I use?
Thanks a lot anyway!
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
' Fill the dataset
Dim ds As New DataSet()
dsc.sqlclient.sqlcommand(ds, "Users")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
Thanks a lot guys, this is the correct answer tho, kbworkshop helped me a lot!
For anyone wanna know this is the code
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
conn.Open()
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub
Your code should be something like this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
objConn.Open()
' Fill the dataset
Dim ds As New DataSet("Users")
Dim daExample As New SqlDataAdapter(strSQL, objConn)
daExample.Fill(ds, "Users2")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
objConn.close()
End If
End Sub
but you can also take this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
PLEASE don't create your SELECT statement by pasting text together.
Ugh.
Never do that.
You just allow anyone to use "SQL Injection" to log in (and worse) without a
password.
Imports System.Data
Imports System.Data.SqlClient
Partial Class log
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=F:\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True")
Dim log As String = "SELECT * FROM login WHERE userid='" & TextBox1.Text & "' AND password='" & TextBox2.Text & "'"
Session("user") = TextBox1.Text
Dim cmd As New SqlCommand(log, cn)
Dim dr As SqlDataReader
cn.Open()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("showdata.aspx")
Else
Response.Redirect("log.aspx")
End If
End Sub
End Class
You can use SqlDataAdapter class to fill your dataset:
SqlConnection conn = new SqlConnection("My ConnectionString");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
VB.Net:
Dim conn As New SqlConnection("My ConnectionString")
Dim da As New SqlDataAdapter()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = SQL
da.SelectCommand = cmd
Dim ds As New DataSet()
conn.Open()
da.Fill(ds)
conn.Close()
I am trying to work out SQL code in VB but I am having problems I have a simple database with the table admin with the columns UserName and Password.
I want to be able to read data from a text box and then input it into a SQL string… the SQL string works (I've tested it) and I can get it to output with a simple SELECT statement but I can't seem to get the SQL to read my Parameter.
Help?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call Password_Check(txtTestInput.Text)
End Sub
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", Answer)
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
in your code above:
--> Dim parameter As New SqlParameter("#Username", Answer)
Can I suggest two options:
Dim parameter As New SqlParameter("#Username", sqldbtype.nvarchar)
parameter.value = Answer
or
cmd.CommandText = string.format("SELECT Password FROM Admin WHERE (UserName = {0})", Answer)
Full Code:
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", SqlDbType.NVarChar)
parameter.Value = Answer
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
Regarding to your Database system it is possible that it does not support parameter names. Have you tried ? Wat DB System you used?
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = ?)"