I have a SQL string in Asp.net web page, with vb code behind.
It was working fine before but for unknown reason I start now getting the following error:
Error: Sys.WebForms.PageRequestManagerServerErrorException: Operator '&' is not defined for string "UPDATE db.usersdata SET `SH" and type 'TextBox'.
UPDATE: SH is a string ('SAVE' or 'HIDE')
UPDATE: I am using MySQL database on the background.
Protected Sub savehide_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim SQLstring As String = ""
Dim SH As String
SH = saveorhide.SelectedItem.Value
' the following line is where the error occurs
SQLstring = "UPDATE `db`.`usersdata` SET `SH`='" & SH & "' WHERE `PIC` = '" & Session("UserId") & "'"
Session("SH") = SH
SQLNonQuery_mysql(SQLstring)
CLEARALL()
displaydata()
End Sub
I have spent hours but I cannot find the reason for this, specially when before it was working fine.
This code runs when a dropdownlist field is changed.
The thing it also started to happen to other dropdownlist and SQL string creation code...So it is failing in various VB places now (as I said before it wasn't)
I am wondering if there is a bug or some weird reason why this error is coming out now (and not before) and what would be the solution.
According to the error message, either SH is a TextBox or Session("UserId") is a TextBox.
Since you already showed the declaration of SH, the only suspect remaining is the Session("UserId").
Can you show how you are setting the Session("UserId") value?
My best guess is that you are doing this:
Session("UserId") = TextBox1
you should change it to:
Session("UserId") = TextBox1.Text
(replace TextBox1 with name of your TextBox)
Related
I have a VB.Net project in visual studio 2010 intended to let a user upload a video and then stick it in a DB. The file is called "Media/Test.aspx.vb".
When I tried to run the code to debug, tons of errors were generated for a file called App_Web_nkhy2w0y.0.vb
I couldn't locate this file anywhere, and I certainly didn't write it, so I double clicked on the error and it opened a file with about 350 lines of (apparently) auto-generated code, and I have no clue what I did to cause it to do this. Nor do I have any idea how to fix it.
I'll admit I'm new to VB.Net, but I've never seen anything like this online so I'm in the dark.
My original code is below for the code-behind file that handles nothing more than a fileupload control, button, and label in the actual page.
Imports System.IO
Imports System.Data.SqlClient
Imports System.Data
Partial Class Media_Test
Inherits System.Web.UI.UserControl
Protected Sub TryMe_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TryMe.Click
Dim connection As SqlConnection
'check the file
Dim buffer As Byte()
If testFile.HasFile AndAlso testFile.PostedFile IsNot Nothing AndAlso testFile.PostedFile.FileName <> "" Then
Dim file As HttpPostedFile = testFile.PostedFile
'retrieve the HttpPostedFile object
buffer = New Byte(file.ContentLength - 1) {}
Dim bytesReaded As Integer = file.InputStream.Read(buffer, 0, testFile.PostedFile.ContentLength)
'the HttpPostedFile has InputStream porperty (using System.IO;)
'which can read the stream to the buffer object,
'the first parameter is the array of bytes to store in,
'the second parameter is the zero index (of specific byte)
'where to start storing in the buffer,
'the third parameter is the number of bytes
'you want to read (do u care about this?)
If bytesReaded > 0 Then
Try
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection = New SqlConnection(connectionString)
Dim cmd As New SqlCommand("INSERT INTO Videos (Video, Video_Name, Video_Size)" & " VALUES (#video, #videoName, #videoSize)", connection)
cmd.Parameters.Add("#video", SqlDbType.VarBinary, buffer.Length).Value = buffer
cmd.Parameters.Add("#videoName", SqlDbType.VarChar).Value = testFile.FileName
cmd.Parameters.Add("#videoSize", SqlDbType.BigInt).Value = file.ContentLength
Using connection
connection.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
Label1.Text = "uploaded, " & i.ToString() & " rows affected"
End Using
Catch ex As Exception
Label1.Text = ex.Message.ToString()
End Try
End If
Else
Label1.Text = "Choose a valid video file"
End If
End Sub
End Class
And the top of the generated page is:
#ExternalChecksum("C:\Users\handcm\Documents\Visual Studio 2010\WebSites\APPS\Media\Test.aspx","{406ea660-64cf-4c82-b6f0-42d48172a799}","F31F20662F14B4894B6FBF58215628CB")
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.296
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
I can post the entire file if need be, but could someone shine some light on what's going on here? I have no clue how to debug a file I didn't write or have never seen.
Edit 2: I checked the "'InitializeCulture' is not a member of 'ASP.media_test_aspx" error and it usually is a discrepancy between the class being inherited on the aspx page not being the correct as in the aspx.vb file. However, in this case, there isn't a discrepancy as it's the correct file.
Edit: Some of the error messages I am getting:
Error 4 'GetWrappedFileDependencies' is not a member of 'ASP.media_test_aspx'. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 103
Error 2 Class 'media_test_aspx' must implement 'ReadOnly Property IsReusable As Boolean' for interface 'System.Web.IHttpHandler'. Implementing property must have matching 'ReadOnly' or 'WriteOnly' specifiers. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 84
Error 10 'ProcessRequest' is not a member of 'Media_Test'. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 342
Error 1 'InitializeCulture' is not a member of 'ASP.media_test_aspx'. C:\Users\handcm\Documents\Visual Studio 2010\WebSites\APPS\Media\Test.aspx 1
I don't even know what the last one is referring to, as there is definitely not an "Initialize Culture" on the page.
I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function
I'm trying to update a record from an Ms-Access table with VB.NET and ASP.NET. I'm getting 2 errors:
On the web page that's opened I'm getting Thread was being aborted
Web Developer 2010 gives me an error says there's an error in the
UPDATE statement
This is the code so far:
Imports System.Data.OleDb
Partial Class ChangePassword
Inherits System.Web.UI.Page
Protected Sub btnChange_Click(sender As Object, e As System.EventArgs) Handles btnChange.Click
Dim tUserID As String = Session("UserID")
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\WebSite3\db.mdb;")
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where UserID=?", conn)
Dim cmd2 = New OleDbCommand("UPDATE USER SET [Password] = '" + txtConfPass.Text + "' where UserID = '" + tUserID + "'", conn)
cmd.Parameters.AddWithValue("#UserID", tUserID)
Dim read As OleDbDataReader = cmd.ExecuteReader()
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
lblUser.Text = tUserID.ToString
lblUser.Visible = True
If read.HasRows Then
While read.Read()
If txtOldPass.Text = read.Item("Password").ToString Then
cmd2.ExecuteNonQuery()
lblPass.Visible = True
End If
End While
Else
lblPass.Text = "Invalid Password."
lblPass.Visible = True
End If
conn.Close()
lblPass.Text = tUserID.ToString
lblPass.Visible = True
Any help would be appreciated.
Thanks !
First, your cmd2 fails because USER is a reserved word. Enclose in
square brackets as you already do in the first OleDbCommand.
Second, to execute a statement like UPDATE, INSERT, DELETE you call
cmd2.ExecuteNonQuery not ExecuteReader. Don't really needed that call
after the first for cmd.
Third, in the first OleDbCommand (cmd) you use a parameter for
UserID, why in the second one you revert to string concatenation for
user and password? This opens the door to any kind of Sql Injection
Attack.
Fourth, the Using statement assure that every Disposable object
used in your code will be CLOSED thus freeing the memory used by
this commands ALSO IN CASE OF EXCEPTIONS. An example of Using
statement here
(1)
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
and then
(2)
cmd2.ExecuteNonQuery()
Remove (1) - ExecuteNonQuery should do the update.
USER is a keyword in Access, add brackets the same way you have added in the Select statement. Next time, you are faced with a similar problem, print out the statement as Access would see it and try executing it on the database directly - that will point out the errors accurately.
Please use place holders for the update statement similar to the select statement.
I am having some trouble getting the correct syntax for a bit if code. I am using vb to insert data into a db and outputting the data as XML, here is the code
<WebMethod()> _
Public Function addTrack(ByVal tTitle As String, ByVal tAlbum As String, ByVal tGenre As String) As String
Dim conn As New SqlConnection("Data Source=MARTIN-LAPTOP\SQLEXPRESS;Initial Catalog=mp3_playlists;Integrated Security=True")
Dim sql As String = "INSERT INTO Tracks (trackTitle, trackAlbum, trackGenre) VALUES ('" & tTitle & "', '" & tAlbum & "', '" & tGenre & "') FOR XML AUTO, ELEMENTS"
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim track As String = cmd.ExecuteScalar()
conn.Close()
Return track
End Function
The code is for a ASP.NET web service, when I click invoke on the website i get the error Incorrect syntax near the keyword 'FOR'. If I remove FOR XML AUTO, ELEMENTS everything works find, db updates but I dont get the data to output as XML. I think the issue is with
the brackets required for the insert values because this issue does not occur if the SQL statement is a SELECT statement which has no brackets but i just cant figure out the correct syntax, thanks for your help
FOR XML AUTO is only used for SELECT statements. So, the issue is not your insert statement, it is your select statement, whereever that is.
Hi
I am trying to submit some information into a database using an ASP.NET multiline textbox.
I have the following code:
Dim noteContent As String = Replace(txtNoteContent.InnerText.ToString(), vbCrLf, "<br />")
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)
The addNote's function code is:
Public Shared Sub addNote(ByVal JobID As Integer, ByVal NoteFrom As Integer, ByVal NoteTo As Object, ByVal NoteContent As String)
Dim newNote As New Job_Note
newNote.Date = DateTime.Now()
newNote.JobID = JobID
newNote.NoteByStaffID = NoteFrom
If Not NoteTo = Nothing Then
newNote.NoteToStaffID = CInt(NoteTo)
End If
newNote.NoteContent = NoteContent
Try
db.Job_Notes.InsertOnSubmit(newNote)
db.SubmitChanges()
Catch ex As Exception
End Try
End Sub
When it submit's the compiler does not seem to detect that line breaks have been entered into the textbox. I have debugged and stepped through the code, and sure enough, it just ignores the line breaks. If I try and replace another character instead of a line break, it works fine.
It doesn't seem to be anything to do with my function, the LINQ insert or anything like that, it simply just doesn't detect the line breaks. I have tried VbCr, and also chr(13) but they do not work either.
Can someone help me? I have been trying ad searching for over an hour trying to sort this.
Thanks
When you do your replace, you should check for VbCrLf (Windows Line Break), VbLf (Unix Line Break) and VbCr (Mac Line Break). If memory serves correct, the standard newline in a HTML textarea element is "\n" (aka VbLf), so you might just get away with replacing VbCrLf with VbLf in your code, but personally I always check for them all just to be safe.
Example
Dim htmlBreakElement As String = "<br />"
Dim noteContent As String = txtNoteContent.Text _
.Replace(vbCrLf, htmlBreakElement) _
.Replace(vbLf, htmlBreakElement) _
.Replace(vbCr, htmlBreakElement)
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)