Why is Visual Studio (VB) not reading my SQL connection string properly? - sql

I am writing a small windows tool to search a few SQL databases. I was able to connect and search the first database without issues but I keep getting the following login error when I try to search the second database (Database 2):
'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Login failed for user '\azahir'
You will find that <Domain>\azahir is not even specified in my connection string or anywhere in my few lines of code.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim Conn As SqlConnection
Dim Conn2 As SqlConnection
Private Sub btSearch_Click(sender As Object, e As EventArgs) Handles btSearch.Click
Conn = New SqlConnection("Data Source = <SERVER>;Initial Catalog=<DATABASE>;Integrated Security=SSPI;User ID = <Domain> \ axzahir;Password=<Password>;")
Conn.Open()
Dim cmd2 As SqlCommand = Conn.CreateCommand
cmd2.CommandText = "select firstname, lastname
from systemuserbase where firstname like" + "'%" + TxFirstName.Text + "%'" +
" And lastname Like" + " '%" + TxLastname.Text + "%'"
Dim dir As SqlDataReader = cmd2.ExecuteReader()
If dir.HasRows Then
Dim dtClient As New DataTable
dtClient.Load(dir)
dtOutput.DataSource = dtClient
End If
dir.Close()
Conn.Close()
End Sub
....
Private Sub btnArgus_Click(sender As Object, e As EventArgs) Handles btnArgus.Click
Conn2 = New SqlConnection("Data Source = <SERVER2>;Initial Catalog=<DATABASE 2>;Integrated Security=SSPI;User ID = <DOMAIN> \ axzahir;Password=<PASSWORD>;")
Conn2.Open()
Dim cmd3 As SqlCommand = Conn2.CreateCommand
cmd3.CommandText = "select userID, Fullname
from Users where FullName like" + "'%" + TxFirstName.Text + "%'" +
" And Fullname Like" + " '%" + TxLastname.Text + "%'"
Dim dir3 As SqlDataReader = cmd3.ExecuteReader()
If dir3.HasRows Then
Dim dtClient As New DataTable
dtClient.Load(dir3)
dtOutput.DataSource = dtClient
End If
dir3.Close()
Conn2.Close()
End Sub
End Class
I have verified that my domain/username + password works for database 2. I am stumped as to why Visual Studio thinks my user is '\azahir' instead of the specified '\axzahir'. Any thoughts on how this can be fixed?
Thank you,
Asif

That's not how integrated security works. When using integrated security, there is no way to specify a specific username or the password. Instead, you get the user authorization for whatever user account runs your program. The entire connection string looks like this, with no specific user information:
Data Source = <SERVER>;Initial Catalog=<DATABASE>;Integrated Security=SSPI;
If you want to specify a username and password, you must use SQL authentication. If you want to access the database as a specific domain account, you use integrated security, but you have to run your app as that user. There is no way to specify Active Directory credentials in a connection string and get that user's database access.
While I'm here, let me show you a better pattern for your database connection. (One that's not crazy vulnerable to sql injection! and will remember to close the connection even if an exception is thrown.)
Assuming a valid connection string:
Private ConnString As String = "connection string here"
Private Sub btSearch_Click(sender As Object, e As EventArgs) Handles btSearch.Click
Dim SQL As String = _
"SELECT firstname, lastname " &
"FROM systemuserbase " &
"WHERE firstname like '%' + #FirstName + '%' AND lastname Like '%' + #LastName + '%';"
Using Conn As New SqlConnection(ConnString), _
cmd As New SqlCommand(SQL, Conn)
'Use actual database column types and lengths here
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 20).Value = TxFirstName.Text
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 20).Value = TxLastName.Text
Conn.Open()
Using dir As SqlDataReader = cmd2.ExecuteReader()
dtOutput.DataSource = dir
dir.Close()
End Using
End Using
End Sub
Private Sub btnArgus_Click(sender As Object, e As EventArgs) Handles btnArgus.Click
Dim SQL As String = _
"SELECT userID, Fullname " &
"FROM Users " &
"WHERE FullName like '%' + #FirstName + '%' AND Fullname Like '%' + #Lastname + '%';"
'Note I can use the same variable names.
' These are scoped to the method, not the class.
' Different scope, different variables, even though the names are the same
Using Conn AS New SqlConnection(ConnString), _
cmd As New SqlCommand(SQL, Conn)
'Use actual database column types and lengths here
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 20).Value = TxFirstName.Text
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 20).Value = TxLastName.Text
Conn.Open()
Using dir As SqlDataReader = cmd.ExecuteReader()
dtOutput.DataSource = dir
dir.Close()
End Using
End Using
End Sub

Related

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 make log in code in 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

sql command query for log in asp.net

Hello i been looking around and i cant seem to find how to make a safe sql command ( vs injections ) for checking log in details from the database , i found something like this code which seem to be the thing i need but i cant seem to understand how to actully check if the user exists.
This code happens on LogIn Button click , and i am suppose to redirect the user to another page + save some of the valuse from the row ( like userId , companyId and few others ) into sessions for later use . I just not so sure how .
Protected Sub enterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Dim query As String = String.Format("select userName, userPassword, companyId from " & "[users] where userName like '%+#userName+%', userBox.Text)
Using con As New SqlConnection(connectionString)
'
' Open the SqlConnection.
'
con.Open()
'
' The following code uses an SqlCommand based on the SqlConnection.
'
Using da As New SqlDataAdapter()
Using command As New SqlCommand(query, con)
'pass the parameter
command.Parameters.Add(New SqlParameter("#userName", userBox.Text))
command.Parameters.Add(New SqlParameter("#userPassword", passwordInput.Text))
command.Parameters.Add(New SqlParameter("#companyId", companyIdBox.Text))
Dim ds As New DataSet()
da.SelectCommand = command
da.Fill(ds, "test")
End Using
End Using
End Using
Change your query string to
Dim query As String = "select userName, userPassword, companyId " & _
"from [users] " & _
"where userName like #userName " & _
"userPassword = #userPassword " & _
"companyID = #companyID"
and then in the section where you add the parameters
command.Parameters.Add(New SqlParameter("#userName", "%" & userBox.Text "%"))
The trick is to write the query text as clean as possible and add the wildcard required by the like directly in the value passed to the SqlParameter constructor
I suggest also to use a different way to build your Parameters collection
command.Parameters.Add(New SqlParameter With
{
.ParameterName = "#userName",
.Value = "%" & userBox.Text "%",
.SqlDbType = SqlDbType.NVarChar
})
This is more verbose but avoids the confusion between the two overloads of the Add method the one that accepts an SqlDbType and the one that accepts an object as second parameter.
Then if you want to know if a user with that name, password an company has been found just loop at the count of rows present in the first table of the DataSet
If ds.Tables(0).Rows.Count > 0 then
... you have your user .....
End if
However a better query would be
Dim query As String = "IF EXISTS(select 1 from [users] " & _
"where userName like #userName " & _
"userPassword = #userPassword " & _
"companyID = #companyID) " & _
"SELECT 1 ELSE SELECT 0"
and instead of the SqlDataAdapter and DataSet you write simply
Using con As New SqlConnection(connectionString)
Using command As New SqlCommand(query, con)
con.Open()
command.Parameters.Add(New SqlParameter("#userName", userBox.Text))
command.Parameters.Add(New SqlParameter("#userPassword", passwordInput.Text))
command.Parameters.Add(New SqlParameter("#companyId", companyIdBox.Text))
Dim userExists = Convert.ToInt32(command.ExecuteScalar())
if userExists = 1 Then
Session["UserValidated"] = "Yes"
else
Session["UserValidated"] = "No"
End If
End Using
End Using

Error when trying to run login form vb.net

Here's my code...
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con = New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
con.Open()
Dim dr As SqlClient.SqlDataReader
Dim cmd As New SqlClient.SqlCommand("SELECT * FROM [user] where userid= " + txtuser.Text + " AND password= " + txtpass.Text + "", con)
dr = cmd.ExecuteReader
If dr.Read Then
MsgBox("Succesfully loggedin")
End If
con.Close()
End Sub
End Class
when I try to run the programs, it shows this error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid column name 'admin'.
Invalid column name 'admin'.
'admin' is on the value stored in the userid column under 'user' table under 'Vehicle' database..I'm creating a small Win application for our office but I was stacked with this one, this is also part of my practice.
thanks for the help guys..
I'll start with a warning: use SQLParameter to avoid SQL injection!
In this case the problem is that you pass a SELECT like this:
SELECT * FROM [user] where userid = admin
So SQL Server thinks admin is a column name.
The correct syntax is:
SELECT * FROM [user] where userid = 'admin'
you need to escape your text. This is what your DB sees:
SELECT * FROM [user] where userid= admin AND password= somepass
This is what you want it to see:
SELECT * FROM [user] where userid= 'admin' AND password = 'somepass'
To fix this, re-write your code like:
"SELECT * FROM [user] where userid= '" + txtuser.Text + "' AND password= '" + txtpass.Text + "'"
(note the single quotes).
You should also worry about what would happen if the userid or password included a single quote, you can fix this by doing Replace(txtuser.Text,"'","''")
You need to encase the contents txtUser.Text and txtPass.Text in apostrophes, to escape them. You're currently trying to match a column called admin.
For example;
Dim cmd As New SqlClient.SqlCommand("SELECT * FROM [user] where userid='" & txtuser.Text & "' AND password='" & txtpass.Text & "';", con)
dr = cmd.ExecuteReader
What you really should be doing is something like this;
Dim cmd As New SqlClient.SqlCommand("SELECT * FROM [user] WHERE userid=#U AND password=#P;", con)
cmd.Parameters.Add("#U", SqlDBType.NVarChar).Value = txtUser.Text.Trim
cmd.Parameters.Add("#P", SqlDBType.NVarChar).Value = txtPass.Text.Trim
dr = cmd.ExecuteReader
I find this simplifies things quite a bit.

Can't retrieve data with dot symbol from sql database

In my project (vb.net) I store the ip address of a website in a table with column of type nvarchar. But I can't retrieve it from the table. I wonder if its a problem with "dot" symbol. Please help.
This is the command that I use
query = "select *from restricted_sites where site_address='" + webip + "'"
webip is the ip address of web site.
Imports System.Data.SqlClient
Imports System.Net
Public Class restrict
Private Sub clear_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clear_button.Click
site_TextBox1.Text = ""
addr_TextBox1.Text = ""
End Sub
Private Sub submit_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submit_button.Click
Dim connectionstr As String
Dim query As String
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim webip As String
Dim hostname As IPHostEntry = Dns.GetHostByName(addr_TextBox1.Text)
Dim ip As IPAddress() = hostname.AddressList
Try
webip = ip(0).ToString
connectionstr = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\URLTrack.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
conn = New SqlConnection(connectionstr)
conn.Open()
query = "insert into restricted_sites values('" + site_TextBox1.Text + "','" + webip + "')"
cmd = New SqlCommand(query, conn)
cmd.ExecuteNonQuery()
MsgBox("Website added for restriction", MsgBoxStyle.Information)
conn.Close()
Catch ex As SqlException
End Try
End Sub
End Class
Private Sub Combox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Combox1.KeyPress
If e.KeyChar = Convert.ToChar(Keys.Enter) Then
Dim connectionstr As String
Dim query As String
Dim cmd As SqlCommand
Dim reader As SqlDataReader
Dim conn As SqlConnection
Dim url As String = ""
Dim webip As String
Dim hostname As IPHostEntry = Dns.GetHostByName(Combox1.Text)
Dim ip As IPAddress() = hostname.AddressList
webip = ip(0).ToString
connectionstr = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\URLTrack.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
conn = New SqlConnection(connectionstr)
conn.Open()
query = "select * from restricted_sites where site_address='" + webip + "'"
cmd = New SqlCommand(query, conn)
reader = cmd.ExecuteReader
While (reader.Read())
url = reader(2)
End While
reader.Close()
MsgBox(url, MsgBoxStyle.Information)
If webip <> url Then
AxWebBrowser1.Navigate(Combox1.Text)
Combox1.Text = AxWebBrowser1.LocationURL
Else
MsgBox("This Web Page is Restricted.Contact the ADMIN for Further Info", MsgBoxStyle.Critical)
End If
End If
If e.KeyChar = Convert.ToChar(Keys.Escape) Then
AxWebBrowser1.Stop()
End If
End Sub
The second code is the comparing part.
query = "select * from restricted_sites where site_address='" + webip + "'"
this code is the problem.
This is my code for restricting web sites through matching with ip address stored in database,when the url is being navigated.
You have a syntax error on your query. you forgot the space between * and from.
select *from restricted_sites
^ here
it should be
select * from restricted_sites
side note, since you are using VBNet, please do parameterized your query by using adonet command and parameters as your current query is susceptible with SQL Injection.
You need to put a space between the * and the from like so:
query = "select * from restricted_sites where site_address='" + webip + "'"
Dot symbols (presumably you meant in the webip) won't be a problem because it is in a String
If all you are doing is checking if an IP address string is in the database, you only need to count the number of occurences of that string:
query = "SELECT COUNT(*) FROM restricted_sites WHERE site_address = #WebIp;"
cmd = New SqlCommand(query, conn)
' assumes the ip address column is 15 chars '
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#WebIp", _
.SqlDbType = SqlDbType.NVarChar, _
.Size = 15, _
.Value = webip})
conn.Open()
Dim nFound = CInt(cmd.ExecuteScalar)
conn.Close()
If nFound = 0 Then
' site is not in restricted list
End If
Also, you should not use SELECT * in code other than for testing - use the column names instead of * and only retrieve what you need.