Getting value for webpage - rewriting code so no sql injection - vb.net

I'm trying to rewrite my code to prevent vulnerability to SQL Injection. I see code for inserting or updating tables, but not for just getting a value. Here is the code I have that is vulnerable:
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
cmde.CommandText = "SELECT EmployeeID FROM tblEmployees where login = '" & vname & "'"
cmde.CommandType = CommandType.Text
cmde.Connection = sqlConnection
sqlConnection.Open()
'employeeid
rve = cmde.ExecuteScalar()
sqlConnection.Close()
I started rewriting the code and this is what I have so far:
sql1 = "Select EmployeeID from tblEmployees where login = #loginname"
cmde = new sqlcommand(sql1)
This is where I'm stuck:
cmde.parameters.????("#loginname", vname)
cmde.ExecuteReader()
I'm not adding or updating or inserting - I just want the value to appear on my webpage. What is the code for this? And is the rest of the code correct? Thanks in advance!
****Continued...
After help, I came up with this code but I'm getting an error - ExecuteReader: Connection property has not been initialized. I'm confused. Here's the code:
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
Dim sqlConnection As New SqlConnection("Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI")
Dim sqlemp As String
Dim cmde As New SqlCommand
Dim rve As Object
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
sqlConnection.Open()
sqlemp = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
cmde = New SqlCommand(sqlemp)
cmde.Parameters.AddWithValue("#loginname", vname)
rve = cmde.ExecuteReader()
sqlConnection.Close()

Related

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

getting error : Conversion failed when converting character string to smalldatetime data type. when querying again DB

I am getting an error when trying to insert into a table. As the error shows I know is because of the smalldatetime field. But I have tried several different things From other posts and its not working. Plus when I'm reading from the same table I use the same format for smalldatetime and it works. code show below. Any help would be really appreciated.
Code when trying to Insert a new row
.vb.net
Dim conn As String = "Your Connection String"
'Dim querystring As String = "INSERT INTO 'Where SupID='" & supervisor & "' Order By EmpNum"
Dim querystring As String = "INSERT INTO [AttendanceDB].[dbo].[tblAbsences]([fldEmployeeID] " & _
",[fldAbsentDate],[fldAbsentCode],[fldRuleViolationWarningType],[fldRuleViolationIssueDate] " & _
",[fldLOAEndDate]) VALUES('23','11-06-2014','NA','NULL','NULL','NULL')"
Using connection As New SqlConnection(conn)
Dim command As New SqlCommand(querystring, connection)
connection.Open()
Try
command.ExecuteNonQuery()
Catch ex As Exception
connection.Close()
End Try
End Using
I have also tried this code in SQL Management Studio
INSERT INTO [AttendanceDB].[dbo].[tblAbsences]([fldEmployeeID],
[fldAbsentDate],[fldAbsentCode],[fldRuleViolationWarningType],
[fldRuleViolationIssueDate],[fldLOAEndDate])
VALUES ('23','11-06-2014','NA','NULL','NULL','NULL')
This is the code that works when im reading from the same table when databinding to ViewGrid
Dim startdate As String = txtcalendarstart.Text
Dim enddate As String = txtcalendarstop.Text
startdate = startdate.Replace("/", "-")
enddate = enddate.Replace("/", "-")
Dim SqlDataSource2 As SqlDataSource = New SqlDataSource()
SqlDataSource2.ID = "SqlDataSource2"
Page.Controls.Add(SqlDataSource2)
SqlDataSource2.ConnectionString = "Data Source=SVR-SQLDB2;Initial Catalog=AttendanceDB;Integrated Security=True"
SqlDataSource2.SelectCommand = "SELECT * FROM [tblAbsences] WHERE [fldAbsentDate] BETWEEN '7-03-2014' AND '8-21-2014' ORDER BY [fldEmployeeID]"
GridView1.DataSource = SqlDataSource2
GridView1.DataBind()

Sql in Visual Basic returning nothing while same query in Access returns right value

My code:
strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=PIZZA.accdb"
strSql = "SELECT INGREDIENTNR AS NR FROM INGREDIENTS WHERE DESCRIPTION = '" & ingredients(counter * 2) & "'"
objConnection = New OleDbConnection(strConnectionString)
objCommand = New OleDbCommand(strSql, objConnection)
objConnection.Open()
objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
Dim strIngNr As String = objDataReader("NR")
Dim strIngNr As String = objDataReader("NR") gives the error: No data exists for the row/column.
But the same query in Access does return 14, which is the right value and what I want to get. What am I doing wrong?
Another thing: counter is the right value, tested that already.
And another thing: DESCRIPTION is a String

Query SQL Database and Store Results in a Variable VB.Net

I am trying to query a SQL DB using a textbox field and retreive a column from the DB and store it in a variable so I can use it in other places within my site. My web form requires the user to enter a few items such as name and zip code.
My database has 3 columns; email address, zip code, and id. I need the input form to query the database and return the "email address" that matches the user's inputted "zip code"
I understand the SQL SELECT statement and the connection string is correct. My queries are working, I just can't seem to figure out how to get the returned "email address" to store in a variable. Any help would be appreciated.
Dim strconnection As String, strSQL As String, strZipCheck As String
Dim objconnection As OleDbConnection = Nothing
Dim objcmd As OleDbCommand = Nothing
Dim RREmail As String = Nothing
Dim zipQuery As String = zipCodeBox.Text
'connection string
strconnection = "provider=SQLOLEDB;Data Source=XXX.XXX.XXX.XXX;Initial Catalog=XXXXXXX;User ID=XXXX;Password=XXXXXXXX;"
objconnection = New OleDbConnection(strconnection)
objconnection.ConnectionString = strconnection
'opens connection to database
objconnection.Open()
strSQL = "SELECT [EMAIL ADDRESS] FROM ZIPCODEDATA WHERE [ZIP CODE] = #ZIP CODE "
objcmd = New OleDbCommand(strSQL, objconnection)
RREmail = CType(objcmd.ExecuteScalar(), String)
lblRREmail.Text = RREmail
objconnection.Close()
While the other comments do point out particular deficiencies with your syntax, I would like to address the question of storing a variable and take it a bit further. I generally do not use parameterized connections unless I am calling stored procedures and need an output parameter. Instead, here is what I often do to create a database connection and get my results.
First I create a public class called dbConn so I dont have to write it out a million times.
Imports System.Data.SqlClient
Public Class dbConn
Public Property strSQL As String
Private objConn As SqlClient.SqlConnection = _
New SqlClient.SqlConnection("Data Source=(local)\dev;Initial Catalog=testDataBase;Persist Security Info=False;Integrated Security = true;")
Public Function getDt() As DataTable
Dim Conn As New SqlClient.SqlConnection
Dim da As SqlClient.SqlDataAdapter
Dim dt As New DataTable
Try
objConn.Open()
da = New SqlClient.SqlDataAdapter(strSQL, objConn)
da.Fill(dt)
da = Nothing
objConn.Close()
objConn = Nothing
Catch ex As Exception
objConn.Close()
objConn = Nothing
End Try
Return dt
End Function
End Class
Then from another class (lets assume its form1) I call up that function to get a datatable returned to me. In this case I select TOP 1 to save your sanity in case by chance there is more than one email address per zip code.
Public sub getdata()
Dim strEmailAddress As String = Nothing
Dim dt As New DataTable
Dim da As New dbConn
da.strSQL = " select top 1 [email address] from [zipcode] " _
& " where [zip code] = '" & strZipCode & "'" _
& " order by [email address] asc"
dt = da.getDt
If dt.Rows.Count > 0 Then
If Not IsDBNull(dt.Rows(0)(0).ToString) Then
strEmailAddress = dt.Rows(0)(0).ToString
End If
End If
End Sub
From there you can use strEmailAddress within the sub after it is set, or you can move the string declaration outside of the sub as a public string declaration to use it elsewhere, or you can create other classes like an email class with a public property for strEmailAddress to pass it off to, etc.
I hope something in there helps you understand how to deal with your problem.

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)