I am having an issue with my login page. I am not getting any errors so am not able to know where the problem is?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login.Click
'connection string
Dim mysqlconn As MySqlConnection = New MySqlConnection("server=localhost;user id=root;Password=123;database=users;persist security info=False")
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim mydata As New DataTable
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "SELECT * FROM login_form where Username = '" & rfvUser.Text & "' and Password='" & rfvPWD.Text & "'"
cmd = New MySqlCommand(query, mysqlconn)
reader = cmd.ExecuteReader
While reader.Read()
If rfvUser.Text = "admin" And rfvPWD.Text = "admin" Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Admin.aspx")
ElseIf (rfvUser.Text = reader("UserName").ToString()) And (rfvPWD.Text = reader("Password").ToString()) Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Ersal_send.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username or Password')</script>")
reader.Close()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
End Class
Have you tried running the query directly via a SQL client? If your query is not returning any rows, then your procedure will simply exit without any errors as it will never enter the While loop.
Another advice: It is never a good idea to pass user input directly into a query. This leads to SQL injection. Use parameterised queries. Google for it.
Related
I need to retrieve data from the database first and then update the table with the new entry, following is my code but I am having an error:
"Invalid attempt to call Read when reader is closed."
I know I need to open the datareader by commenting dr1.close, but as soon as I did that I face an another exception:
"there is already an open datareader associated with this command which must be closed first. vb.net"
Imports System.IO
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Data
Partial Class Officer_Module_GST_id_password
Inherits System.Web.UI.Page
Dim sscript As String
Dim sms As New smsgw
Dim mail As New MailSender
Dim cmd As New SqlCommand
Dim ds As New DataSet
Dim dr As SqlDataReader
Dim objconn As New connectioncls
Dim name As String
Dim pid As String
Dim pwd As String
Dim email_sent As Integer
Dim email_status As String
Dim mobile As String
Dim message As String
Dim subject As String
Dim email As String
Dim mtext As String
Protected Sub validatedeal_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles validatedeal.Click
containertwo.Visible = True
txt_subject.Text = "Communication of the Provisional Identification Number and Password"
txt_mail.Text = "Instance mail"
End Sub
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
objconn.openconn()
cmd.Connection = objconn.conn
cmd.CommandText = "Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details"
Dim dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
name = dr1(0).ToString()
pid = dr1(1).ToString()
pwd = dr1(2).ToString()
mobile = dr1(3).ToString()
email = dr1(4).ToString()
email_status = dr1(5).ToString()
email_sent = dr1(6).ToString()
subject = "subject to instance"
mtext = "new instance email"
message = "new instance message"
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
Call sms.SendSMSUsingNICGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Try
Call sms.SendSMSUsingMGOVGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Catch
Dim cmd1 As New SqlCommand
cmd1.Connection = objconn.conn
cmd1.Parameters.AddWithValue("#mobile", mobile)
cmd1.Parameters.AddWithValue("#Email_status", "NO")
cmd1.CommandText = "Update Provisional_details set Email_sent = #Email_status where reg_mob_no = #mobile"
cmd1.ExecuteNonQuery()
cmd1.Parameters.Clear()
Exit Sub
Finally
End Try
dr1.Close()
Dim cmd2 As New SqlCommand
cmd2.Connection = objconn.conn
cmd2.Parameters.AddWithValue("#mobile", mobile)
cmd2.Parameters.AddWithValue("#Email_status", "YES")
cmd2.Parameters.AddWithValue("#emailsent", email_sent + 1)
cmd2.CommandText = "Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile"
cmd2.ExecuteNonQuery()
cmd2.Parameters.Clear()
End While
sscript = "<script language=javascript>alert('Your Mail has been sent to all applied dealers!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
End Sub
End Class
I've pared this down to just the method that matters (like you should have done when posting the question). Updates are in the method, using comments to annotate what's going on.
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'Best practice in .Net is use a brand new connection instance for most DB calls. Really.
'Don't try to be clever and re-use one connection. Just use the same string.
Dim connString As String = "Connection String Here"
'Using block will guarantee connection closes properly, even if an exception is thrown
Using cn As New SqlConnection(connString), _
cmd As New SqlCommand("Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details", cn), _
cn2 As New SqlConnection(connString), _
cmd2 As New SqlCommand("Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile", cn2)
'Define your parameters as early as possible, and be explicit about parameter types and lengths
' This will avoid potentially crippling performance gotchas
cmd2.Parameters.Add("#mobile", SqlDbType.NVarChar, 14)
cmd2.Parameters.Add("#Email_status", SqlDbType.VarChar, 5)
cmd2.Parameters.Add("#emailsent", SqlDbType.Int)
'Separate SQL statements in a tight loop like this is one of the few places to re-use a connection object...
' Even here, it should be a BIG RED FLAG that there's a better way to handle this whole process that avoids multiple calls to the DB.
' For example, it might be better to assume success, Update the DB accordingly in the original statement, and then only write failures back when needed
cn2.Open()
cn.Open()
dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
'Best practice in .Net are to declare these variables in the method where you use them
Dim name As String = dr1(0).ToString()
Dim pid As String = dr1(1).ToString()
Dim pwd As String = dr1(2).ToString() 'You're not really storing passwords in plain-text are you? Please say, "No".
Dim mobile As String = dr1(3).ToString()
Dim email As String = dr1(4).ToString()
Dim email_status As String = dr1(5).ToString()
Dim email_sent As Integer = dr1.GetInt32(6) 'It's a number. You do math on it later. Get the INTEGER value
Dim subject As String = "subject to instance"
Dim mtext As String = "new instance email"
Dim message As String = "new instance message"
cmd2.Parameters("#mobile").Value = mobile
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
' Also... the "Call" keyword is a vb6-era relic that has no purpose any more. Don't use it
sms.SendSMSUsingMGOVGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'Don't set values to "Nothing" to free them in VB.Net.
'It doesn't help the way it used to in vb6/vbscript, and can actually be HARMFUL in rare cases in .Net
End Try
' Do you really mean to try both gateways, even if the first succeeds?
' Because that's what the original code is doing.
Try
sms.SendSMSUsingNICGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'No need to call Exit Try here,
' and no need for an empty Finally section
End Try
Catch
cmd2.Parameters("#emailsent") = email_sent
cmd2.Parameters("#Email_status") = "NO"
cmd2.ExecuteNonQuery()
End Try
cmd2.Parameters("#Email_status").Value = "YES"
cmd2.Parameters("#emailsent").Value = email_sent + 1
cmd2.ExecuteNonQuery()
End While
End Using
End Sub
I'm writing a simple update-password page (studying purposes). The page consist of two text-box controls that will allow the user to enter their new password, followed by confirming their password by entering it into the second text-box control and finally clicking the submit bottom to update their password in the table stored in a database. My problem is that I receive the following error upon button-click: Format of the initialization string does not conform to specification starting at index 0 Error.
This is the code in behind he button:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox2.Text = TextBox3.Text Then
Dim myConnectionString As String
myConnectionString = "myDbIIConnectionString1"
Dim myConnection As New SqlConnection(myConnectionString)
myConnection.Open()
Dim mySQLQuery As String
mySQLQuery = "UPDATE myTb SET password VALUES (#password)"
Dim myCommand As New SqlCommand(mySQLQuery, myConnection)
myCommand.Parameters.AddWithValue("#password", TextBox3.Text)
myCommand.Connection = myConnection
myCommand.ExecuteNonQuery()
myCommand = Nothing
myConnection.Close()
myConnection = Nothing
Label2.Text = "Your Password has been changed"
Else
Label2.Text = "Retype your Password"
End If
Response.Redirect("login.aspx")
End Sub
Could someone assist me as to what I'm missing here? Thank You
There is problem in your update query . Correct it as :
mySQLQuery = "UPDATE myTb SET password=#password"
I figured it out; I should have been using configurationmanager.connectionstrings["the name goes here"]. to access my connection string.
I am using Visual Studio 2010 as my IDE and creating a simple website using Visual Basic I dunno if it's possible but can I display the Username that has just logged into my LoginForm to the other forms using sessions?
I'm not that good enough to understand it but can anyone tell me, is this the right way to contain the value in a session?, how can I display it to the other form?
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim connect As String = "Provider=Microsoft.ACE.OleDb.12.0;" & _
"Data Source=C:\Users\cleanfuel\Documents\Visual Studio 2010\Projects\FinalProject4a2p\FinalProject4a2p\bin\DBFinalProject.accdb"
Dim query As String
query = "Select Count(*) From tblAccount Where Username = ? And UserPass = ?"
Dim result As Integer = 0
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", TxtUser.Text)
cmd.Parameters.AddWithValue("", txtPass.Text)
conn.Open()
result = DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Using
If result > 0 Then
Response.Redirect("Menus.aspx")
Session("User") = TxtUser.Text
Session("Pass") = txtPass.Text
Else
Response.Write("<td>")
Response.Write("<div align=""center"">")
Response.Write("<font color='white'>")
Response.Write("Unable to Login, Invalid Username or Password! </font>")
Response.Write("</div>")
Response.Write("</td>")
End If
End Sub
Setup a label in your Master Page (if you have one), assign the user name from your session to the label and it will appear in all the pages. If you don't have Master page then can setup a label in the page (you want username to appear) and then set the label Text property to value from the session.
The way you are storing the values in the session is correct, you should redirect to Menu.aspx once the values are stored in the session like:
If result > 0 Then
Session("User") = TxtUser.Text
Session("Pass") = txtPass.Text
Response.Redirect("Menus.aspx")
....
And to access them you can do :
labelUserName.Text = Session("User").ToString()
Use FormsAuthentication, then you can simply put a LoginName control on your form, or get the UserName from HttpContext.Current.User.Identity.Name
The answers that the other users provide can be used also, but I find this one and successfully got the result that I want to have.
here are my codes:
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim connect As String = "Provider=Microsoft.ACE.OleDb.12.0;" & _
"Data Source=C:\Users\cleanfuel\Documents\Visual Studio 2010\Projects\FinalProject4a2p\FinalProject4a2p\bin\DBFinalProject.accdb"
Dim query As String
query = "Select Count(*) From tblAccount Where Username = ? And UserPass = ?"
Dim result As Integer = 0
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", TxtUser.Text)
cmd.Parameters.AddWithValue("", txtPass.Text)
conn.Open()
result = DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Using
If result > 0 Then
Dim myCookie As HttpCookie = New HttpCookie("USER")
myCookie.Value = TxtUser.Text
Response.Cookies.Add(myCookie)
Response.Redirect("Menus.aspx")
Else
Response.Write("<td>")
Response.Write("<div align=""center"">")
Response.Write("<font color='white'>")
Response.Write("Unable to Login, Invalid Username or Password! </font>")
Response.Write("</div>")
Response.Write("</td>")
End If
End Sub
I used HTTPcookie instead of session because I can't satisfy myself because it didn't displayed the value that I want to display and it always shows me the same ERROR over and over again.
here are the codes to display:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Request.Cookies("USER") Is Nothing Then
Label7.Text = "No Account Logged In"
Else
Dim aCookie As HttpCookie = Request.Cookies("USER")
Label7.Text = Convert.ToString(Server.HtmlEncode(aCookie.Value))
End If
End Sub
I am creating login pages using asp.net with code behind in vb.net, I am newbie:D. My problem is how to pass the login name to another page. First, whenever I login it will identify if it is an administrator shown in a msgbox. The user requirement is that the employee name is displayed as login not the username. Here is my code. Thanks in advance.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd1 As New SqlCommand
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "SELECT * from UserTable WHERE Username ='" & txt_username.Text & "'"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
If txt_username.Text = rdr.Item(0) And txt_password.Text = rdr.Item(3) Then
CurPos = rdr.Item("Type")
CurUser = rdr.Item("Username")
CurName = rdr.Item("EmployeeName")
If rdr.Item(4) = "ADMINISTRATOR" Then
MsgBox("WELCOME! " & rdr.Item(4), MsgBoxStyle.Information)
Main.lbl_name.Text = CurName.ToUpper 'it's not working
POS.lbl_cashier.Text = CurName.ToUpper ' it's not working
Response.Redirect("ACESCHOOLSUPPLIES.aspx")
cmd1.Connection.Close()
'Me.Dispose()
Else
MsgBox("WELCOME! " & rdr.Item(4), MsgBoxStyle.Information)
cmd1.Connection.Close()
Response.Redirect("POS.aspx")
End If
A quick and dirty way to pass a variable is to use a session variable like:
Session("CurName") = CurName
Some other way: https://web.archive.org/web/20210125140826/https://www.4guysfromrolla.com/articles/020205-1.aspx
As you can see from the commented out code, I'm trying to get the model dropdown be affected by + selCurrentManuf.Text.
I get this error
'selCurrentManuf' is not declared. It may be inaccessible due to its protection level.
How can this be solved?
I can access the drop down in another part of the page like this..
Dim sc1_currentmanuf As String = CType(e.Item.FindControl("selCurrentManuf"), DropDownList).Text
However in the function i am trying to use selCurrentManuf does not have access to e
Dim sc1_currentmanuf As String = CType(dlContacts.Items(0).FindControl("selCurrentManuf"), DropDownList).Text
Dim myQuery As String = "SELECT * FROM c5_model where c5_manufid = " + sc1_currentmanuf
Right click on your .aspx page, and select the command Convert To Web Application.
Then you'll be able to write:
Dim myQuery As String =
String.Format("SELECT * FROM c5_model WHERE c5_manuf = '{0}'",
selCurrentManuf.SelectedItem.Text )
I'm assuming your functions are inside a class in your App_Code or another dll and not on the code behind of the page.
If so do this instead:
I'm assuming you have something like this on your asp page code behind:
Protected Sub selCurrentManuf_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetCurrentModel(selCurrentManuf.Text)
End Sub
Change Your GetCurrentModel Code To:
Function GetCurrentModel(Byval c5_manuf as String) As DataSet
Dim mySession = System.Web.HttpContext.Current.Session
Dim myQuery As String = "SELECT * FROM c5_model " 'where c5_manuf = " + + c5_manuf
Dim myConnection As New MySqlConnection(mySession("localConn"))
myConnection.Open()
Dim myCommand As New MySqlCommand(myQuery, myConnection)
Dim myDataAdapter = New MySqlDataAdapter(myCommand)
Dim myDataset As New DataSet
myDataAdapter.Fill(myDataset, "c5_model")
Dim dr As DataRow = myDataset.Tables(0).NewRow
myDataset.Tables(0).Rows.Add(dr)
GetCurrentModel = myDataset
myConnection.Close()
End Function