Login and syntax error - asp.net

i try to do a login using asp.net 3.5 and sql server 2005 i create a dataset and do this code
but something is missing in the code here the code
Protected Sub btnlogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim LoginTable As New ClassSet.UsersDataTable
Dim LoginAdapter As New ClassSetTableAdapters.UsersTableAdapter
LoginAdapter.FillBylogin(LoginTable, txtuser.Text, txtpass.Text)
Dim dr As DataRow() = LoginTable.Select("Name= ' " & txtuser.Text & " 'Password= ' " & txtpass.Text & " '")
If dr.Length > 0 Then
Response.Redirect("MyClassifieds.aspx")
Else
Label1.Text = "Invalid UserName or Password"
End If
End Sub
it say that there is something missed after the password=' " & txtpass.Text in line 5 but i cant get what missed can any one help please

You are missing the "AND" statement between Name and Password
Dim dr As DataRow() = LoginTable.Select("Name= '" & txtuser.Text & "' AND Password= '" & txtpass.Text & "'")

You're missing an AND
Dim dr As DataRow() = LoginTable.Select("Name= '" & txtuser.Text & "' AND Password= '" & txtpass.Text & "'")
And I doubt you want spaces in there either.
But you also have a problem here, SQL Injection. You seriously do not want to build up dynamic SQL like this, you MUST parameterise all your queries.

Why are you running a select to verify the username and password in the login table when its just been filled using the username and password through the data adaptor? Surely you can just check its length then. Also, if there is any security in your login system the password won't be stored in plain text so the adaptors fill method should do some kind of one way hashing to find the correct password to return the the data table.

Related

No data exists for row/column

While executing the following code in ASP.NET with VB, I am getting the error "No data exists for the row/column."
Dim hdnuserid = e.CommandArgument
If e.CommandName = "additem" Then
' First, see if the product is already in the vendor_catalog table
Dim dr, dr2, username
dr = connection.returnsqlresult("SELECT * FROM vendor_users where vendor_id = '" & Request("vendor_id") & "' AND userid = '" & hdnuserid & "'")
If dr.hasrows() Then
dr.read()
Response.Write("<script type=""text/javascript"">alert(""User already assigned to this vendor."");</script>")
Else
dr2 = connection.returnsqlresult("SELECT * FROM users WHERE userid = '" & hdnuserid & "'")
Response.Write(hdnuserid)
If dr2.hasrows() Then
dr2.read()
username = dr("username")
connection.executesql("INSERT INTO vendor_users(userid, vendor_id, username) VALUES('" & hdnuserid & "','" & Request("vendor_id") & "','" & username & "')")
'ScriptManager.RegisterStartupScript(Me, GetType(Page), "itemsadded", "window.opener.__doPostBack('__Page', 'populate_usergrid');window.close();", True)
Else
Response.Write("<script type=""text/javascript"">alert(""User does not exist."");</script>")
End If
dr2.close()
End If
dr.close()
Else
End If
I have checked that the columns exist in my tables, and also checked the select * from users statement in SQL directly with a hard coded value and I see the result I expect. I'm not sure why I am getting this error. The error is being thrown on the username = dr("username") line.
Any assistance in this would be very helpful.
JV
I think you have a bit of a typo. Change
username = dr("username")
to
username = dr2("username")
Shouldnt the reader object be dr2 instead of dr? since dr doesnt have any rows, dr("username") wouldnt be accessible.
username = dr2("username")

insert data into ms access, using asp

im trying to insert a new row with new data to an ms access table, using asp page.
i have no background in asp, im an android developer, but those are my client specifications.
i know im doing something very wrong, but i dont know what...
can you please help me?
this is what i was trying to do:
<%
'define variables
dim conn, strsql, strMDBPath
Set conn = Server.CreateObject("ADODB.Connection")
'Connect to the database
strMDBpath = Server.MapPath("data.mdb")
conn.open "PROVIDER=MICROSOFT.JET.OLEDB.4.0;DATA SOURCE=" & strMDBPath
'On Error Resume Next
'write to the database
strSql = "INSERT INTO avi (id,first,last) VALUES ("4", '" yom "','" cobi "')"
conn.Execute(strSql)
'close database
conn.close
Set conn = nothing
%>
You're missing some ampersands.
strSql = "INSERT INTO avi (id,first,last) VALUES (4, '" & yom & "', '" & cobi & "')"

Classic ASP and MS Access Batch Update

I am using the following code to update an Access Database with Classic Asp:
<%# Language=VBScript %>
<% Option Explicit %>
<%
Response.Buffer = True
'First, we need to get the total number of items that could be updated
Dim iCount
iCount = Request("Count")
'We need to obtain each cost and ID
Dim strstudent, strcourse, strgrade, strcomments
'We will also need to build a SQL statement
Dim strSQL
Dim conn
set conn=server.CreateObject("ADODB.connection")
conn.ConnectionString="provider=Microsoft.jet.OLEDB.4.0;data source=C:\db\agsystem.mdb"
conn.Open
'Now, we want to loop through each form element
Dim iLoop
For iLoop = 0 to iCount
'student data
strstudent = Request(iLoop & ".Student")
'course data
strcourse = Request(iLoop & ".course")
'grade
if isNull(Request(iLoop & ".grade")) or Request(iLoop & ".grade")="" then
strgrade="null"
else
strgrade= Request(iLoop & ".grade")
end if
if isNull(Request(iLoop & ".comments")) or Request(iLoop & ".comments")="" then
strcomments=null
else
strcomments=Request(iLoop & ".comments")
end if
strSQL = "UPDATE testing SET semester2 = " & strgrade & ", commentss=" & "'" & strcomments & "'" & " WHERE newstudentid = " &"'"& strstudent&"'" & " and Courseid = " & "'"& strcourse & "'"
conn.Execute strSQL
Next
conn.Close
Set conn = Nothing
Response.Redirect "protected.asp"
%>
The problem is that when tested in the server it updates without any issues. But when access from a wireless network it won't update.
The target table to update has about 27,000 records
I need to know what I'm doing wrong or if there is another approach.
I found the error after carefully analyzing the situation.
Records in primary key that have spaces for example '2 OR 13' will not update. But records without spaces in primary key like '2CEN13' updates perfectly. I did not had time to solve it in my asp code, so i edited all records with spaces and that solve the problem.

How can I insert uploaded images into a database?

I want to insert uploaded image in root directory images folder and its path to image column in database.
I am using the following code. It inserts the path to images in the database column, but not the filename:
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
On Error Resume Next
If FileUpload1.HasFile Then
FileUpload1.SaveAs(IO.Path.Combine(Server.MapPath("images"), FileUpload1.FileName))
End If
'/// upload images
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Table3 (city, hotel, location, avialiability, room, price, image, category, from1, to1, price1, from2, to2, price2, from3, to3, price3, details) VALUES('" & Trim(DropDownList1.SelectedItem.Text) & "','" & Trim(DropDownList2.SelectedItem.Text) & "','" & Trim(TextBox5.Text) & "','" & Trim(TextBox6.Text) & "','" & Trim(DropDownList3.SelectedItem.Text) & "','" & Trim(TextBox7.Text) & "','" & "images/" & FileUpload1.FileName & "','" & Trim(TextBox17.Text) & "','" & Trim(TextBox8.Text) & "','" & Trim(TextBox9.Text) & "','" & Trim(TextBox10.Text) & "','" & Trim(TextBox11.Text) & "','" & Trim(TextBox12.Text) & "','" & Trim(TextBox13.Text) & "','" & Trim(TextBox14.Text) & "','" & Trim(TextBox15.Text) & "','" & Trim(TextBox16.Text) & "','" & (Editor1.Content) & "')"
cmd.ExecuteNonQuery()
con.Close()
End Sub
Try this:
Dim cmd As MySqlCommand = Nothing
Try
Dim query As String = "INSERT INTO (city, hotel, location) VALUES (#city, #hotel, #location)"
cmd = New MySqlCommand(query, connection)
cmd.Parameters.AddWithValue("#city", ddlCity.SelectedItem.Text)
cmd.Parameters.AddWithValue("#title", txtTitle.Text)
cmd.Parameters.AddWithValue("#location", txtLocation.Text)
cmd.ExecuteNonQuery()
Catch ex As Exception
Messagebox.Show("Error: " & ex.Message, MsgBoxStyle.Critical)
End Try
There are several important things to remember here:
Use Naming Conventions and Meaningful Names for your components. Such as txtCity for a TextBox that holds City data. You'll avoid confusion this way.
Use Parameterized Query when building your SQL CommandText next time and always avoid using string concatenation. This saves you lot of time and headache (also for us ;D). By doing so, you can easily change the values in the query. Also when you use string concatenation to build query strings, you'll encounter problems when your values have special characters but by using SQL Parameters this will be avoided.
It inserts the path to images in the database column, but not the filename.
You can try checking the source for the filename value by setting a breakpoint in that part of the code so you can follow and check it.
Hope this helps.
Try this:
''//cmd.ExecuteNonQuery() Comment out for now.
Response.Write(cmnd.CommandText)
Take a look at the commandText and if you can figure out the problem. If part of the Insert statement works its probably a simple SQL syntax error which you should be able to pick up visually. If you still can't see the problem post your code here.
Incidentally, building up your SQL command strings like this is only going to cause headaches. Try using a Parameterised Query in future - it'll go a long way to securing your application from real-world SQL Injection attacks and save hours of your life ;-)
HTH

How to Validate a textbox+dropdowns in vb for a asp.net form

Previous question which links onto this and has any addition code ref should I forget to link any, I have set it up to email me should someone submit this form and an error occur and right now should that occur for most integer or datetime fields if they fail to validate then it will show me which fields in the email failed and what was input into them.
Problem I'm having now is to validate the drop downs and the textboxs in a similar way to what I with integer and datetime fields so I can display those also in the email in case they error.
present integer and datetime validation
Catch ex As Exception
lblInformation.Text = ("<h4>Unable to save data in database</h4>" + vbNewLine + "The error was '" + ex.Message + "'" + vbNewLine + vbNewLine + vbNewLine + "The SQL Command which falied was:" + vbNewLine + "<strong>" + mySQL + "</strong>" + vbNewLine).Replace(vbNewLine, "<br />" + vbNewLine)
Dim dtb As DateTime
If Not DateTime.TryParse(DateOfBirth, dtb) Then
strEMessageBody.Append("<strong>Date Of Birth:</strong> " & DateOfBirthYear.SelectedItem.Value & "-" & DateOfBirthMonth.SelectedItem.Value & "-" & DateOfBirthDay.SelectedItem.Value & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
Dim iao As Integer
If Not Integer.TryParse(AnyOther, iao) Then
strEMessageBody.Append("<strong>Any Other:</strong> " & rblAnyOther.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
then below the final validation I have the Dim for the email setting but that I sorted out in the other question.
The problem is much earlier in the page I have
Sub Upload_Click(ByVal source As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
Dim Name As String
Which prevents me just using there names as shown above where I would instead call them something else but that doesn't work with strings so my main issue is having some bit of code to check if the strings are valid and for the dropdowns which would either work but always show the data in the email or would hiccup in the code,
Dim imd As Integer
If Not Integer.TryParse(dept, imd) Then
strEMessageBody.Append("<strong>Department:</strong> " & dept.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
below was how it had been setup to record the department
Department = dept.SelectedItem.Value
Department = Replace(Department, "'", "''")
Summary:- Need vb code to validate if strings and dropdowns are valid and the use of try/catch block is another possible solution but I wasn't able to figure out how to implement validation for that either.
Log your values into your database. Setup a logging table called "tblLog" or something else. Record the value of ex.Message or possibly even InnerException (if it exists).
Going hand in hand with Matt's answer, there is a tool that can help you with automatically logging errors to a DB.
It's called ELMAH.
EDIT
Here are 2 validations that you might want to use:
Dim s As String = "some user input in here"
If [String].IsNullOrEmpty(s) Then
' Watch out, string is null or it is an empty string
End If
Dim cb As New ComboBox()
If cb.SelectedItem Is Nothing Then
' Watch out, combo has no item selected
End If
NOTE ComboBox is a WinForm control in this example, but the idea is the same for the ASP.NET counterpart
Since everybodies given up trying to find a solution then I'm just gona close this topic with this post as the answer.

Resources