I am debugging some code in an ASP.net web application project.
I have an If/Else statement nested in a Try/Catch block. Whenever an error occurs within the If block, rather than immediately jumping into the Catch block, it falls into the Else block.
I have stepped through the code repeatedly to witness this happening. When I throw an exception within the if block, I would expect logic to flow into the catch block, and I would never expect to see the if block get hit, and then the else block get hit, that seems to completely defeat the purpose of the if/else logic.
Here is the code in question:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadDocument()
End Sub
Private Sub LoadDocument()
Dim taDocuments As New SecureTableAdapters.IndividualDocumentsTableAdapter
Dim dtDocuments As New Secure.IndividualDocumentsDataTable
Dim iDocumentID As Integer = CInt(Request.QueryString("iDocumentID"))
Dim sFileName As String
Dim isMac As Boolean = clsApplication.isMac(Request.Browser.Platform)
Dim bDownloaded As Boolean = False
Try
If taDocuments.FillBy_IndividualDocumentID(dtDocuments, iDocumentID) > 0 Then
Dim oRow As Secure.IndividualDocumentsRow = dtDocuments.Rows(0)
sFileName = "Statement-" & oRow.sFileNumber & ".pdf"
If oRow.sDocumentName.ToUpper.Contains("LEDES") Or oRow.sDocumentName.ToUpper.Contains("TEXT") Then
sFileName = sFileName.Replace("pdf", "txt")
End If
Dim b As Byte() = Nothing
If oRow.IsbExtractedNull = False AndAlso oRow.bExtracted Then
Dim sHost As String = "206.220.201.175"
Dim sPath As String = String.Format("/Legacy/{0}/{1}/{2}.pdf", oRow.iFirmID.ToString, "Individuals", oRow.iIndividualDocumentID.ToString)
b = DownloadDocument(sHost, sPath)
If b Is Nothing Then
'When this line is hit, logic jumps to the else block with the comment below
Throw New Exception("FTP Download Failed")
Else
bDownloaded = True
End If
Else
bDownloaded = False
End If
If bDownloaded = False Then
b = getImage(iDocumentID, "oPDF", "iIndividualDocumentID", "tblIndividualDocuments")
If b Is Nothing Then
Throw New Exception
End If
End If
If isMac Then
Response.ContentType = "application/x-macbinary"
Else
Response.ContentType = "application/octet-stream"
End If
Response.Expires = 0
Response.AddHeader("Content-Disposition", "attachment; filename=""" & sFileName & """")
Response.BinaryWrite(b)
Else
'--->When the exception occurs, logic jumps to this else block
Throw New Exception
End If
Catch ex As Exception
Response.Write("Sorry, that statement could not be located. Please try again, or call us at xxx.xxx.xxxx for further information.")
clsApplication.EmailError("An error occurred downloading a statement: " & vbCrLf & ex.Source & vbCrLf & ex.Message & vbCrLf & ex.StackTrace)
End Try
End Sub
How is this possible?
It sounds like you're using the debugger with Optimizations still turned on. This can cause the Step Traceing to act in seemingly illogical and even impossible ways. This is caused because after the optimizer moves the code and variables around and consolidates different statements, there is no longer a simple or straight-forward relationship between the lines of source-code and the executable instructions.
Sounds like the code you're debugging against might be out of sync with the code that's executing. Try rebuilding the whole solution.
I think you are probably mistaken:
Try the following in simple vb .net winforms program.
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
Dim doIt As Boolean = True
If doIt Then
Throw New Exception("throwing that stuff")
Else
MsgBox("in here - how did that happen?")
End If
Catch ex As Exception
MsgBox(String.Format("That makes sense. Exception is: {0}", ex))
End Try
End Sub
End Class
Related
I am making Log in page for my project but I am getting an error "There is no row at position 0" while running.
I tried these lines of codes.
Imports System.Data.SqlClient
Imports System.Data
Partial Class Dept_login
Inherits System.Web.UI.Page
Protected Sub BtnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click
Dim ds As New DataSet
'Try
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("VMSConnectionString").ConnectionString)
con.Open()
Dim cmd As New SqlCommand("SELECT password FROM Dept_login WHERE user_id='" + Txtuname.Text + "'", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
If Not IsDBNull(ds) Then
If Txtpwd.Text = ds.Tables(0).Rows(0).Item("password") Then
Response.Redirect("Online Services.aspx") 'the page i want to redirect to after login successful
Else
Label1.Visible = True 'initially visible is false and text is INVALID PASSWORD
End If
con.Close()
' Catch ex As Exception
' End Try
End If
End Sub
Private Function Dept_login() As Integer
Throw New NotImplementedException
End Function
End Class
This line doesn't make sense:
If Not IsDBNull(ds) Then
ds will never be DBNull. Instead, check for the number of rows coming back, like:
If ds.Tables(0).Rows.Length > 0 Then
You're trying to get the first row (.Rows(0)) when there aren't any - that's what the error is telling you.
Try using something like this:
If ds.Tables(0).Rows.Count > 0 AndAlso Txtpwd.Text = ds.Tables(0).Rows(0).Item("password") Then
Response.Redirect("Online Services.aspx", False) 'the page i want to redirect to after login successful
Context.ApplicationInstance.CompleteRequest();
Else
Label1.Visible = True 'initially visible is false and text is INVALID PASSWORD
End If
con.Close()
' Catch ex As Exception
' End Try
(Note: You should use parameterization for the SQL query. You're leaving yourself open to a SQL injection attack.)
This line doesn't make sense:
If Not IsDBNull(ds) Then
Makes sense
If ds.Tables(0).Rows.count > 0 andalso ds.Tables..count > 0 Then
END IF
Hope this helps
Did you try using a datareader instead of a dataadapter?
Try
Dim datare As SqlDataReader
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("VMSConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT password FROM Dept_login WHERE user_id='#User'", cn)
cmd.Parameters.AddWithValue("#User", Txtuname.Text)
cn.Open()
datare = cmd.ExecuteReader()
With datare
If .Read() Then
If .Item(0) = txtpwd.Text Then
Response.Redirect("Online Services.aspx")
Else
Label1.Visible = True
End If
End If
End With
End Using
End Using
Catch ex As Exception
Throw ex
End Try
Also, on the query you write user_id. did you mean username? Is you query correct?
Working over 5 hours on the following problem:
Private Sub ModulEdit_PreInit(sender As Object, e As EventArgs) Handles Me.PreInit
Dim modulid As Integer = 1
loadeditors(modulid)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Sub loadeditors(modulID As Integer)
PlaceHolder1.Controls.Clear()
Using dbContext As New EntitiesModel()
Dim mps As List(Of ef.Modulparameter) = dbContext.Modulparameters.Where(Function(c) c.ModulID = modulID).ToList
Dim mmid As Int16
If EditMode.Checked = True Then
mmid = RadComboBox3.SelectedValue
End If
Dim mp As ef.Modulparameter
For Each mp In mps
Dim lbl As New Label
lbl.Text = "<BR>" & mp.Name & "<BR>"
PlaceHolder1.Controls.Add(lbl)
Select Case mp.Editor.Name
Case "textbox1line"
Dim con As New TextBox
con.ID = mp.ID
If EditMode.Checked = True Then
Using dbContext2 As New EntitiesModel
Try
Dim mpa As ef.Menu_modul_paramvalue = dbContext2.Menu_modul_paramvalues.Where(Function(c) c.ModulparameterID = mp.ID And c.Menu_modulID = mmid).First
con.Text = mpa.Valuestring
Catch ex As Exception
con.Text = "AAAA"
End Try
End Using
End If
PlaceHolder1.Controls.Add(con)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(Panel1, con, Nothing)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(con, con, Nothing)
Case "radeditor"
Dim con As New RadEditor
con.ID = mp.ID
con.ToolsFile = "\admin\controls\ToolsFile.xml"
'con.CssFiles.Add("\Content\frenzy\css\frenzy-orange.css")
If EditMode.Checked = True Then
Using dbContext2 As New EntitiesModel
Try
Dim mpa As ef.Menu_modul_paramvalue = dbContext2.Menu_modul_paramvalues.Where(Function(c) c.ModulparameterID = mp.ID And c.Menu_modulID = mmid).First
con.Content = mpa.Valuestring
Catch ex As Exception
con.Content = "BBBB"
End Try
End Using
End If
PlaceHolder1.Controls.Add(con)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(Panel1, con, Nothing)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(con, con, Nothing)
End Select
Next
End Using
End Sub
I add the control dynamicly, calling the codepart above in pre_init (tryed in load and init too with same result)
The value (text) for the control is there until that line PlaceHolder1.Controls.Add(con)
After the con.text is empty.
The control is added after, but with no value.
Strange, that in the same proc i add another control (label), where the text value is on the page after.
Adding additional info:
the control value (text or content), when debugging the LoadEditors), is allways correctly set. But then on the page both (textbox and radeditor) are empty
The routing is called from pre init, as described in a lot of related posts.
You are calling loadeditors in ModulEdit_Init. Shouldn't this be LoadControls ?
I fixed it myself:
Adding "con.ViewStateMode = System.Web.UI.ViewStateMode.Disabled" before adding control to placeholder
Calling "loadeditors()" in RadComboBox3 too
much probably the problem was, that i loaded editors in page-load or init, which got the correct values, but then the RadComboBox3.SelectedIndexChanged event was called, which overwrote the values somehow
So my answer is not a real answer, but it works now (I hate such: it works, but i dont know why) ;)
I'm trying to pass a value to a feedbacklabel after an asynch upload.
Protected Sub FileUploadComplete(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim filename As String = System.IO.Path.GetFileName(AsyncFileUpload1.FileName)
AsyncFileUpload1.SaveAs(Server.MapPath("tmp/") + filename)
lblFeedback.Text = "File uploaded. Processing information"
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(Server.MapPath("tmp/") + filename)
While objStreamReader.Peek <> -1
lblFeedback.Text += objStreamReader.ReadLine()
End While
objStreamReader.Close()
Catch ex As Exception
End Try
End Sub
The thing is I need to display how many rows have been uploaded in the database. How can I do this?
Add at the end of FileUploadComplete procedure following method call (I hope you can translate it from C# to VB):
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "feedback", string.Format("top.$get('{0}').innerText = '{1}'", lblFeedback.ClientID, lblFeedback.Text), true);
In codebehind I have the following:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
Dim sql As String
Dim conn As OleDbConnection
Dim cmd As OleDbDataAdapter
Dim ds As DataSet
Dim tbl As DataTable
conn = New OleDbConnection("Provider=SQLOLEDB;Data Source=(local);Initial Catalog='library';Integrated Security=SSPI;")
Try
sql = "SELECT f1, f2, f3 FROM mydb WHERE ltrim(rtrim(UPPER(username))) = 'MYNAME'"
cmd = New OleDbDataAdapter(sql, conn)
ds = New DataSet
cmd.Fill(ds)
tbl = New DataTable
tbl = ds.Tables(0)
If tbl.Rows.Count = 0 Then
Response.Redirect("goback.html")
End If
Response.Redirect("dummy.html")
Catch ex As Exception
Response.Redirect("goback2.html")
End Try
End Sub
The routine works to a point. I can check the value of tbl.Rows.Count = 1, so it should redirect to "dummy.html" WHICH IT DOES CORRECTLY so long as I comment out the line that redirects to "goback2.html".
If I uncomment the line to redirect to goback2, then it goes to "goback2.html"
I thought it should only execute that code if there was some error in the previous code - but there can't be an error in the previous code, if it executes. It's like it's executing the catch code regardless of what I'm going.
Oddly, it ONLY messes up with the redirect! If I replace the redirect to goback2 with an assignment to a textbox.text then it works (by ignoring that code) - but the redirect it seems to execute regardless of whether it should take the catch
Response.Redirect(string) throws a ThreadAbortException when Response.End() is called.
Use the overload that takes a string and a boolean instead:
Response.Redirect("goback.html", false);
From MSDN: the second parameter, endResponse, "Indicates whether execution of the current page should terminate."
Response.Redirect throws a ThreadAbortException to terminate the current request.
Your Catch block is catching that exception.
It may be because of ThreadAbortedException because of Response.Redirect. - MSDN support link
You haven't open the connection. You cannot redirect in an Try/Catch. You should set a boolean variable success to false and check for it after the Try/Catch/Finally and redirect if it's set to false.
Have a look at this SO-Question: Is there something that prevents Response.Redirect to work inside try-catch block?
This would be better:
Dim success As Boolean = True
Dim ds As New DataSet
Using conn As New OleDb.OleDbConnection("Provider=SQLOLEDB;Data Source=(local);Initial Catalog='library';Integrated Security=SSPI;")
Try
Dim Sql = "SELECT f1, f2, f3 FROM mydb WHERE ltrim(rtrim(UPPER(username))) = 'MYNAME'"
Dim cmd = New OleDb.OleDbDataAdapter(Sql, conn)
conn.Open()
cmd.Fill(ds)
Catch ex As Exception
success = False
End Try
End Using
If Not success Then
Response.Redirect("goback2.html")
ElseIf ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count = 0 Then
Response.Redirect("goback.html")
Else
Response.Redirect("dummy.html")
End If
I'm trying to sort records in the gridview right after a radio button is selected. My approach is with the dataview, but because the dataset variable doesn't survive a round trip to the server, I don't know how to make this happen. please help!
Public Sub GetCustomers()
db.RunProcedure("usp_customers_get_all")
db.doSort(radList.SelectedValue)
gvCustomers.DataSource = db.MyView
End Sub
Protected Sub radList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radList.SelectedIndexChanged
If radList.SelectedValue = 0 Then
db.doSort(0)
gvCustomers.DataSource = db.MyView
End If
If radList.SelectedValue = 1 Then
db.doSort(1)
gvCustomers.DataSource = db.MyView
End If
End Sub
Public Sub doSort(ByVal strIn As Integer)
If strIn = 0 Then
MyView.Sort = "lastname, firstname"
Else
MyView.Sort = "username"
End If
End Sub
Public Sub RunProcedure(ByVal strName As String)
Dim objConnection As New SqlConnection(mstrConnection)
Dim mdbDataAdapter As New SqlDataAdapter(strName, objConnection)
Try
mdbDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
Me.mDataset.Clear()
mdbDataAdapter.Fill(mDataset, "tblCustomers")
MyView.Table = mDataset.Tables("tblCustomers")
Catch ex As Exception
Throw New Exception("stored procedure is " & strName.ToString & " error is " & ex.Message)
End Try
End Sub
You could store the dataset in one of the following places and then when the post back happens just load it again from there. I have done many of these on a corporate intranet.
Session Variable
ViewState
QueryString
Cache
I cant really provide more help as you didn't specify if this is done in Ajax or if you do a full postback etc. If you provide more info I would love to help you.