Wrong line number on stacktrace exception - asp.net

I've got some code which errors and I'm using the stacktrace to find out what the line number is but it seems to be giving me the wrong number
Here's my code
Try
Dim query As String = "Select * from table"
Dim ds As DataSet = data.db(query)
Catch e As Exception
Dim st As New StackTrace(True) 'This is the line number it gives me'
Dim sf As StackFrame = st.GetFrame(0)
Response.Write(" Method: " & sf.GetMethod().Name)
Response.Write(" File: " & sf.GetFileName())
Response.Write(" Line Number: " & sf.GetFileLineNumber().ToString())
End Try
It seems to give me the line number of where the StackTrace is starting rather than the line number of what is causing the exception
Any ideas?

If you particularly want a StackTrace object, and don't just want the string from e.StackTrace, then change your constructor call to;
Dim st As New StackTrace(e, True)
"st" will now be initialised with the source details as you're expecting.
See http://msdn.microsoft.com/en-us/library/dsay49kt.aspx for details.

Why don't you use the info from the Exception object?
Catch e As Exception
Response.Write(e.StackTrace)
Response.Write(" Method: " & e.TargetSite)
Response.Write(" File: " & e.Source)
End Try

The StackTrace(true) constructor creates a new stacktrace for this point in the code.
Use the .Stacktrace property of the exception.

Surely you want the StackTrace of the Exception? You are creating a new stacktrace at the line of code in the exception handler.
You want e.StackTrace instead.

Related

Asp.net Server.GetLastError don't have line number

when i look in the stack trace of a try/catch, i have the row of my code that throw exception.
if i don't manage try/catch to redirect to a custom page and get my last exception with Server.GetLastError i have a different stack trace.
for example:
with try catch i have my line reference
without try catch, on my custom page nothing
i tried also
Dim ex As Exception = Server.GetLastError.GetBaseException
Dim trace As New Diagnostics.StackTrace(ex, True)
as suggested in an other post, but is not working. i wrong something?
this is how i solved:
Dim ex As Exception = Server.GetLastError()
Dim StackTraces As New Diagnostics.StackTrace(ex.InnerException, True)
Dim StackFrame = Nothing
For Each StackFrame In StackTraces.GetFrames()
If (StackFrame.GetFileColumnNumber() > 0) Then
Exit For
End If
Next

Exception info from a ThreadAbortedException

I get an exception at response.redirect() and Visual Studio does not help me with appropriate info. I only get this for ex:expression cannot be evaluated, message:subprocess annulled and _HResult:-2146233040. I don't get a helplink or anything else.
Try
Dim unidadD As String = Request.QueryString("unity")
Dim categD As String = Request.QueryString("category")
Dim resulD As String = Request.QueryString("result")
Dim anioD As String = Request.QueryString("year")
Dim cicloD As String = Request.QueryString("cicle")
Response.Redirect("~/Evaluacion/Detalle_Resultados.aspx?op=1" & "&unity=" & unidadD & "&category=" & categD & "&result=" & resulD & "&cicle=" & cicloD & "&year=" & anioD)
Catch exa As System.Threading.ThreadAbortException
Dim link As String = exa.HelpLink
End Try
Response.Redirect is expected to throw a ThreadAbortedException. Simply move the Response.Redirect out of the try/catch block.
Another option is to use:
Response.Redirect(url, False)
This will redirect without ending the current request. You can later call Application.CompleteRequest.
Another alternative would be
Try
Response.Redirect(url)
Catch tax as ThreadAbortedException
' Do nothing, as this is an expected exception
' No need to rethrow, as this exception is automatically re-thrown
End Try
This is expected behaviour, as a workaround just pass false in Response.Redirect e.g.
Response.Redirect("...", false);
Or as already suggested, get rid of the Try...Catch - not quite sure what you expect to do with a ThreadAbortException anyway...

How to properly report / handle classic asp page errors and database errors

I have been trying to create an error handling path for our classic asp website. I have been searching for information for 3hrs now and have not found much even here on stack overflow. So if you can point me towards a duplicate great ... I couldn't find anything although it must exist.
My plan is the following ...
Have proper error handling in the stored procedures. Any errors that occur get inserted into an error table and are also raised back up to the application.
Have "On error resume next" set on the page. Then check the connection.errors collection for errors. As well as Server.GetLastError() property.
If there are any redirect to a page to to display safe error information and insert another record into another database table to tie the page name where the error occurred to the already existing database error in the database table mentioned above for later debugging purposes.
I have created the following page to to begin testing this out. However it is not working.
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
on error resume next
cmd.CommandText = "spReturnDBException"
cmd.CommandTimeout = 30 ' 2 minutes
cmd.Execute
dim objErr
set objErr = Server.GetLastError()
if objError.ASPCode <> 0 then
response.write("ASPCode=" & objErr.ASPCode)
response.write("")
response.write("ASPDescription=" & objErr.ASPDescription)
response.write("")
response.write("Category=" & objErr.Category)
response.write("")
response.write("Column=" & objErr.Column)
response.write("")
response.write("Description=" & objErr.Description)
response.write("")
response.write("File=" & objErr.File)
response.write("")
response.write("Line=" & objErr.Line)
response.write("")
response.write("Number=" & objErr.Number)
response.write("")
response.write("Source=" & objErr.Source)
else
response.write("There's nothing wrong.")
end if
Dim objErr2
for each objErr2 in objConn.Errors
response.write("<p>")
response.write("Description: ")
response.write(objErr2.Description & "<br />")
response.write("Help context: ")
response.write(objErr2.HelpContext & "<br />")
response.write("Help file: ")
response.write(objErr2.HelpFile & "<br />")
response.write("Native error: ")
response.write(objErr2.NativeError & "<br />")
response.write("Error number: ")
response.write(objErr2.Number & "<br />")
response.write("Error source: ")
response.write(objErr2.Source & "<br />")
response.write("SQL state: ")
response.write(objErr2.SQLState & "<br />")
response.write("</p>")
next
Free(cmd)
Free(con)
In the stored procedure I simply RAISERROR( N'Lets throw an error because I want to!', 17, 0 );
The output I get every time is as follows ...
ASPCode=ASPDescription=Category=Column=-1Description=File=Line=0Number=0Source=
Description: Help context: Help file: Native error: Error number: Error source: SQL state:
Why am I not getting any error information on the conn.Errors loop?
Resolved.
I was using a different connection object for the loop that loops through the connection.Errors ... copy paste error.
However on a side note ... I found it extremely difficult to find information on how to even do what I've so far.
here's some additional resources:
some general topics:
http://social.msdn.microsoft.com/search/en-US?query=Server.GetLastError%28%29&refinement=89
a specific example:
http://support.microsoft.com/kb/224070

checking if row was inserted

I am trying to check whether a row is getting inserted into my database. It is throwing an error even when it does insert (it's a database issue that will get resolved later when I get a newer version of Microsoft Access), so I can't check whether the insert is successful based on whether there's an error or not. I think I need to check the AffectedRows of something, but I'm not sure what. I've been looking for info on how to do this but I can't figure out how to make it work for my exact situation. Here's a general idea of what my code looks like:
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
'code for collecting data...
'Define Connection
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource1.ConnectionString
myConn.Open()
'Insert command
Dim myIns1 As New OleDbCommand("INSERT INTO tableCourse 'long insert command here...
'Execute command and handle errors
Try
myIns1.ExecuteNonQuery()
Catch myException5 As Exception
End Try
'Close connection
myConn.Close()
-UPDATE-
I tried it like this:
'Execute command, handle errors, and check if row was inserted
Dim numInserted As Integer = 0
Try
numInserted = myIns1.ExecuteNonQuery()
Catch myException As Exception
Finally
If numInserted = 0 Then
Label1.Text = "Sorry, an error occured."
Else
Label1.Text = "Thank you! Your new course approval request has been submitted."
End If
End Try
But the numInserted is coming out as 0 every time even though the insert is successful. It may have to do with the fact that myIns1.ExecuteNonQuery() throws an error even though the insert is successful.
-EDIT- I discovered that the "duplicate values" error is because it is somehow attempting to insert the record twice. I have no idea why it's doing that though.
The ExecuteNonQuery function returns the affected number of rows...
Dim numInserted as Integer = myIns1.ExecuteNonQuery()
If numInserted = 0 Then
' no rows were inserted...throw exception?
End If
The symptoms you are describing (known no duplicates, but inserts throw duplicate errors) sound like your Access database needs Compacting and Repairing.
You should do this on a regular basis. (Always backup up first).

ASP.NET Replacing Line Break with HTML br not working

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)

Resources