Neither a DataColumn nor a DataRelation - asp.net error - asp.net

I'm getting this error:
banner_flag is neither a DataColumn nor a DataRelation for table temp
After searching, the error is apparently appearing because I'm referencing banner_flag, but it doesn't exist, but I've declared it in all the same places as intra_user (As an example).
Below is my code, any help is greatly appreciated. Thanks!:
Dim reason As String = ""
Dim banner_action As String = ""
Dim esr_link As String = ""
Dim seen_message AS String = ""
Dim last_updated AS String = ""
Dim daysSinceUpdated As Integer
Dim intra_user As String = ""
Dim banner_flag As String = ""
Sub Page_Load(ByVal Sender As Object, ByVal e As EventArgs)
Dim sc As Web.HttpContext = Web.HttpContext.Current
Dim updatePeriod As Integer = 90
Dim strConn As String = getStrConn(sc)
Dim rst As DataView
Dim strsql, last_updated, email_address As String
Dim update_required As String = ""
' - Really don't know what this is for... so I have commented it out.
' - Response.Write("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />hello no details")
' Check users last update to their email address
strsql = "select last_updated, email, esr_link, intra_user, banner_action, seen_message from user_group where id = " & Session("u_id") & " AND (esr_link <> 5)"
rst = GetDefaultView(strsql, strConn)
If (rst.count > 0) Then
' Get details for new banner check for launching windows at startup
If Not IsDBNull(rst(0)("banner_action")) Then
banner_action = rst(0)("banner_action").ToString
Else
banner_action = ""
End If
' Get details for seen message
If Not IsDBNull(rst(0)("seen_message")) Then
seen_message = rst(0)("seen_message").ToString
Else
seen_message = ""
End If
' Gets banner_flag value
If Not IsDBNull(rst(0)("banner_flag")) Then
banner_flag = rst(0)("banner_flag").ToString
Else
banner_flag = ""
End If
' Gets the ESR link value to check if the New User code needs to run
If Not IsDBNull(rst(0)("esr_link")) Then
esr_link = rst(0)("esr_link").ToString
Else
esr_link = ""
End If
' Gets the intra_user value
If Not IsDBNull(rst(0)("intra_user")) Then
intra_user = rst(0)("intra_user").ToString
Else
intra_user = ""
End If
' Grab users last_updated value if available
If Not IsDBNull(rst(0)("last_updated")) Then
last_updated = rst(0)("last_updated").ToString
Else
last_updated = ""
End If
' Grab users email address if available
If Not IsDBNull(rst(0)("email")) Then
email_address = rst(0)("email").ToString
email_address = Replace(email_address, "'", "")
Else
email_address = ""
End If
'Checks the email address to see if it is valid
If email_address <> "" Then
If IsEmailValid(email_address) = False Then
update_required = "true"
reason = "Your current Email address is invalid please update it." & vbCrLf
End If
Else
update_required = "true"
reason = "You have not entered a current Email address please add one." & vbCrLf
End If
'If it not empty then compare
If last_updated <> "" Then
last_updated = CDate(last_updated)
daysSinceUpdated = DateDiff("d", last_updated, Now())
If daysSinceUpdated > updatePeriod Then
update_required = "true"
reason &= "Your details have expired please check them to ensure they are up-to-date" & vbCrLf
End If
'If it empty then needs updating...
Else
update_required = "true"
reason = "Your details have expired please check them to ensure they are up-to-date" & vbCrLf
End If
rst.Dispose()
rst = Nothing
Session("checked_details") = "true"
If update_required = "true" Then
reason = Server.UrlEncode(reason)
'response.write(reason)
'Response.Write("<scr" & "ipt language='javascript'>findTop().submitURL('/sorce/app_centre/launch_form.aspx?fhandle=User_Details_Amendment&elemid=" & Session("u_id") & "&reason=" & reason & "');</scr" & "ipt>")
End If
Else
'Response.Write("<br /><br /><br /><br /><br /><br />hello details")
'Response.Write("<scr" & "ipt language='javascript'>findTop().submitURL('/sorce/app_centre/launch_form.aspx?fhandle=User_Details_Amendment&elemid=" & Session("u_id") & "&reason=" & reason & "');</scr" & "ipt>")
End If
End Sub
Function IsEmailValid(ByVal strEmail As String) As Boolean
Dim strArray() As String
Dim strItem As String
Dim i As Integer
Dim c As String
Dim blnIsItValid As Boolean
' assume the email address is correct
blnIsItValid = True
' split the email address in two parts: name#domain.ext
strArray = Split(strEmail, "#")
' if there are more or less than two parts
If UBound(strArray) <> 1 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' check each part
For Each strItem In strArray
' no part can be void
If Len(strItem) <= 0 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' check each character of the part
' only following "abcdefghijklmnopqrstuvwxyz_-."
' characters and the ten digits are allowed
For i = 1 To Len(strItem)
c = LCase(Mid(strItem, i, 1))
' if there is an illegal character in the part
If InStr("abcdefghijklmnopqrstuvwxyz_-.", c) <= 0 And Not IsNumeric(c) Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
Next
' the first and the last character in the part cannot be . (dot)
If Left(strItem, 1) = "." Or Right(strItem, 1) = "." Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
Next
' the second part (domain.ext) must contain a . (dot)
If InStr(strArray(1), ".") <= 0 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' check the length oh the extension
i = Len(strArray(1)) - InStrRev(strArray(1), ".")
' the length of the extension can be only 2, 3, or 4
' to cover the new "info" extension
If i <> 2 And i <> 3 And i <> 4 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' after . (dot) cannot follow a . (dot)
If InStr(strEmail, "..") > 0 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' finally it's OK
IsEmailValid = blnIsItValid
End Function

Your sql statement is:
select last_updated, email, esr_link, intra_user, banner_action, seen_message from user_group where ...
Therefore there will be a column in the returned DataView for intra_user, which is present in the sql select, but not banner_flag, which is not present.

Related

Retrieving values from dynamically created controls

First post, so go easy on me.
I've been coding for years, first with VB6, then VB.NET and more recently ASP.NET. I'm ashamed to say, this issue has beaten me to the point where I need to ask for help. What's more annoying is that this should be a simple thing to achieve! I'm clearly missing something here.
I'm creating checkbox controls dynamically, quite a few of them in fact. Two per dynamically created table row and their IDs are appended with the ID of the particular DB record on the row, row 1, 2, 3 etc. So on each row there would be two checkboxes, ihave_check_1, ineed_check_1. The next row would be ihave_check_2 and ineed_check_2 and so on.
There is a submit button at the bottom of the page, and when clicked, it's supposed to loop through each row (and cell) in the table and pick out controls whose IDs contain "ihave_check_" and "ineed_check_" then get their Checked value. Once I have the values, I add a record into the database.
Problem is, when you click the button, the table disappears and so do the values.
From what I've read so far, this is happening because the controls are dynamically created, if they were static (coded in the HTML section) I wouldn't have this problem.
So first question, what do I need to do to get it working?
And second question, why is using dynamic controls so difficult?
Here's the code setting up the table, which works great:
Private Sub ddCardSeries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddCardSeries.SelectedIndexChanged
If IsPostBack = True And Not ddCardSeries.SelectedValue = "Select..." Then
cardsTable.Visible = True
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXXXXX;")
Dim dtSections As New DataTable
dtSections = dat.DataSelect("SELECT baseCardID,baseCardSeries,baseCardNumber,baseCardName,frontArtist,conceptArtist,backArtist,backWriter,isBaseCard,isDieCut,isMatte,isGlossy,differentBack,frontImage,backImage FROM baseCards where baseCardSeries = '" & Split(Split(ddCardSeries.Text, "(ID:")(1), ")")(0) & "' and isBaseCard = 'Yes'")
If dtSections.Rows.Count > 0 Then
For i As Integer = 0 To dtSections.Rows.Count - 1
Dim row As New TableRow
For x = 0 To dtSections.Columns.Count - 1
Dim cell1 As New TableCell
If Not IsDBNull(dtSections.Rows(i)(x)) Then
If x = 0 Then
cell1.Text = dtSections.Rows(i)(x)
ElseIf x = 1 Then
cell1.Text = get_card_series(dtSections.Rows(i)(x))
ElseIf x = 13 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
ElseIf x = 14 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
Else
cell1.Text = dtSections.Rows(i)(x)
End If
Else
cell1.Text = ""
End If
row.Cells.Add(cell1)
Next x
Dim newbutton As New Button
Dim newlabel As New Label
newlabel.Text = "<br />"
newbutton.Text = "Modify this entry"
newbutton.Width = 120
newbutton.ID = "modify_button_" & dtSections.Rows(i)(0)
Dim newcheck1 As New CheckBox
Dim newlabel2 As New Label
newlabel2.Text = "<br />"
newcheck1.Text = "I own this card"
newcheck1.Width = 120
newcheck1.ID = "ihave_check_" & dtSections.Rows(i)(0)
Dim newcheck2 As New CheckBox
newcheck2.Text = "I need this card"
newcheck2.Width = 120
newcheck2.ID = "ineed_check_" & dtSections.Rows(i)(0)
Dim cell2 As New TableCell
If is_user_admin() = True Then
newbutton.Enabled = True
Else
newbutton.Enabled = False
End If
cell2.Controls.Add(newbutton)
cell2.Controls.Add(newlabel)
cell2.Controls.Add(newcheck1)
cell2.Controls.Add(newlabel2)
cell2.Controls.Add(newcheck2)
row.Cells.Add(cell2)
cardsTable.Rows.Add(row)
Next
End If
Else
cardsTable.Visible = False
End If
End Sub
Here's the code that loops through the table and tries to save the results to the database:
Protected Sub SubmitChanges_Click(sender As Object, e As EventArgs) Handles SubmitChanges.Click
For Each pcontrol As control In Page.Controls
Dim havecard As String = Nothing
Dim needcard As String = Nothing
Dim rowcardid As String = Nothing
'For Each tabcell As TableCell In tabrow.Cells
'For Each pgcontrol As Control In tabcell.Controls
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ihave" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
havecard = "Yes"
Else
havecard = "No"
End If
End If
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ineed" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
needcard = "Yes"
Else
needcard = "No"
End If
End If
'Next
If Not havecard = Nothing And Not needcard = Nothing Then
If add_card_to_user_list(Session("username"), rowcardid, havecard, needcard) = True Then
Label1.Text = "Update complete"
Else
Label1.Text = "Update failed"
End If
End If
'Next
Next
End Sub
Public Function add_card_to_user_list(ByVal userid As String, ByVal cardid As String, ByVal own As String, ByVal need As String) As Boolean
Try
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXX;")
Dim dtCardSeries As New DataTable
dtCardSeries = dat.DataSelect("select CardID from [" & userid & "_cards] where cardid = '" & cardid & "'")
If dtCardSeries.Rows.Count > 0 Then
dat.DataDelete("delete from [" & userid & "_cards] where cardid = '" & cardid & "'")
End If
dat.DataInsert("insert into [" & userid & "_cards] (Username,CardID,Own,Need) values ('" & userid & "', '" & cardid & "', '" & own & "', '" & need & "');")
Return True
Catch ex As Exception
Return False
End Try
End Function
Any help at this point would be gratefully received.
Thanks!

Called to stored procedure through VB.net application not working

I have a VB.Net application that calls the database stored procedure and it supposedly suppose to look for tasks in a table with the Status of "Wait" and then updates it to executing and then generates the report.
However, I have ran the step in Visual Studio but it seems it doesn't to run the store procedure or run the stored procedure with no result .
I have individually ran the stored procedure through SQL Developer to check it and it works, so I don't think it's the problem.
I find that the rsresult never has rows so I am wondering do I need to add another line of code after ExecuteReader?
Can you all please help?
Below is the function and stored procedure
Public Function SelectGetTasktoExec(ByVal plngCount As Integer, ByVal
pstrIPAddr As String, ByRef pdicResult As Dictionary) As Boolean
Dim result As Boolean = False
Dim blnResult As Boolean
Dim strCaller As String = ""
Dim strErrMsg As String = ""
Dim lngRet As Integer
Dim rsResult As OracleDataReader = Nothing
Dim dicItem As Dictionary
Dim intIndex As Integer
Try
m_TranObj.CreateSPCaller("PKG_TD_BATCH_REPORT.SELECT_REPRINT_TASK")
m_TranObj.AddSPParams("i_task_count", OracleDbType.Decimal, 10, plngCount, ParameterDirection.Input)
m_TranObj.AddSPParams("i_ipaddr", OracleDbType.Varchar2, 16, pstrIPAddr, ParameterDirection.Input)
m_TranObj.AddSPParams("ocs_name", OracleDbType.RefCursor, 20, Nothing, ParameterDirection.Output)
m_TranObj.AddSPParams("o_err_code", OracleDbType.Decimal, 20, lngRet, ParameterDirection.Output)
If Not m_TranObj.RunSPReturnRS(lngRet, "o_err_code", rsResult) Then
strErrMsg = "call Pkg_Td_Batch_Report.SELECT_REPRINT_TASK failed."
Throw New Exception()
End If
If lngRet <> 0 Then
strErrMsg = "Call Pkg_Td_Batch_Report.SELECT_REPRINT_TASK failed,Error code:" & CStr(lngRet)
Throw New Exception()
End If
intIndex = gc_DicFirstKey
rsResult.Read()
While rsResult.HasRows()
dicItem = New Dictionary
dicItem.Add(gc_KEY_TASK_NO, rsResult("TASK_NO") & "")
dicItem.Add(gc_KEY_QUEUE_NO, rsResult("QUEUE_NO") & "")
dicItem.Add(gc_KEY_START_DATE, rsResult("START_DATE") & "")
dicItem.Add(gc_KEY_END_DATE, rsResult("END_DATE") & "")
dicItem.Add(gc_KEY_STORAGE_PATH, rsResult("STORAGE_PATH") & "")
dicItem.Add(gc_KEY_DATA_SOURCE, rsResult("DATA_SOURCE") & "")
dicItem.Add(gc_KEY_TEMPLATE_NAME, rsResult("TEMPLATE_NAME") & "")
dicItem.Add(gc_KEY_SOFT_COPY_FORMATS, rsResult("SOFT_COPY_FORMATS") & "")
dicItem.Add(gc_KEY_SCHEDULED_EXECUTE_DATE, rsResult("SCHEDULED_EXECUTE_DATE") & "")
dicItem.Add(gc_KEY_HARD_DISTRIBUTION_IND, rsResult("PRINT_IND") & "")
dicItem.Add(gc_KEY_SOFT_DISTRIBUTION_IND, rsResult("EXPORT_IND") & "")
dicItem.Add(gc_KEY_RESULT_PATH, rsResult("RESULT_PATH") & "")
dicItem.Add(gc_KEY_PRINTER_NAME, rsResult("PRINTER_NAME") & "")
dicItem.Add(gc_KEY_TRACTOR_NO, rsResult("TRACTOR_NO") & "")
dicItem.Add(gc_KEY_TEMPLATE_NO, rsResult("TEMPLATE_NO") & "")
dicItem.Add(gc_KEY_DUPLEX_PRINT_IND, rsResult("DUPLEX_PRINT_IND") & "")
dicItem.Add(gc_KEY_DESCRIPTION, rsResult("DESCRIPTION") & "")
dicItem.Add(gc_KEY_DEPT_DIVISION_CODE, rsResult("DEPT_DIVISION_CODE") & "")
dicItem.Add(gc_KEY_SYSDATE, Strings.Format(rsResult("SYSDATE"), gc_FormatDateTime) & "")
dicItem.Add(gc_KEY_FROM_PAGE, rsResult("FROM_PAGE") & "")
dicItem.Add(gc_KEY_TO_PAGE, rsResult("TO_PAGE") & "")
'add end
pdicResult.Add(intIndex, dicItem)
intIndex += 1
End While
SBL_Error.DebugLog(strCaller, "End")
blnResult = True
Catch excep As System.Exception
blnResult = False
SBL_Error.ErrorLog(strCaller, strErrMsg & excep.ToString)
Throw excep
Finally
result = blnResult
End Try
Return result
End Function
Here is the RunSPReturnRS method:
Public Function RunSPReturnRS(ByRef plngCnt As Integer, ByVal pstrReturnName
As String, ByRef prsResult As Object) As Boolean
Dim result As Boolean = False
Dim blnResult As Boolean
Dim strCaller As String = ""
Dim strErrMsg As String = ""
Dim strMsg As String = ""
Dim rsresult As String = ""
Try
If Not mblnConnected Then
If Not Connect() Then
strErrMsg = "Can not open connection!"
End If
End If
prsResult = mCmd.ExecuteReader()
If prsResult.HasRows Then
prsResult.Read()
prsResult = prsResult(0).ToString()
strMsg = "Batch Date is" + Space(1) + prsResult
Else
prsResult = prsResult
End If
If pstrReturnName Is "" Then
plngCnt = mCmd.Parameters(pstrReturnName).Value
End If
mCmd.Dispose()
SBL_Error.DebugLog(strCaller, strMsg)
blnResult = True
Catch ex As Exception
SBL_Error.ErrorLog(strCaller, ex.ToString())
blnResult = False
Finally
result = blnResult
End Try
Return result
There's little to go on here... but... if the stored procedure only returns a single row then you'd never see the result.
You need the rsResult.Read within the While loop:
While rsResult.HasRows
rsResult.Read
' do your processing...
End While

Button click is not firing in a multiview?

I have one aspx page which contains 4 multiview controls and different views in each of them. In the first view which is the details view, I am entering some invoice details and checks the db for the datarow to appear along with the payment details.
The code works fine till it displays the datarow along with the payment control, but the payment control (user control) is not firing its validation controls properly (required field & regex controls). Besides the button click also not firing the validation code ,although it saves the data if I enter the correct details.
Could anyone of you please look into the below code and tell me whats wrong in it?.
Protected Sub cmdPay_Click(sender As Object, e As EventArgs) Handles cmdPay.Click
mvwDetails.Visible = False
Try
' If Not Page.IsPostBack Then
If Me.CreditCard1.CCNumber.Length < 14 Or Me.CreditCard1.CCNumber.Length > 16 Then
Me.lblError.Text = "Please enter Valid Card details"
Else
Dim result As DateTime = Conversions.ToDate("1/1/1900")
If Not DateTime.TryParse(Me.CreditCard1.CCExpireDate, result) Then
Me.lblError.Text = "Please enter the Valid Expiry Date"
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
ElseIf DateTime.Compare(result, DateTime.Today) < 0 Then
Me.lblError.Text = "Please enter the Valid Expiry Date"
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
ElseIf Me.CreditCard1.CVV Is Nothing Or Not Versioned.IsNumeric(DirectCast(Me.CreditCard1.CVV, Object)) Then
Me.lblError.Text = "Invalid credit card details."
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
ElseIf Strings.Len(Me.CreditCard1.CVV) > 4 Then
Me.lblError.Text = "Invalid cvv number."
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
Else
Dim OrderID As String
OrderID = grdMain.Items(0).Cells(1).Text
If Page.IsValid Then
Dim dtOrderPerson As DataTable = Me.DataAction.GetDataTable("SELECT o.ID,o.BillToID,o.ShipToName,o.BillToCompanyID,o.OrganizationID,o.InvoiceNumber,OrderDate,GrandTotal,Balance,CurrencySymbol,NumDigitsAfterDecimal FROM " & Convert.ToString(Me.Database) & "..vwOrders o INNER JOIN " & Convert.ToString(Me.Database) & "..vwCurrencyTypes ct ON o.CurrencyTypeID=ct.ID where Balance > 0 AND o.OrderStatus <> 'Cancelled' And o.ID=" & CLng(OrderID), IAptifyDataAction.DSLCacheSetting.BypassCache)
If dtOrderPerson.Rows.Count > 0 Then
Me.mvwMakePayment.SetActiveView(vwMakePayment)
Me.mvwMakePayment.Visible = True
'lblkaj.Text = "returned a record"
FirstName = dtOrderPerson.Rows(0).Item("ShipToName").Trim.ToString()
Dim entityObject As AptifyGenericEntityBase = Me.AptifyApplication.GetEntityObject("Payments", -1)
entityObject.SetValue("EmployeeID", DirectCast(1, Object)) 'No web user is returned as the data is based on orderid and companyid , Employee id of the web user is 1 hence using the same
' entityObject.SetValue("EmployeeID", DirectCast(grdMain.Items(0).Cells(0).ToString(), Object))
entityObject.SetValue("PersonID", DirectCast(dtOrderPerson.Rows(0).Item("BillToID").ToString, Object))
entityObject.SetValue("CompanyID", DirectCast(dtOrderPerson.Rows(0).Item("BillToCompanyID").ToString, Object)) 'Me.dtOrders.Rows(0).Item("BilllToCompanyID").ToString
entityObject.SetValue("PaymentDate", DirectCast(DateTime.Today, Object))
entityObject.SetValue("DepositDate", DirectCast(DateTime.Today, Object))
entityObject.SetValue("EffectiveDate", DirectCast(DateTime.Today, Object))
entityObject.SetValue("PaymentTypeID", DirectCast(Me.CreditCard1.PaymentTypeID, Object))
entityObject.SetValue("CCAccountNumber", DirectCast(Me.CreditCard1.CCNumber, Object))
entityObject.SetValue("CCExpireDate", DirectCast(Me.CreditCard1.CCExpireDate, Object))
entityObject.SetAddValue("_xCCSecurityNumber", DirectCast(Me.CreditCard1.CVV, Object))
entityObject.SetValue("PaymentLevelID", DirectCast(1, Object))
' entityObject.SetValue("Comments", DirectCast("Created through the CGI e-Business Suite", Object))
entityObject.SetAddValue("_xConvertQuotesToRegularOrder", DirectCast("1", Object))
Dim genericEntityBase As AptifyGenericEntityBase = entityObject.SubTypes("PaymentLines").Add()
genericEntityBase.SetValue("Amount", DirectCast(dtOrderPerson.Rows(0).Item("Balance").ToString, Object))
genericEntityBase.SetValue("OrderID", DirectCast(dtOrderPerson.Rows(0).Item("ID").ToString, Object))
genericEntityBase.SetValue("Comments", DirectCast("Invoice paid from web", Object))
If entityObject.Save(True) Then
Dim dtPyments As DataTable = Me.DataAction.GetDataTable("select P.ID,P.PersonID,P.CompanyID,P.PaymentDate,Pl.OrderID,Pl.Amount from payment P inner join paymentdetail pl on P.id=Pl.paymentid where pl.orderid=" & CLng(OrderID))
' Me.grdReceipt.DataSource = DirectCast(dtPyments, Object)
' grdReceipt.DataBind()
' grdReceipt.Visible = False
lblInvo.Text = OrderID
lblPyNo.Text = dtPyments.Rows(0).Item("ID").ToString()
lblAmount0.Text = dtPyments.Rows(0).Item("Amount").ToString()
Dim amnt As Double = lblAmount0.Text
amnt = FormatNumber(amnt, 2)
lblAmount0.Text = amnt
' EmailID = txtEmail.Text.Trim.ToString
mvwMakePayment.Visible = False
mvwMessage.Visible = True
mvwMessage.SetActiveView(vwSuccessMessage)
Dim mailBody As New StringBuilder
mailBody.Append("Dear " & FirstName & ", ").AppendLine(Environment.NewLine)
mailBody.Append("Thank you, for your payment of invoice number " & lblInvo.Text & ". $ " & lblAmount0.Text & " " & "has been deducted from your nominated credit card. ").AppendLine(Environment.NewLine)
mailBody.Append("Your receipt number is " & lblPyNo.Text & ". Please keep this for your reference.").AppendLine(Environment.NewLine)
mailBody.Append("If you have any queries regarding this payment please contact our Accounts Receivable department on 04456666 and reference your invoice number.").AppendLine(Environment.NewLine)
' mailBody.Append("Receipt Number : " & lblPyNo0.Text)
sendEmail("Accounts Department", lblEmail.Text, "Payment Receipt’", mailBody.ToString)
' lblEmail.Text = EmailID
Else
mvwMessage.Visible = True
mvwMessage.SetActiveView(vwFailedMessage)
End If
End If
End If
End If
End If
'End If
Catch ex As ThreadAbortException
ExceptionManager.Publish(ex)
ProjectData.SetProjectError(DirectCast(ex, Exception))
ProjectData.ClearProjectError()
Catch ex As Exception
ProjectData.SetProjectError(ex)
ExceptionManager.Publish(ex)
ProjectData.ClearProjectError()
End Try
End Sub
check if you have proper validation group, also can happen if you are conditionally setting causes validation if so check that too.

Invalid Cast Exception with Update Panel

On Button Click
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
MsgBox("INSIDE")
If SocialAuthUser.IsLoggedIn Then
Dim accountId As Integer = BLL.getAccIDFromSocialAuthSession
Dim AlbumID As Integer = BLL.createAndReturnNewAlbumId(txtStoryTitle.Text.Trim, "")
Dim URL As String = BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim)
Dim dt As New DataTable
dt.Columns.Add("PictureID")
dt.Columns.Add("AccountID")
dt.Columns.Add("AlbumID")
dt.Columns.Add("URL")
dt.Columns.Add("Thumbnail")
dt.Columns.Add("Description")
dt.Columns.Add("AlbumCover")
dt.Columns.Add("Tags")
dt.Columns.Add("Votes")
dt.Columns.Add("Abused")
dt.Columns.Add("isActive")
Dim Row As DataRow
Dim uniqueFileName As String = ""
If Session("ID") Is Nothing Then
lblMessage.Text = "You don't seem to have uploaded any pictures."
Exit Sub
Else
**Dim FileCount As Integer = Request.Form(Request.Form.Count - 2)**
Dim FileName, TargetName As String
Try
Dim Path As String = Server.MapPath(BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim))
If Not IO.Directory.Exists(Path) Then
IO.Directory.CreateDirectory(Path)
End If
Dim StartIndex As Integer
Dim PicCount As Integer
For i As Integer = 0 To Request.Form.Count - 1
If Request.Form(i).ToLower.Contains("jpg") Or Request.Form(i).ToLower.Contains("gif") Or Request.Form(i).ToLower.Contains("png") Then
StartIndex = i + 1
Exit For
End If
Next
For i As Integer = StartIndex To Request.Form.Count - 4 Step 3
FileName = Request.Form(i)
'## If part here is not kaam ka..but still using it for worst case scenario
If IO.File.Exists(Path & FileName) Then
TargetName = Path & FileName
'MsgBox(TargetName & "--- 1")
Dim j As Integer = 1
While IO.File.Exists(TargetName)
TargetName = Path & IO.Path.GetFileNameWithoutExtension(FileName) & "(" & j & ")" & IO.Path.GetExtension(FileName)
j += 1
End While
Else
uniqueFileName = Guid.NewGuid.ToString & "__" & FileName
TargetName = Path & uniqueFileName
End If
IO.File.Move(Server.MapPath("~/TempUploads/" & Session("ID") & "/" & FileName), TargetName)
PicCount += 1
Row = dt.NewRow()
Row(1) = accountId
Row(2) = AlbumID
Row(3) = URL & uniqueFileName
Row(4) = ""
Row(5) = "No Desc"
Row(6) = "False"
Row(7) = ""
Row(8) = "0"
Row(9) = "0"
Row(10) = "True"
dt.Rows.Add(Row)
Next
If BLL.insertImagesIntoAlbum(dt) Then
lblMessage.Text = PicCount & IIf(PicCount = 1, " Picture", " Pictures") & " Saved!"
lblMessage.ForeColor = Drawing.Color.Black
Dim db As SqlDatabase = Connection.connection
Using cmd As DbCommand = db.GetSqlStringCommand("SELECT PictureID,URL FROM AlbumPictures WHERE AlbumID=#AlbumID AND AccountID=#AccountID")
db.AddInParameter(cmd, "AlbumID", Data.DbType.Int32, AlbumID)
db.AddInParameter(cmd, "AccountID", Data.DbType.Int32, accountId)
Using ds As DataSet = db.ExecuteDataSet(cmd)
If ds.Tables(0).Rows.Count > 0 Then
ListView1.DataSource = ds.Tables(0)
ListView1.DataBind()
Else
lblMessage.Text = "No Such Album Exists."
End If
End Using
End Using
'WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.ReturnUrl("~/Memories/SortImages.aspx?id=" & AlbumID))
Else
'TODO:we'll show some error msg
End If
Catch ex As Exception
MsgBox(ex.Message)
lblMessage.Text = "Oo Poop!!"
End Try
End If
Else
WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.LoginWithReturnUrl("~/Memories/CreateAlbum.aspx"))
Exit Sub
End If
End Sub
The above code works fine.I have added an Update Panel in the page to avoid post back, But when i add the button click as a trigger
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" />
</Triggers>
in the update panel to avoid post back, i get the following error.This happens when i add the button click as a Trigger to the update panel.
The Request.Form returns a NameValueCollection which is accessible by the name of the key or the int indexer. It always returns a String and not an Integer.
Dim FileCount As String = Request.Form(Request.Form.Count - 2)
This is all intuition from the exception message, but on the line
FileCount As Integer = Request.Form(Request.Form.Count - 2)
It looks like Request.Form(Request.Form.Count - 2) is a string, and you're trying trying to assign a it to an integer type.
I don't know what you're trying to do, but the string looks like it contains "true" do you want the following?
FileCount As Integer += Boolean.Parse(Request.Form(Request.Form.Count - 2)) ? 1 : 0;

Performance issue with this code [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
the following code is for user control(it display banner), the page get stuck in IIS with status Executerequesthandler (when there is concurrent requests for this page), when I take this user control out from the page it runs smoothy, please note this control is embeded 5 times in the page. Here is the entire code for this user control, can someone spot out the problem?
Public Class daAds
Private Remote_Host As String
Private Script_Name As String
Private PATH_INFO As String
Private Page_Link As String
Private Country As String
Public Property p_Country() As String
Get
Return Country
End Get
Set(ByVal value As String)
Country = value
End Set
End Property
Public Property p_Page_Link() As String
Get
Return Page_Link
End Get
Set(ByVal value As String)
Page_Link = value
End Set
End Property
Public Property p_Remote_Host() As String
Get
Return Remote_Host
End Get
Set(ByVal value As String)
Remote_Host = value
End Set
End Property
Public Property p_Script_Name() As String
Get
Return Script_Name
End Get
Set(ByVal value As String)
Script_Name = value
End Set
End Property
Private ConnectionToFetch As SqlConnection
Private ReadOnly Property Connection() As SqlConnection
Get
ConnectionToFetch = New SqlConnection(ConnectionString)
ConnectionToFetch.Open()
Return ConnectionToFetch
End Get
End Property
Private ReadOnly Property ConnectionString() As String
Get
Return ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString
End Get
End Property
Public Property p_PATH_INFO() As String
Get
Return PATH_INFO
End Get
Set(ByVal value As String)
PATH_INFO = value
End Set
End Property
Public Function showAd(ByVal Banner_inc As Integer, ByVal banner_layout As String, Optional ByVal ShowAdsInfo As Integer = 0) As String
'Return ""
Try
'Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString
Dim imp_user_ip As String = Trim(Remote_Host)
Dim imp_country As String = Trim(p_Country)
imp_country = Replace(imp_country, Chr(10), "")
imp_country = Replace(imp_country, Chr(13), "")
Dim imp_page_name As String = Trim(Script_Name)
Dim imp_page_name2 As String = Trim(PATH_INFO)
Dim imp_page_link As String = p_Page_Link
'Response.Write(imp_page_name)
'ParamArrayAttribute()
'Dim m As DataSet
'm = SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, "disp_banner_byPageName_views", parameters)
Dim InsertCommand As New SqlCommand
InsertCommand.Connection = Connection
InsertCommand.CommandText = "disp_banner_byPageName_views"
InsertCommand.CommandType = CommandType.StoredProcedure '
'Dim IdParameter = New SqlParameter("#CategoryID", SqlDbType.Int)
'Dim NameParameter = New SqlParameter("#CategoryName", SqlDbType.NVarChar)
'IdParameter.Direction = ParameterDirection.Output
'NameParameter.Value = txtCategoryName.Text
'InsertCommand.Parameters.Add(IdParameter)
'InsertCommand.Parameters.Add(NameParameter)
Dim Param_Imp_user_ip = New SqlParameter("#imp_user_ip", SqlDbType.VarChar)
Param_Imp_user_ip.Direction = ParameterDirection.Input
Param_Imp_user_ip.Value = imp_user_ip
InsertCommand.Parameters.Add(Param_Imp_user_ip)
Param_Imp_user_ip = Nothing
Dim Param_imp_country = New SqlParameter("#imp_country", SqlDbType.VarChar)
Param_imp_country.Direction = ParameterDirection.Input
Param_imp_country.Value = imp_country '"jo" '
InsertCommand.Parameters.Add(Param_imp_country)
Param_imp_country = Nothing
Dim Param_banner_inc = New SqlParameter("#banner_inc", SqlDbType.Int)
Param_banner_inc.Direction = ParameterDirection.Input
Param_banner_inc.Value = Banner_inc
InsertCommand.Parameters.Add(Param_banner_inc)
Param_banner_inc = Nothing
Dim Param_imp_page_name = New SqlParameter("#imp_page_name", SqlDbType.VarChar)
Param_imp_page_name.Direction = ParameterDirection.Input
Param_imp_page_name.Value = imp_page_name
InsertCommand.Parameters.Add(Param_imp_page_name)
Param_imp_page_name = Nothing
Dim Param_imp_page_link = New SqlParameter("#imp_page_link", SqlDbType.VarChar)
Param_imp_page_link.Direction = ParameterDirection.Input
Param_imp_page_link.Value = imp_page_link
InsertCommand.Parameters.Add(Param_imp_page_link)
Param_imp_page_link = Nothing
Dim Param_banner_layout = New SqlParameter("#banner_layout", SqlDbType.VarChar)
Param_banner_layout.Direction = ParameterDirection.Input
Param_banner_layout.Value = banner_layout
InsertCommand.Parameters.Add(Param_banner_layout)
Param_banner_layout = Nothing
Dim Param_activeBanners = New SqlParameter("#activeBanners", SqlDbType.VarChar)
Param_activeBanners.Direction = ParameterDirection.Input
Param_activeBanners.Value = ""
InsertCommand.Parameters.Add(Param_activeBanners)
Param_activeBanners = Nothing
Dim Param_banner_width = New SqlParameter("#banner_width", SqlDbType.Int)
Param_banner_width.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_banner_width)
Dim Param_banner_height = New SqlParameter("#banner_height", SqlDbType.Int)
Param_banner_height.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_banner_height)
Dim Param_campaign_id = New SqlParameter("#campaign_id", SqlDbType.Int)
Param_campaign_id.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_campaign_id)
Dim Param_imp_id = New SqlParameter("#imp_id", SqlDbType.Int)
Param_imp_id.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_imp_id)
Dim Param_banner_url = New SqlParameter("#banner_url", SqlDbType.VarChar, 500)
Param_banner_url.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_banner_url)
Dim Param_banner_img = New SqlParameter("#banner_img", SqlDbType.VarChar, 100)
Param_banner_img.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_banner_img)
Dim Param_banner_text = New SqlParameter("#banner_text", SqlDbType.VarChar, 1000)
Param_banner_text.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_banner_text)
Dim Param_banner_script = New SqlParameter("#banner_script", SqlDbType.VarChar, 2000)
Param_banner_script.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_banner_script)
Dim Param_banner_ID = New SqlParameter("#banner_ID", SqlDbType.Int)
Param_banner_ID.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(Param_banner_ID)
Dim param_adv_name_script = New SqlParameter("#adv_name", SqlDbType.VarChar, 2000)
param_adv_name_script.Direction = ParameterDirection.Output
InsertCommand.Parameters.Add(param_adv_name_script)
InsertCommand.ExecuteNonQuery()
Dim ActiveBanner As String = ""
Dim banner_height As Integer
Dim campaign_id As Integer
Dim imp_id As Integer
Dim banner_url As String
Dim banner_img As String
Dim banner_text As String
Dim banner_script As String
Dim banner_ID As Integer
Dim banner_width As String
'ActiveBanner = Param_activeBanners.Value()
banner_width = Param_banner_width.Value()
banner_height = Param_banner_height.Value()
If (Not IsDBNull(Param_campaign_id.Value())) Then
campaign_id = Convert.ToInt16(Param_campaign_id.Value())
End If
If (Not IsDBNull(Param_imp_id.Value())) Then
imp_id = Convert.ToInt16(Param_imp_id.Value())
End If
banner_url = Param_banner_url.Value()
banner_img = Param_banner_img.Value()
banner_text = Param_banner_text.Value()
banner_script = Param_banner_script.Value()
banner_ID = Param_banner_ID.Value()
ConnectionToFetch.Close()
ConnectionToFetch = Nothing
Param_banner_width = Nothing
Param_banner_height = Nothing
Param_campaign_id = Nothing
Param_imp_id = Nothing
Param_banner_url = Nothing
Param_banner_img = Nothing
Param_banner_text = Nothing
Param_banner_script = Nothing
Param_banner_ID = Nothing
param_adv_name_script = Nothing
If imp_page_link = "" Then
imp_page_link = " "
End If
'Dim x As Integer = parameters(9).Value
If String.IsNullOrEmpty(campaign_id) Then
campaign_id = -1
End If
If IsNothing(campaign_id) Then
campaign_id = -1
End If
If campaign_id < 1 Then 'If CInt("0" & param_campaign_id.value) < 1 Then
Return "<!-- log name='campNull' value='" & campaign_id & "' -->"
End If
If ActiveBanner = "" Then
ActiveBanner = banner_ID
ElseIf InStr("," & ActiveBanner & ",", "," & banner_ID & ",") < 1 Then
ActiveBanner = banner_ID & "," & ActiveBanner
End If
Dim strRet As String
'If request.QueryString("ads") = 1 Then
'Response.Write(" SessionID:" & Session.SessionID & " " & " disp_custom_banner " & campaign_id & "," & banner_ID & "," & adv_id & " Country=" & gCountry & " Banner=" & adv_name & " IP=" & request.ServerVariables("Remote_host"))
' End If
Dim strbuilder As New StringBuilder
If ShowAdsInfo = 1 Then
strbuilder.Append("disp_custom_banner " & campaign_id & "," & banner_ID & "," & " Country=" & imp_country & ", Banner=" & param_adv_name_script.Value())
End If
strbuilder.Append("<!-- log banner=" & banner_ID & " activeBanners=" & ActiveBanner & " -->")
strbuilder.Append("<script language='javascript' defer=defer>AdvimgBanner=" & IIf(imp_id = Nothing, 0, imp_id) & ";</script>" & vbCr)
If Len(banner_script) > 5 Then
''''''''' added for counting issue
Dim tmtmp As String = Replace(DateTime.Now.ToShortTimeString(), "PM", "")
Dim tm As String = Replace(tmtmp, "AM", "")
tm = Replace(tm, ":", "")
'''''''''
Dim max, min, RandomNum
max = 10000
min = 1
RandomNum = CStr(Int((max - min + 1) * Rnd() + min))
RandomNum = RandomNum & "-" & banner_ID
Dim ReFactor As String = Replace(banner_script, "[timestamp]", RandomNum & tm)
strbuilder.Append(Replace(ReFactor, "&cacheburst=", "&cacheburst=" & RandomNum & tm))
Return strbuilder.ToString
End If
If InStr(LCase(banner_img), ".swf") > 0 Then
Dim url_str As String = HttpContext.Current.Server.UrlEncode("http://www.xxx.com/includes/bannerhits.asp?campaign_id=" & campaign_id & "&imp_id=" & imp_id & "&URL=" & HttpContext.Current.Server.UrlEncode(banner_url))
Dim banner_str As String = "<A HREF=/includes/in_banner_hits.asp?campaign_id=" & campaign_id & "&imp_id=" & imp_id & "&URL=" & HttpContext.Current.Server.UrlEncode(banner_url) & " TARGET='_blank'>"
Dim bannersrc As String = "/updates/banners/" & banner_img
Dim concatEmbedID As String = "CAMP" & campaign_id
Dim DivNameID As String = "flashbanner" & banner_layout
Dim bannerhit As String = "http://www.xxx.com/includes/bannerhits.asp?campaign_id=" & campaign_id & "&imp_id=" & imp_id & "&URL=" & banner_url
bannerhit = HttpContext.Current.Server.UrlEncode(bannerhit)
strbuilder.Append("<div id='<%=DivNameID%>'>")
strbuilder.Append("<a href='http://www.adobe.com/go/getflashplayer'>")
strbuilder.Append("<img src='http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' border='0' /></a></div>")
strbuilder.Append("<script type='text/javascript' src='/includes/scripts/swfobject.js' ></script>")
strbuilder.Append("<script type='text/javascript' >")
strbuilder.Append("var so = new SWFObject(" + bannersrc + ", " + DivNameID + "," + banner_width + ", " + banner_height + ", ""6"", ""#ffffff"");")
strbuilder.Append("so.addParam(""quality"", ""autohigh "");")
strbuilder.Append("so.addParam(""bgcolor"", ""#ffffff"");")
strbuilder.Append("so.addParam(""swliveconnect"", ""false"");")
strbuilder.Append("so.addParam(""wmode"", ""transparent"");")
strbuilder.Append("so.addVariable(""clickTAG""," + bannerhit + ");")
strbuilder.Append("so.write(" + DivNameID + ");")
strbuilder.Append("</SCRIPT>")
Else
strbuilder.Append("<A HREF=/includes/in_banner_hits.asp?campaign_id=" & campaign_id & "&imp_id=" & imp_id & "&URL=" & HttpContext.Current.Server.UrlEncode(banner_url) & " TARGET='_blank'>" & _
" <IMG SRC='/updates/banners/" & banner_img & "' WIDTH='" & banner_width & "' HEIGHT='" & banner_height & "' BORDER='0' ALT='" & banner_text & "' vspace='5'></A>")
'response.write(banner_str)
End If
If Err.Number <> 0 Then
strbuilder.Append("<!--log name='err' value='" & Err.Description & _
"' Source='" & Err.Source & "' Number='" & Err.Number & "'-->")
End If
InsertCommand = Nothing
Dim strReturn As String = strbuilder.ToString
strbuilder = Nothing
Return strReturn
Catch ex As Exception
End Try
End Function
End Class
In short: You should create,open,use,close,dispose Connections where you're using them.
The best way is to use the using-statement. By not closing the connection as soon as possible, the Connection-Pool needs to create new physical connections to the dbms which is very expensive in terms of perfomance.
Using conn As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString)
Using insertCommand As New SqlClient.SqlCommand("disp_banner_byPageName_views", conn)
insertCommand.CommandType = CommandType.StoredProcedure
' ....
End Using
End Using
Performance problems are the least you get when not closing connections properly.
Edit: I've overlooked the ConnectionToFetch.Close in the middle of the code.
But anyway, you should use using or the finally of a try/catch to close a connection, otherwise it'll keep open in case of any exceptions. Because you've already a try/catch you could use it to close it in it's finally block.
I don't want to nag even more, but an empty catch is bad, because you'll never know when an exception was raised. You might want to log or at least throw it again there to catch it in Application_Error and/or in a custom error page or at the caller of this method.
Try
' code here
Catch ex As Exception
' log exception and/or throw(what is always better than to intercept it)
Throw
Finally
ConnectionToFetch.Close
End Try

Resources