one time Login process - vb.net

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

Related

How do I make it so everyone has a separate account when they login

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.

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

how do i code for user login when logging in specific form authorized else block them using vb and sql server

My code below does not block other user who's col1 and col2 in sql does not match. Need help resolve
trying to give access to user if userid matches dept name and open specific form. If userid1 and dept1 matches open Form1 and userid2 and dept2 matches open Form2 else unauthorized user.
Private Sub BTNLOGIN_Click(sender As System.Object, e As System.EventArgs) Handles BTNLOGIN.Click
Try
Dim myconn As New SqlClient.SqlConnection("connection string;")
myconn.Open()
Dim sql As String = "select USERNAME,DEPT FROM USERS where USERNAME = '" & TXTBUNAME.Text & "'AND DEPT='" & CmbDept.Text & "'"
Dim CMD As SqlCommand = New SqlCommand(sql, myconn)
Dim reader As SqlDataReader = CMD.ExecuteReader
If reader.Read Then
CmbDept.SelectedIndex = "#DEPT"
Me.Dispose()
Else
MessageBox.Show("Unauthorized User")
Me.Show()
End If
Catch ex As Exception
End Try
If CmbDept.Text.Trim = "option1" Then
Form1.Show()
End If
If CmbDept.Text.Trim = "option2" Then
Form2.Show()
End If
End Sub
my code is good for 1 user in each dept. How can I have multi users from same department but need to authenticate user id with environment login. No password isstored in SQL. Table col's USERID, EMP NAME & DEPT
Try
Dim conn As New SqlClient.SqlConnection("Connection String;")
conn.Open()
Dim Command As New SqlCommand("SELECT USERID,Dept FROM TABLENAME WHERE USERNAME ='" & UName & "'and Dept ='" & CmbDept.SelectedItem & "'", conn)
Dim da As SqlDataAdapter = New SqlDataAdapter(Command)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
If (dt.Rows.Count > 0) Then
If (CmbDept.SelectedIndex = 0) Then
Dim a As New form1
a.Show()
Me.Hide()
ElseIf (CmbDept.SelectedIndex = 1) Then
Dim b As New form2
b.Show()
Me.Hide()
End If
Else
MessageBox.Show("invalid User")
Me.Show()
End If
Catch ex As Exception
End Try
End Sub

Data source name not found and no default driver specifie

Help i am using vb.net2010 and trying to access my database through sqlyog but there seems to be an error on con.Open() line.(I'm trying to create a login form with a database and this is my first time)
Public con As New Odbc.OdbcConnection
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
con = New Odbc.OdbcConnection("dsn=cara")
Dim cmd As New Odbc.OdbcCommand
Dim reader As Odbc.OdbcDataReader
cmd.Connection = con
con.Open()
cmd.CommandText = " SELECT username,password FROM userinfo WHERE username='" & txtusername.Text & "' and password='" & txtpassword.Text & "'"
reader = cmd.ExecuteReader
If reader.HasRows Then
Admin_Page.Show()
Else
MessageBox.Show("Invalid Username or Password")
End If

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