Multiple User Registration Form vb.net - vb.net

I have a user registration form for multiple users. This works fine except the code is unable to identify if there is already username exist. I know there is mistake in my code but I am unable to rectify that one.
Code is below can anyone help me sort this, how to write modify code for reader
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim user, pass As String
user = UsernameTextBox.Text
pass = PasswordTextBox.Text
Dim connection1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Credentials.mdb;")
Dim command As New OleDbCommand("SELECT [ID] FROM [Staff] WHERE [usernameField] = username AND [passwordField] = password", connection1)
Dim usernameParam As New OleDbParameter("username", Me.UsernameTextBox.Text)
Dim passwordParam As New OleDbParameter("password", Me.PasswordTextBox.Text)
command.Parameters.Add(usernameParam)
command.Parameters.Add(passwordParam)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User Exist")
MyPlayer.SoundLocation = path & LogOnsound
PasswordTextBox.Text = ""
UsernameTextBox.Text = ""
ElseIf user = "" Or pass = "" Then
MsgBox("Please Fill The Boxs", , "Error")
Else
Dim connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Credentials.mdb;"
Using myconnection As New OleDbConnection(connection)
myconnection.Open()
Dim sqlq As String = "INSERT INTO [staff] ([username], [password]) VALUES (#user, #pass)"
Using cmd As New OleDbCommand(sqlq, myconnection)
cmd.Parameters.AddWithValue("#usernme", user)
cmd.Parameters.AddWithValue("#passwrd", pass)
cmd.ExecuteNonQuery()
MsgBox("User Registered!", , "register")
user = ""
pass = ""
End Using
End Using
End If
command.Connection.Close()
End Sub

It looks like you have multiple things wrong:
You should be specifying #username instead of just username in your SELECT statement so that it will be recognized as a parameter.
Why are you checking for a match on password also? If you do that, people can have the same username with just a different password...do you want that?
In your SELECT, you have usernameField as the column name in your Staff table, but in your INSERT, you have username as the column name. Which is it?
In your INSERT, you specify the parameter #user, but in your cmd.Parameters.AddWithValue statement, you have #usernme.

Related

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

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 :)

Attempting to validate username (email address) and password - having issues - vb.net

I have a Windows Form app that is not properly validating the user input information. Need some help.
I inserted the Microsoft Login form and am writing code to verify the user credentials. Using an Access DB to store and retrieve info. Two tables - one for email address and another for password.
I verify format of the email addy using regex. This works very well.
I validate the email address is in correct form and verify it is in the table (this works well). Then I attempt to read the password (appears this is not working as expected) and then read both bits of information from the tables. Next, I test to make sure both are present. If both are present control is passed to another form.
My issue is reading/verifying the password.
Here is my Visual Studio VB.net code.
Private Sub OK_Click(sender As System.Object, e As System.EventArgs) Handles OK.Click
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Try
If i = 0 Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
'Change the following to your access database location
dataFile = "\11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
i = 1
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
'the query:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "'", myConnection)
Dim com As OleDbCommand = New OleDbCommand("SELECT * FROM [Password] WHERE [Password] = '" & txtPassword.Text & "'", myConnection2)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
Dim drp As OleDbDataReader = com.ExecuteReader()
' the following variable is hold true if EmailAddress is found, and false if EmailAddress is not found
Dim userFound As Boolean = False
' the following variable is hold true if Password is found, and false if Password is not found
Dim passwordFound As Boolean = False
' the following variables will hold the EmailAddress and Password if found.
Dim EmailAddressText As String = ""
Dim PasswordText As String = ""
'if found:
While dr.Read()
userFound = True
EmailAddressText = dr("EmailAddress").ToString
End While
While drp.Read()
passwordFound = True
PasswordText = drp("Password").ToString
End While
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
End Sub
Well first your approach isn't really safe due to the fact the the password isn't encrypted and that either there is no link between email and password ideally you would have table for example:
USER
--UID
--Email
PASS
--ID
--UID
--PASS
And you would hash your password for example sha512 furthermore for more security you would use Salt and certificates to secure the database connection.
Then you could do:
Hash current password in textbox and execute:
"SELECT USER.Email FROM USER,PASS WHERE USER.Email='TEXTBOX_EMAIL' AND USER.UID = PASS.UID"
Check if you have result if yes your connected.
However I tried to correct a bit what you did in the above code. Having used only SQLClient and not Olecommand i tried to keep what you did so there might be few syntax errors but should be ok:
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Dim passwordFound As Boolean
Dim userFound As Boolean
Using con As New SqlClient.SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =\ 11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb")
'Using to make sure connection is disposed
'Open connection
con.Open()
'Prepare sql
Dim command As New OleDbCommand("SELECT [emailAddress] FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "';", con)
'Create the reader
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim Id As String = ""
' Call Read before accessing data.
While reader.Read()
'Get data
Id = reader(0)
End While
'Close Reader
reader.Close()
If Id <> "" Then
'User found
userFound = True
'Prepare the second sql
Dim command2 As New OleDbCommand("SELECT [Password] FROM [Password] WHERE [Password] = '" & txtPassword.Text & "';", con)
'Prepare second reader
Dim reader2 As OleDbDataReader = command.ExecuteReader()
Dim Pass As String = ""
' Call Read before accessing data.
While reader2.Read()
'Get tdata
Pass = reader2(0)
End While
reader.Close()
If Pass <> "" Then
'Pass found
passwordFound = True
Else
passwordFound = False
End If
Else
userFound = False
End If
'Close connection
con.Close()
'Clear connection pool
SqlConnection.ClearPool(con)
End Using
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
Decided to combine the email and passwords into one table. Made everything easier for now. Thanks for your help and suggestions.

Can not retrieve data from MySql database

when I run the code, I have an error message that says: Object reference not set to an instance of an object. I would like to create a code that verify credentials that are in the database. If the user that not enter valid information, an error message appears. Here is my code:
'Declare variables
Dim pwd, username As String
Dim dbpwd, dbUsername As String
'Get credentials variables
username = Me.username.Text
pwd = Me.TextBox2.Text
Dim objConn As MySqlConnection
Dim objDataset As New DataSet
Dim objDataAdapter As MySqlDataAdapter
Dim sqlConn As String
If username <> "" And pwd <> "" Then
objConn = New MySqlConnection("server=localhost;userid=root;password= ;database=mayombe_mdcs")
objConn.Open()
sqlConn = "select agent_id, Password from password where agent_id = " & username & ""
Try
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.Fill(objDataset)
' intRowNumber = sqlR
dbUsername = objDataset.Tables("password").Rows(1).Item(2)
' dbpwd = objDataset.Tables("password").Rows(1).Item(1)
'WriteLine (dbUsername )
'Force users to enter credentiasl
objConn.Close()
'Force user to enter true credentials
If pwd = dbpwd And username = dbUsername Then
open form
Me.Close()
End If
Catch ex As Exception
strMsg As String
Prompt message that tells the user that credentials entered are not correct.
strMsg = String.Format("One of the following is incorrect: {0}* Username entered {0}* Password entered.", Environment.NewLine)
MessageBox.Show(strMsg, "Warning")
End Try
There are some things wrong in your code.
First, if agent_id is a varchar field you need to use single quotes around the value used in the where clause, but it is better to avoid this problem and use a parameterized query.
Second, if you find something then you should refer to the first row using index 0 and to the second column using index 1. Your code assumes that indexing of an array starts at index 1 but this is not true in the NET world. Arrays always start at index 0.
I would try to rewrite your code as this
objDataset = new Dataset()
sqlConn = "select agent_id, Password from password where agent_id = #usr"
using objConn = New MySqlConnection(....)
objConn.Open()
Try
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.SelectCommand.Parameters.AddWithValue("#usr", username)
objDataAdapter.Fill(objDataset)
if objDataset.Tables(0).Rows.Count > 0 Then
dbUsername = objDataset.Tables(0).Rows(0).Item(1).ToString
End If
End Using

Cheking duplicate name and insert user vb.net

I am doing a form where the user is writing his username and choose from a button list. Before the insert i need to check if the username is already existed or not. The server side code is:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
'Duplicate username
Dim username As String = tbUsername.Text.Trim()
Dim tempUser As Byte = CByte(rblDept.SelectedIndex)
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim haha As DataTable = New DataTable()
Using adapter = New SqlDataAdapter(query1, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter.Fill(haha)
If haha.Rows.Count <> 0 Then
lblmessage.Text = "Error! user name is already exist"
Return
End If
End Using
'Insert new user
Dim query As String = "Insert into Intranet.dbo.Gn_ISCoordinators (cUserName,lDeptUser) Values ('" & username & "'," & tempUser & ")"
Dim hehe As DataTable = New DataTable()
Using adapter1 = New SqlDataAdapter(query, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter1.Fill(hehe)
lblmessage.Text = "User has been added"
End Using
End Sub
So when the user press the button it first check the duplicate username if everything is ok, then it inserts the row.
Btw the error is occur when i press on submit button and it gave me this Must declare the scalar variable "#cUserName". on adapter.Fill(haha) line.
Please i want to know what is wrong with my code. Help me
Thanks in advance.
Error message shows everything you need to know to solve that issue. You're using parameter #cUserName in your query, but it is never set.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn )
Dim param As New SqlParameter()
param.ParameterName = "#cUserName"
param.Value = username
command.Parameters.Add(param)
Using adapter = New SqlDataAdapter(command)
You are using a Parameter #cUserName but you did not initialize it or pass values to it.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn)
command.Parameters.AddWithValue("#cUserName",username)
Using adapter = New SqlDataAdapter(command)