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

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

Related

Is it okay to catch exception and then cast it to a specific one?

With this code I get the response (error code and message) when an exception from type WebException gets catched.
Dim castExceptionToWebException As WebException = TryCast(ex, WebException)
using r As new StreamReader(castExceptionToWebException.Response.GetResponseStream())
Dim responseContent = r.ReadToEnd()
' DO SOMETHING WITH responseContent
End Using
My questions are: 1.) How could I get the response stream like I did but without casting down to WebException? Is it possible to access it through Exception class 2.) Is there any better work-around?
Replace this with the exceptions you need. Extend the Exception class if you need a custom one.
Try
'do stuff
Dim a = 1 / 0
Catch ex As DivideByZeroException
'handle it
Catch ex As Exception
'bug out
Throw ex
End Try

Try/Catch Failing Incorrectly

I'm trying to use Try/Catch to handle a potential failed connection to a database. There's a Response.Redirect command in the Catch section. Whenever the page loads it redirects as per the Catch section whether the code in the Try section fails or not.
If I comment out the Response.Redirect command in the Catch section the page loads just fine. Similarly, if I replace the Response.Redirect command with code to populate a control on the page with the supposed error being trapped the Try section succeeds. It's something about having Response.Redirect in the Catch section...
Private Sub Page_Load(Sender As Object, e As eventargs) Handles Me.Load
Try
Dim sqlcon As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("SarcoidsConnectionString").ConnectionString)
Dim cmd As New System.Data.SqlClient.SqlCommand("SELECT PortalEnabled FROM [tlkSettings]", sqlcon)
sqlcon.Open()
Dim dbReader As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader()
If dbReader.HasRows Then
While dbReader.Read()
If dbReader("PortalEnabled") = True Then
Response.Redirect("~/SubmitWizard.aspx")
Else
Response.Redirect("~/Maintenance.aspx")
End If
End While
End If
sqlcon.Close()
Catch ex As Exception 'Display Maintenance page if database cannot be connected to
Response.Redirect("~/Maintenance.aspx")
End Try
End Sub
Response.Redirect() without the second parameter of False will generate a ThreadAbortException because .End() is called on the Response object, so the following lines are the issue:
If dbReader("PortalEnabled") = True Then
Response.Redirect("~/SubmitWizard.aspx")
Else
Response.Redirect("~/Maintenance.aspx")
End If
Change it to this:
If dbReader("PortalEnabled") = True Then
Response.Redirect("~/SubmitWizard.aspx", False)
Else
Response.Redirect("~/Maintenance.aspx", False)
End If
The second parameter to Redirect() is the endResponse value, when setting it to False this tells the response to not call .End() and thus does not generate a ThreadAbortException.
Per MSDN documentation:
When you use this method in a page handler to terminate a request for one page and start a new request for another page, set endResponse to false and then call the CompleteRequest method. If you specify true for the endResponse parameter, this method calls the End method for the original request, which throws a ThreadAbortException exception when it completes. This exception has a detrimental effect on Web application performance, which is why passing false for the endResponse parameter is recommended. For more information, see the End method.
Read HttpResponse.Redirect Method documentation for more information.
I think the Problem is related to the other Response.Redirect Statements:
If dbReader("PortalEnabled") = True Then
Response.Redirect("~/SubmitWizard.aspx")
Else
Response.Redirect("~/Maintenance.aspx")
End If
Response.Redirect always throws a ThreadAbortException. This is caught in your exception handler as it catches any exception. Either you substitute the Reponse.Redirect calls or you add a handler the catches ThreadAbortExceptions:
Try
'...
Catch threadAbort As ThreadAbortException
Throw
Catch ex As Exception
'...
End Try
By the way: you should add some Using statements to close the connection and free other objects reliably.

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...

SqlTrackingQuery.GetWorkflows is not getting the correct workflows

I'm using ASP.NET 3.5 and WF 3.5.
The code I have is constantly giving me a FileNotFoundException. Even though I have created two workflow instances. It keeps trying to grab the first Workflow (and tells me the assembly is not there) and not the second workflow. This is my code:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("LocalWFConnection").ConnectionString
Dim trackingQuery As SqlTrackingQuery = New SqlTrackingQuery(connectionString)
Dim options As SqlTrackingQueryOptions = New SqlTrackingQueryOptions()
Dim workflws As IList(Of SqlTrackingWorkflowInstance)
Try
workflws = trackingQuery.GetWorkflows(options)
Catch ex As SqlException
workflowError = String.Format("A SQL exception occurred. Details:<br />{0}", ex.Message)
Return workflowData
Catch ex As IO.FileNotFoundException
workflowError = String.Format("File loading exception occurred. Details:<br />{0}", ex.Message)
Return workflowData
End Try
Dim trackingQuery As SqlTrackingQuery = New SqlTrackingQuery(connectionString)
Dim options As SqlTrackingQueryOptions = New SqlTrackingQueryOptions()
options.WorkflowType = GetType(Workflow1) ' where Workflow1 is the name of your Workflow

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).

Resources