Issue Log in vb.Net? - vb.net

I have a problem with a log in... Well let me explain you my problem, the problem is that i want to create a log in with restrictions, I have some textbox with the binding source property changed to my database. But when I type something that is not in the DataBase the program got freezes, I will post my code, hope you can help me (=
Private Sub KryptonButton1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles KryptonButton1.Click
If txtUser.Text <> UserTextBox.Text Then
While txtUser.Text <> UserTextBox.Text
Me.UsuarioContraseñaBindingSource.MoveNext()
End While
If txtUser.Text = UserTextBox.Text Then
KryptonMessageBox.Show("Welcome")
Else
KryptonMessageBox.Show("Error")
End If
End If
End Sub

Have a closer look at the loop in your code and its exit condition … under what circumstances does the loop exit? What happens otherwise?
In general you need play out and cover all scenarios but you already know the scenario here: your user input is not in the database and the application freezes. This should provide ample hints to find the cause.

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If txt_user.Text <> vbNullString And txt_pass.Text <> vbNullString Then
Dim chkcmd As New SqlCommand("select * from users where username = '" & txt_user.Text & "' and password = '" & txt_pass.Text & "'", con)
If con.State = ConnectionState.Open Then con.Close()
con.Open()
Dim chkval As SqlDataReader = chkcmd.ExecuteReader
If chkval.Read = True Then
Me.Hide()
Form2.Show()
Else
MsgBox("Invalid key to login!", MsgBoxStyle.Exclamation, "Message")
txt_pass.Clear()
txt_user.Clear()
txt_user.Select()
End If
con.Close()
End If
End Sub

Related

Encrypting Password With Windows Form VB.NET

I was wondering if anyone is able to guide me in the right direction as to how to encrypt passwords given by a windows form in VB.net. I am fairly new to programming so some specialist terms may not make sense. I also store the username and password in an access database. Should this be encrypted? If so how? Or should i encrypt the password before pressing enter so that the encrypted value is stored? Any help or information whatsoever will be appreciated. I will respond quickly to any questions you may have in order to provide you with further information. I will provide my code now, (as i do not think it is of relevance) ::::::
Imports System.Data.OleDb
Imports System.Data
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Label4_Click(sender As Object, e As EventArgs) Handles Label4.Click
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox2.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Then
MsgBox("Please Complete All Fields")
Else
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Computer Science\CA\tyre_stock_database_21.accdb")
Dim insert As String = "Insert into login_info values('" & TextBox1.Text & "','" & TextBox2.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Account Successfully Created")
Me.Close()
Catch ex As Exception
MsgBox(String.Format("Error: {0}", ex.Message))
End Try
End If
End Sub
End Class

vb.net login with sqlite

im trying to create a login form in vb.net with SQLite with this code
Imports System.Data.SQLite
Public Class frmLogin
Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim table As DataTable = Nothing
Dim da As New SQLiteDataAdapter("Select * from user_tbl where username='" & txtuser.Text & "'and pass_id='" & txtpass.Text & "'", myconn)
Try
If txtuser.Text = "" And txtpass.Text = "" Then
MessageBox.Show("Please fill Username and Password", "Important", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtuser.Focus()
Else
da.Fill(table)
If table.Rows.Count > 0 Then
frmMain.Show()
Me.Close()
Else
MessageBox.Show("login not successful")
End If
da.Dispose()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ConnectME()
End Sub
End Class
but i keep getting an error at line 26 "da.fill(table)"
Here is what the error says:
Here are two lines of your code:
Dim table As DataTable = Nothing
da.Fill(table)
You have no code in between that assigns an object to that table variable. Why exactly are you surprised that there's an issue here? If I told you to fill a bag and then handed you no bag, how exactly would you go about filling it? You couldn't, because you can't fill a bag that doesn't exist, yet you expect your app to be able to fill a DataTable that doesn't exist.

Please complete required fields message box

I'm trying to do a "Please complete required fields" messagebox.
Tt does show up but "Account Created" also pops out just right after "Please complete required fields" appears whenever I try entering even one character in a textbox or clicking one of the two radio button.
Also instead of "Please complete required fields", "User already exists!" shows up whenever the fields are empty.
Can somebody tell me what's wrong with my codes?
Thank you....
Public Class CreateAccount
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname, #pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
conn.Open()
Dim strUsername As String = TextBox1.Text
Dim boolUsernameExists As Boolean = False
Using dbConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb")
dbConnection.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", dbConnection)
dbCommand.Parameters.AddWithValue("#uname", strUsername)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result > 0 Then
boolUsernameExists = True
End If
End Using
dbConnection.Close()
End Using
If boolUsernameExists Then
MessageBox.Show("Username already exists!")
Return
End If
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
conn.Close()
If TextBox1.Text = "" Or TextBox2.Text = "" Or RadioButton1.Checked = False Or RadioButton2.Checked = False Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Hide()
LoginUser.Show()
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.Back '<--- this is for backspace
Case 13
e.Handled = True
SendKeys.Send("{TAB}") '<---- use to tab to next textbox or control
KeyAscii = 0
Case Is <= 32
' KeyAscii = 0
Case 48 To 57 '<--- this is for numbers
Exit Sub
Case 65 To 90 '<--- this is for Uppercase Alpha
Exit Sub
Case 97 To 122 '<--- this is for Lowercase Alpha
Exit Sub
Case Else
e.Handled = True
MessageBox.Show("You can only input letters and numbers!", "Create Account")
End Select
End Sub
Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
End Class
I agree with DavidSdot, your code is out of order.
Here is an example that might work. I say might because im not very good at vb.net. So you might need to change a few things to make it work. However, that being said, the following might do you well regarding the correct order in which it should go.
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
If ((TextBox1.Text <> "" And TextBox2.Text <> "") And (RadioButton1.Checked <> False Or RadioButton2.Checked <> False)) Then
conn.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", conn)
dbCommand.Parameters.AddWithValue("#uname", TextBox1.Text)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result = 0 Then
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname,#pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
Else
MessageBox.Show("Username already exists!")
Return
End If
End Using
Else
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
You should really take a look at the logic of Button1_click sub, because it is really hard to understand.
You opening your database twice
you already inserted a user with username="" and password="" thats why you get user exists message when you have not enter anything
Account created successfully! is always shown after Please complete the required fields as there is no check/return/whatever when fields as missing
No idea why the DB Insert is called on every keystroke as there is no code for that in what you posted

check database connection using background worker

I already banging my head with this problem, I use backgroundWorker to check if database is OPEN and here's my code for that:
Public Class Form1
Delegate Sub SetLabelText_Delegate(ByVal [Label] As Label, ByVal [text] As String)
Dim sqlconnection As New SqlConnection("Data Source=" & My.Settings.Server & ";Initial Catalog=" & My.Settings.Database & ";Integrated Security=false;user id=" & My.Settings.Username & ";password=" & My.Settings.Password & ";Connection Timeout=5;")
Dim connectionStatus As String
Private Sub SetLabelText_ThreadSafe(ByVal [Label] As Label, ByVal [text] As String)
If [Label].InvokeRequired Then
Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Label], [text]})
Else
[Label].Text = [text]
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'I store my database information to my.settings then display it on textboxes for manipulation
TextBox1.Text = My.Settings.Server
TextBox2.Text = My.Settings.Database
TextBox3.Text = My.Settings.Username
TextBox4.Text = My.Settings.Password
'just getting my computer name
lblCompName.Text = System.Windows.Forms.SystemInformation.ComputerName
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
If sqlconnection.State = ConnectionState.Closed Then
sqlconnection.Open()
connectionStatus = "Online"
'sqlconnection.Open()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: online")
End If
Catch ex As Exception
connectionStatus = "Offline"
sqlconnection.Close()
SetLabelText_ThreadSafe(Me.Label1, "Database Status: offline")
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
Label1.Text = "Database Status: " & connectionStatus
Else
Label1.Text = "Database Status: " & connectionStatus
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
end class
In my code above it does actually works, it does display "database is online/offline" when restarting my program within the visual studio but when I run the program then turn-off/disable my network connection(my database is on other computer) it always display "Database is ONLINE" but I'm pretty sure that there is already no connection between my pc and database(because I PING it) so it must be display as "Database is oFFLINE".
Did I missed something regarding of using backgroundWOrker? Oh BTW, I'm new in using BackgroundWorker.
Any help or alternative solutions is much appreciated thanks!

Multiple validation in vb.net textbox

The problem i am having is after checking if the field is blank i want program to stop at that, right now it is going ahead and checking the username password also even though the field is blank and printing wrong username password. i am really new at this so please excuse the lack of knowledge
Private Sub ButtonOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOk.Click
Try
Dim con As New SqlConnection("Initial Catalog=stock;Data source=.;integrated security=true")
Dim ds1 As New DataSet
Dim da1 As New SqlDataAdapter("select * from login where Name='" & Trim(txtusername.Text) & "'and password='" & Trim(txtpassword.Text) & "'", con)
If txtpassword.Text.Length = 0 Then
MsgBox("Password or username feild left blank")
End If
If da1.Fill(ds1) Then
adminmain.Show()
Me.Close()
Else
MsgBox("Invalid Password or Username")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Then Return from the function.
If txtpassword.Text.Length = 0 Then
MsgBox("Password or username feild left blank")
Return
End If
But outside of the Try/Catch although it would work(a finally-block would be executed before the return statement). Actually the validation of the TextBox does not need to be inside of the Try/Catch, so imho it's confusing to return from within a Try/Catch.
Put your validations at the top of the Sub, and call Exit Sub as soon as an error is found.
Private Sub ButtonOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOk.Click
If txtpassword.Text.Length = 0 Then
MsgBox("Password or username feild left blank")
Exit Sub
End If
'Other validations here
'Code to save changes here
End Sub
Also, you should remove that Try..Catch clause. If an unexpected error occurs you'll want to know what is the line number and stack trace of the error.