How to make log in code in vb.net - vb.net

Hello Guys please help me about this code,
This is simple log in code in visual studio 2013, my problem is, i try to make wrong password and user name, but the message box does not shows, it means no event after the "else"
HERE IS MY CODE:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
dr.Read()
If dr.Item("UserName") = txtTeacher.Text And dr.Item("UserPass") = txtPword.Text Then
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub

Your issue is that your query "SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'" does not return anything when you enter the wrong password, so it never even executes the code within the If dr.HasRows = True Then block.
Also, you should NEVER store passwords in plain text. Hash them. And, you should always use parameters to preclude SQL injection attacks.
So, you would want to change your code to something like this:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = #UserName AND UserPass = #HashedPassword")
cmd.Parameters.Add(New OleDbParameter("#UserName", txtTeacher.Txt))
cmd.Parameters.Add(New OleDbParameter("#HashedPassword", HasherFunction(txtPword.Txt)))
Note the addition of the parameters and also the HasherFunction which you would have to build to hash your password accordingly.
There are plenty of resources available about SQL injection and how to avoid it. Here's one I found at the top of the Google search: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

you almost there in your code, just don't repeat the checking if the user exists in the database, and you code should be like this based on what you put in the question
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
' you don't need to check again if the user and password are same since you made it
' in you query to database
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub
hope it will help you

Related

Data type mismatch in criteria expression while updating password field

This is my Select & Update code for OLEDB DB.
I am getting a Data type mismatch in criteria expression error whilst changing the Password field value.
All four fields are set to Long Text datatype.
Update Query
con = Class1.dbconn
cmd = New OleDbCommand("Update User_details set User_ID ='" & TextBox1.Text & "', User_Name='" & TextBox2.Text & "', [Password]='" & TextBox3.Text & "' where Sno='" & Label4.Text & "'", con)
cmd.ExecuteNonQuery()
MessageBox.Show("User Details Updated")
Select Query
cmd = New OleDbCommand("select * from User_details where User_ID='" & TextBox1.Text & "'", con)
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.Read Then
Label4.Text = dr("Sno").ToString
TextBox2.Text = dr("User_Name").ToString
TextBox3.Text = dr("Password").ToString
TextBox2.Text = TextBox2.Text.Replace(" ", "")
TextBox3.Text = TextBox3.Text.Replace(" ", "")
dr.Close()
End If
Keep your database objects local so you can control when they are closed and disposed. Using...End Using blocks take care of this for you even if there is an error. The Using blocks demonstrated here take care of both the connection and the command. Note the comma after the connection line.
Always use Parameters. Not only does it make your command text easier to read and write (without all the quotes, double quotes and ampersands) but it protects your database from the destruction of Sql injection. When you are using the OleDb provider it is essential that order that the parameters appear in the command text match the order they are added to the parameters collection. Unlike Sql Server, Access pays no attention to the names of the parameters; only the order.
Notice that the connection is not opened until right before the .Execute... and is closed (with the End Using) directly after. Connections are precious resources. I used a DataTable instead of a DataReader in the SelectUser sub so I could close the connection before updated the user interface. In the UpdatePassword sub the connection is closed before showing the MessageBox. After all the end user could have gone to lunch and there would be your connection flapping in the breeze.
As far as the type mis-match check the links provided by #Jimi and then check your database to see if the OleDbType matches.
Private Sub UpdatePassword()
Using con As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("Update User_details set User_ID = #ID, User_Name = #Name, [Password]= #Password Where Sno= #Sno;", con)
With cmd.Parameters
.Add("#ID", OleDbType.LongVarChar).Value = TextBox1.Text
.Add("#Name", OleDbType.LongVarChar).Value = TextBox2.Text
.Add("#Password", OleDbType.LongVarChar).Value = TextBox3.Text
.Add("#Sno", OleDbType.LongVarChar).Value = Label4.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
MessageBox.Show("User Details Updated")
End Sub
Private Sub SelectUser()
Dim dt As New DataTable
Using con As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("select * from User_details where User_ID= #ID;", con)
cmd.Parameters.Add("#ID", OleDbType.LongVarChar).Value = TextBox1.Text
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
Dim row As DataRow = dt.Rows(0)
Label4.Text = row("Sno").ToString
TextBox2.Text = row("User_Name").ToString
TextBox3.Text = row("Password").ToString
TextBox2.Text = TextBox2.Text.Replace(" ", "")
TextBox3.Text = TextBox3.Text.Replace(" ", "")
End If
End Sub
Finally, you should NEVER store passwords as plain text. They should be salted and hashed. I will leave it to you to research how to do this.

simple login form error VB 2010

I've search a lot of resources and couldn't fix it.
My problem is when I click the button event the next form doesn't show and also I want to close my login form at the same time.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim firstname As String = ""
Dim lastname As String = ""
Dim ara As Boolean = False
cn = New OleDbConnection(con)
cn.Open()
Dim user As String
Dim pass As String
user = TextBox1.Text
pass = TextBox2.Text
With cmd
.Connection = cn
.CommandText = "Select * from users WHERE username='" & user & "' AND password='" & pass & "'"
.ExecuteNonQuery()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
ara = True
While rdr.Read()
firstname = rdr("firstname").ToString
lastname = rdr("lastname").ToString
lib_name = firstname + lastname
End While
If ara = True Then
Form2.Show()
Me.Close()
x = True
Else
MsgBox(" Access Denied!" + Environment.NewLine + "Sorry, username or password is incorrect!")
End If
End If
End With
cn.Close()
cmd.Dispose()
1 : You are opening the gates of SQL INJECTION. Read more . Instead of passing values directly in your query, pass parameters first and use them later(For unknown reason, the code formatting is not working below) :
Dim cmd as New OleDbCommand("Select * from users WHERE username=#user AND password=#pass" , con)
With cmd
.Parameters.Add("#user", OleDbType.Varchar).Value = user
.Parameters.Add("#user", OleDbType.Varchar).Value = password
End With
2 : Your If statement will only work IDateReader.HasRows returns true and if ara=True which is unnecessary. .HasRows is a boolean, you don't need to create another boolean and pass the value to it. However, the rest of your code will only execute if your conditions match
3 : Form1.Close and AnotherForm.Show will never work if in your Project Proerties , Shutdown Mode is set to On main window close(by default). Either change it to On Explicit window close or On last window close or change
Me.CLose To
Me.Hide
4 : In order to reduce too much code , you can use Using Statement :
Using cmd as New SqlCommand("Select * from users WHERE username=#user AND password=#pass" , con)
'''codes here
End Using
''Now no need to call cmd.Dispose
Hope this helps :)

How to update the account table?

I need help with my update query. I need to finish this by tomorrow. I think my codes are wrong.
My form:
My database:
My code:
'user wants to change password
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\db1.accdb;Persist Security Info=True")
Try
connection.Open()
Dim command As OleDbCommand = connection.CreateCommand
command.CommandType = CommandType.Text
command.CommandText = "Update UserAccount SET Password ='" + TextBox2.Text + "' WHERE Username = User"
command.ExecuteNonQuery()
MsgBox("Updated")z
TextBox2.Text = ""
TextBox3.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
Common mistake. The problem is here:
... WHERE Username = User"
It's looking for a field named User.
Is the username actually User? If so, wrap it in quotes:
... WHERE Username = 'User'"
Is User actually a variable holding the username? If so:
... WHERE Username = '" & User & "'"

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

VB Login form ASP.NET with membership or similar

need some minor help with declaring a new array that could read the sql username of the user (if logged in) and store it for later use, either to use it for pages that only authorized users could see (with simple if commands) or lockdown the whole site with web.config authorization system that would allow roles only for admins.
My code is 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=.;Initial Catalog=SoftCoD;User ID=sa;Password=fouf")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From users Where Name='" + 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
dr.Read()
*g_sUser=Name????MsgBox(g_sUser)*
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub
You can use any of the following method for holding the username for future use
Session
QueryString
Method 1 : Session
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
session("user")= g_sUser
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
Method 2 : QueryString
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
Response.Redirect("Default.aspx?username=g_sUser")
Else
Response.Redirect("login.aspx")
End If