How do I make it so everyone has a separate account when they login - vb.net

I am trying to create a login system for a revision app. However, I was wondering if there was a way where everyone can have separate accounts.
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
Dim sqlstring As String
sqlstring = "select * FROM login where username = '" & txtusername.Text & "'"
connection.Open()
dataadapter = New OleDb.OleDbDataAdapter(sqlstring, connection)
dt.Clear()
dataadapter.Fill(dt)
connection.Close()
If dt.Rows.Count = 0 Then
MsgBox("no such user")
Exit Sub
End If
If dt.Rows(0)(2) = Txtpassword.Text Then
Flashcard.Show()
Else
Txtpassword.Text = ""
txtusername.Text = ""
MsgBox("Invalid username and password combination")
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Register.Show()
End Sub
That's the code I have if a user already has an account.
Imports System.Data.OleDb
Public Class Register
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New oledbconnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into login ([username],[password]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(TextBox1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(TextBox1.Text, String)))
MsgBox("You have successfully signed up!")
Form1.Show()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
TextBox1.Clear()
TextBox2.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
That's the code if the user presses the register button (does not have an account).
This code works where the user can succesfully login or register, but the problem is that everyone will have the same windows form. So, I was wondering if there was a way to make each windows form unique to each user?

You can declare and initialize a variable on the same line. The only information you need is if the userName and password exist in the database. Don't pull down data your don't need. You can get this with Count.
Always declare and dispose the connection and command it the method where they are used. Both of these objects need to be disposed so that their unmanaged resources can be released. Using... End Using blocks handle this.
Always use parameters to avoid sql injection. In OleDb the order that the parameters appear in the sql string must match the order that they are added to the parameters collection.
Don't open the connection until directly before the .Execute...
Private ConStr As String = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb" '"Your connection string"
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
Dim rowCount As Integer
Dim sqlstring = "select Count(*) FROM login where [username] = #UserName ANd [password] = #password;"
Using connection As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sqlstring, connection)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = txtusername.Text
connection.Open()
rowCount = CInt(cmd.ExecuteScalar)
End Using
If rowCount = 0 Then
MsgBox("no such user")
Else
Flashcard.Show()
End If
End Sub
Same ideas for the insert. A text box's Text property is always a String so you don't have to convert it.
You are not doing the parameters correctly. You are not using these parameters because the don't appear in the CommandText
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Command = " insert into login ([username],[password]) values (#UserName, #Password);"
Try
Using myconnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox2.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
MsgBox("You have successfully signed up!")
Form1.Show()
TextBox1.Clear()
TextBox2.Clear()
End Sub
Finally, and very important. You should never store passwords as plain text. Look into salting and encrypting.

Related

Confirmation of Old Password

I am having a problem in my condition of changing password. I want to make it simple by confirming the old password and then change the password. Here is my code
Private Sub btnCChangePass_Click(sender As Object, e As EventArgs) Handles btnCChangePass.Click
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\VB.net\My Projects\InventoryData.accdb"
Dim SqlString As String = "Update Cridentials SET [Password] = #pass"
Dim pass As String = "SELECT [Password] from Cridentials"
Dim conn As New OleDbConnection(ConnString)
conn.Open()
'this part is my problem
If (txtCOldPass.Text <> pass) Then
MsgBox("Wrong Old Password", MsgBoxStyle.Critical, "Password not matched")
ElseIf txtCOldPass.Text = Nothing And txtCNewPass.Text = Nothing And txtCConPass.Text = Nothing Then
MsgBox("Please submit the following information", MsgBoxStyle.Critical, "Incomplete")
ElseIf txtCNewPass.Text <> txtCConPass.Text Then
MsgBox("New Password and Confirm Password in not matached", MsgBoxStyle.Critical, "Incomplete")
Else
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#pass", txtCNewPass.Text)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
MsgBox("Changing password Success!", MsgBoxStyle.Information, "Successs!")
Me.Close()
Form1.Show()
End If
txtCOldPass.Focus()
txtCOldPass.Clear()
txtCNewPass.Clear()
txtCConPass.Clear()
End Sub

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll

This is my code. help me to solve it thanks!
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed
Imports System.Data.SqlClient
Partial Class Staff
Inherits System.Web.UI.Page
' Dim conn As New SqlConnection("Data Source=USER-PC\SQLEXPRESS;Initial Catalog=carrental;Integrated Security=True;Pooling=False")
Dim con As New Data.SqlClient.SqlConnection
Dim cmd As New Data.SqlClient.SqlCommand
Dim dr As Data.SqlClient.SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
con.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\Desktop\oh manisku\PROJECT ABIS\project baru\project baru\App_Data\order.mdf;Integrated Security=True;Connect Timeout=30")
con.Open()
Catch ex As Exception
' MsgBox(ex.Message)
End Try
End Sub
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
cmd.CommandText = ("Select Username, Password from Admin WHERE Username ='" & txtusername.Text & "' and Password = '" & txtPass.Text) & "' "
cmd.Connection = con
dr = cmd.ExecuteReader
con.Close()
If dr.HasRows Then
MsgBox("Succesfully Login")
Response.Redirect("recalled.aspx")
Else
MsgBox("Invalid Username and Password")
End If
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
End Sub
Protected Sub SqlDataSource1_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
End Sub
End Class
As I said in my comment, you're closing the connection before reading the data. You should move the connection close to after you finished with the data reader.
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim con As New Data.SqlClient.SqlConnection
con.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\Desktop\oh manisku\PROJECT ABIS\project baru\project baru\App_Data\order.mdf;Integrated Security=True;Connect Timeout=30")
con.Open()
cmd.CommandText = ("Select Username, Password from Admin WHERE Username ='" & txtusername.Text & "' and Password = '" & txtPass.Text) & "' "
cmd.Connection = con
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("Succesfully Login")
Response.Redirect("recalled.aspx")
Else
MsgBox("Invalid Username and Password")
End If
dr.Close() ' close the datareader
con.Close() ' close the connection
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
End Sub
Calling ExecuteReader simply opens the stream. If you close the connection, you close the stream. To use a telephone analogy: it's like hanging up on someone, and then trying to have a conversation.
Please also switch to using parameterized queries since, as it stands, I could enter my username as ' OR 1 = 1 ; -- and I'd gain full access to the first account in your system.
Also, please look into ways to securely store passwords. You should never store passwords in your database in plain text, and you should never store passwords in a way that allows you to reverse them to the original user input. Passwords should be hashed with a salt. see here.

one time Login process

I have 2 forms in my winform application.Form 1 serves as a LogIn form and Form 2 serves as a page that a user would see after log in.Now my form 1 has two text boxes(for username and password) and a button(to login/show form 2).Every time a user runs the application, he has to login using form 1.What i want is, when a user logs in for once,from the next time on,he wouldn't have to log in anymore/he would see the form 2 directly instead of Form 1>Form 2. My code is :
Private Sub Login_Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Settings.UserName = "" Then
Me.Show()
Else
Try
provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source="
dataFile = "XXXXXXX"
connString = provider & dataFile
myConnection.ConnectionString = connString
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Login] WHERE [user_name] = #username AND [password] = #password", myConnection)
myConnection.Open()
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = My.Settings.UserName
cmd.Parameters.Add("#password", OleDbType.VarChar).Value = My.Settings.Password1
Dim adapter As New OleDbDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
If table.Rows.Count <= 0 Then
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
Else
Form1.Show()
Me.Close()
myConnection.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
My.Settings.UserName = user_name.Text
My.Settings.Password1 = password.Text
My.Settings.Save()
provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source="
dataFile = "D:\jyothi school\School Management\School Management\AddStudent.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Login] WHERE [user_name] = '" & My.Settings.UserName & "' AND [password] = '" & My.Settings.Password1 & "'", myConnection)
Dim dr As OleDbDataReader = cmd.ExecuteReader
If dr.HasRows Then
Form1.Show()
Me.Close()
Else
Me.Show()
'MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
End If
myConnection.Close()
End Sub
Basically, i want the textboxes's values to be saved some where and then the application would use it to log in instead of making the user log in every time!
First , create 2 settings object named Username and Password.Now on form 1's login button click, add these codes :
my.settings.username=username.text
My.settings.password=password.text
My.Settings.Save
I suggest you to create a splash screen. Now add a background worker. Code for backgroundworker :
If My.Settings.Username = "" Then
LogIn.Show
Else
Try
Dim cmd as new oledbcommand("Select * rom [table] where [user_name]=#username and password=#password",connectionstring)
con.Open()
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = my.settings.username
cmd.Parameters.Add("#password", OleDbType.VarChar).Value = my.settings.password
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
if table.rows.count <=0 then
SHow warning message
Else
Form2.Show
con.close
Catch ex as exception
Msgbox(ex.message)
End try

How to read and move read content via SQL into variables within VB.net and use a connectionstring from a module in forms?

This is my first question, by the way - and I'm not sure exactly how to ask, or say what's wrong. There's 3 things I can't sort so any help would be appreciated.
Module:
This and the first (login) form work as they are but I couldn't get either Form to reference con.connectionstring for them to use without having to re-use the string contained in "" (as they do below) - my attempts ended up with errors including saying that the state couldn't be changed as the connection was already open, but I'd like the same one string to be referenced from the Forms.
Module ConnectionModule
Public con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Public da As OleDb.OleDbDataAdapter
Public ds As DataSet = New DataSet
Public Path As String = Application.StartupPath
Public Sub OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
con.Open()
If con.State = ConnectionState.Closed Then
MsgBox("Connection to db not made.")
End If
End Sub
Public CurrentUser As String = Nothing
End Module
The First Form:
Public Class LoginForm
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
OpenDb()
con.Close()
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim ID As String = txtID.Text
Dim Pass As String = txtPassword.Text
If IsNumeric(ID) = False Or ID.Length > 4 Or Pass = Nothing Then
MsgBox("Staff ID is a 4-digit number and Password must not be blank.")
Else
Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
con.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then 'Correct:
MenuForm.Show()
Me.Hide()
CurrentUser = ID
Else 'Incorrect:
MsgBox("Staff ID or Password incorrect.")
txtPassword.Text = ""
txtID.Text = ""
txtID.Focus()
End If
Catch ex As Exception
MsgBox("Database Connection Error.")
End Try
con.Close()
End If
End Sub
End Class
A form to change the password:
The problem here is that lblUser (A clarification for the user to tell them which password will be changed) only outputs the data already within the program as a variable: CurrentUser (as assigned upon successful login). No error is produced but the full name of the user isn't shown (or possibly read from the database).
I'm also unsure how the UPDATE SQL command should be contained within the second procedure, btnAccept_click, here. What the syntax is, basically. I haven't found a clear example to look at.
Imports System.Data.OleDb
Public Class PasswordForm
Private Sub PasswordForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New System.Data.OleDb.OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Dim Returned(2) As String
CurrentUser = CurrentUser
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Title], [Forename], [Surname] FROM tblStaff WHERE [StaffID]='" & CurrentUser & "'", con)
Try
con.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
'Makes db contents variables
Returned(0) = reader.Item("[Title]").ToString
Returned(1) = reader.Item("[Forename]").ToString
Returned(2) = reader.Item("[Surname]").ToString
End If
reader.Close()
Catch ex As Exception
Me.Hide()
MsgBox("Database Connection Error.")
Finally
con.Close()
End Try
lblUser.Text = "Current User: " & CurrentUser & Returned(0) & Returned(1) & Returned(2)
''Only outputs CurrentUser
End Sub
Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccept.Click
Dim Current As String = txtCurrent.text
Dim NewPass As String = txtNew.Text
'Verification
If txtNew.Text = txtConfirm.Text And NewPass.Length <= 20 Then
Dim cmd As OleDbCommand = New OleDbCommand("UPDATE tblStaff SET [Pword]='" & NewPass & "' WHERE [StaffID]='" & CurrentUser & "'", con)
End If
End Sub
End Class
Thank you, again, for anyone with ideas (especially exact code).
Oh and throughout what's here there are no errors thrown. Just missing content.
you are opening the connection in openDB() and you are trying to open it again in form1, this will throw the error you are getting. So comment all the con related lines in your form. Same comment for your passowrd form also.
'Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
'con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
'con.Open()
...
end try

login form using ms access in vb.net

I'm creating a login form for vb.net using ms access 2003 as database. But it only checks for the username and bypasses the password. Meaning that if the username is correct and the password doesn't jive with the username, the user can still enter the system. Here is my code:
Try
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from admintable where AdminName= '" & TextBox4.Text & "' ", cn)
cn.Open()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("AdminName")
NoPas = rdr("AdminPass")
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
adminview.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox4.Clear()
TextBox3.Clear()
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
How do I do it so that it checks both username and password?
You are using a single line IF .. THEN :
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
so the next line will always be executed:
adminview.Show()
you have to rearrange your IF .. THEN conditions
I will share about login system in vb.net using binding navigator that less of coding. just following the link below!
http://www.tesear.com/2011/09/login-system-in-vbnet.html
You could have BOTH the uname and pword in the database and "WHERE" on both, if you get no record back, then you have your answer.
Try using System.String.Compare(String str1,String str2, Boolean ) As Integer like:
If (System.String.Compare(TextBox4.Text, NoAcc, false) And System.String.Compare(TextBox3.Text, NoPas, false)) Then NoAccmod2 = NoAcc
here is the code:
Imports System.Data
Imports System.Data.OleDb
Public Class Form5
Inherits System.Windows.Forms.Form
Dim mypath = Application.StartupPath & "\login.mdb"
Dim mypassword = ""
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Dim sql = "SELECT UserID ,PassID FROM MYTAB WHERE USERID='" & TextBox1.Text & "' AND PASSID='" & TextBox2.Text & "'"
cmd = New OleDbCommand(sql, conn)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MessageBox.Show("Authentication failed...")
Me.Show()
Else
MessageBox.Show("Login successfully...")
Dim frmDialogue As New Form11
frmDialogue.ShowDialog()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Close()
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Me.Hide()
Dim frmDialogue As New Form1
frmDialogue.ShowDialog()
End Sub
Private Sub Form5_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim frm As New Form1
frm.Show()
End Sub
End Class
Try
Dim NoAcc As String
Dim NoPas As String
Dim rdr As OleDbDataReader
Dim cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\mobilestore.accdb;Persist Security Info=False;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from logindata where Username= '" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", cnn)
'NoAcc = TextBox1.Text
'NoPas = TextBox2.Text
cnn.Open()
rdr = cmd.ExecuteReader
If (rdr.Read()) Then
NoAcc = rdr("Username")
NoPas = rdr("password")
If (TextBox1.Text = NoAcc And TextBox2.Text = NoPas) Then
Adminpage.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
End Sub