Invalid Cast Exception with Update Panel - asp.net

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;

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

Why I get SQL error message based on Div color style?

I was verify if the boolean is True or False. If it false, it will change the server Name text to color red, if True, it doesn't change color. The SQL was able to read server Name that doesn't change text color but couldn't read the server Name colored red text and got SQL error message,
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'red'.
Here is the VB code:
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim strSqlSecondary As String = "SELECT [Name], [Compliance] FROM [dbo].[ServerOwners] where SecondaryOwner like #uid order by [name]"
Dim cmdSecondary As New System.Data.SqlClient.SqlCommand(strSqlSecondary, sqlConn)
cmdSecondary.Parameters.AddWithValue("#uid", TNN.NEAt.GetUserID())
Dim dr As System.Data.SqlClient.SqlDataReader
Try
sqlConn.Open()
Dim root As TreeNode
Dim rootNode As TreeNode
Dim firstNode As Integer = 0
'Load Primary Owner Node
'Create RootTreeNode
dr = cmdSecondary.ExecuteReader()
If dr.HasRows Then
'Load Secondary Owner Node
'Create RootTreeNode
root = New TreeNode("Secondary Owner", "Secondary Owner")
TreeViewGroups.Nodes.Add(root)
root.SelectAction = TreeNodeSelectAction.None
rootNode = TreeViewGroups.Nodes(firstNode)
'populate the child nodes
While dr.Read()
Dim child As TreeNode = New TreeNode(dr("Name"), dr("Name"))
Dim complianceFlag As Boolean
If Boolean.TryParse(dr("Compliance"), complianceFlag) Then
' Yes, compliance value is a Boolean, now set color based on value
If Not complianceFlag Then
child.Text = "<div style='color:red'>" + child.Text + "</div>"
End If
End If
rootNode.ChildNodes.Add(child)
child.SelectAction = TreeNodeSelectAction.None
End While
dr.Close()
The error came from this line code because it read "red":
child.Text = "<div style='color:red'>" + child.Text + "</div>"
The child node text is passing when I click link to update,
Protected Sub LinkButtonConfirm_Click(sender As Object, e As System.EventArgs) Handles LinkButtonConfirm.Click
hide()
PanelCompliance.Visible = True
PanelDisplayGrid.Visible = True
'display the servers
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim strSql As New StringBuilder
strSql.Append("Select [Name] , [ApplicationName] , [Environment], [Description], [TechMgmtTeam] , [PrimaryOwner], [PPhone], [SecondaryOwner], [SPhone], [Queue], [Crit] from dbo.ServerOwners where")
'Loops Through all Selected items and appends to sql statement
Dim x As Integer = 0
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth = 0 Then
Else
'append to select statement
strSql.Append(" [Name]='" & item.Text & "' or ")
x = x + 1
End If
Next
If x = 0 Then
hide()
LabelError.Text = "Please select at least one server in the left pane."
PanelError.Visible = True
Else
strSql.Append(" [Name]='Blank' order by [name]")
Try
sqlConn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand(strSql.ToString(), sqlConn)
Dim a As New SqlClient.SqlDataAdapter(cmd)
Dim datTab As New DataTable
a.Fill(datTab)
Session("Table") = datTab
GridViewDisp.DataSource = datTab
GridViewDisp.DataBind()
Catch ex As Exception
hide()
LabelError.Text = ex.ToString()
PanelError.Visible = True
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End If
End Sub
If I get rid of Div tag, everything is work fine except there won't be colored red. How they able to read Div style which they should ignore the style and focus on child text. Is there a way to fix?
If you store the Name in the .Tag property of the child, you get to be able to use it regardless of what you do to the .Text of the child:
While dr.Read()
Dim myName as String = dr("Name")
Dim child As TreeNode = New TreeNode(myName , myName)
child.Tag = myName
Then in LinkButtonConfirm_Click
Dim x As Integer = 0
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth <> 0 Then
'append to select statement
strSql.Append(" [Name]='" & CStr(item.Tag) & "' or ")
x = x + 1
End If
Next
But you should still be adding the CStr(item.Tag) as SQL parameters. You already have a counter x in the loop which you can use to construct parameter names ("#p0", "#p1" etc.).
Edit: which would result in the Click handler looking something like
Protected Sub LinkButtonConfirm_Click(sender As Object, e As System.EventArgs) Handles LinkButtonConfirm.Click
hide()
PanelCompliance.Visible = True
PanelDisplayGrid.Visible = True
'display the servers
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim strSql As New StringBuilder
Dim qryBase = <sql>
SELECT [Name]
,[ApplicationName]
,[Environment]
,[Description]
,[TechMgmtTeam]
,[PrimaryOwner]
,[PPhone]
,[SecondaryOwner]
,[SPhone]
,[Queue]
,[Crit]
FROM dbo.ServerOwners
WHERE
</sql>.Value
strSql.Append(qryBase & " ")
'Loop through all Selected items and append to sql statement
Dim x As Integer = 0
Dim nLastCheckedNode As Integer = TreeViewGroups.CheckedNodes.Count - 1
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth <> 0 Then
'append to select statement
Dim paramName As String = "#p" & x.ToString()
strSql.Append("[Name] = " & paramName)
If x <> nLastCheckedNode Then
' we have another node to look at, so add " OR "
strSql.Append(" OR ")
End If
'TODO: set the correct SqlDbType and the correct .Size
cmd.Parameters.Add(New SqlParameter With {.ParameterName = paramName,
.SqlDbType = SqlDbType.NVarChar,
.Size = 20,
.Value = CStr(item.Tag)})
x += 1
End If
Next
If x = 0 Then
hide()
LabelError.Text = "Please select at least one server in the left pane."
PanelError.Visible = True
Else
strSql.Append(" ORDER BY [Name]")
Try
sqlConn.Open()
cmd.Connection = sqlConn
cmd.CommandText = strSql.tostring()
Dim a As New SqlClient.SqlDataAdapter(cmd)
Dim datTab As New DataTable
a.Fill(datTab)
Session("Table") = datTab
GridViewDisp.DataSource = datTab
GridViewDisp.DataBind()
Catch ex As Exception
hide()
LabelError.Text = ex.ToString()
PanelError.Visible = True
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End If
End Sub
#Andrew Morton - Your theory are correct about error in strSql.Append(" [Name]='" & item.Text & "' or ") in LinkButtonConfirm_Click. I changed to strSql.Append(" [Name]='" & item.Value & "' or ") by replacing Text to Value. Now everything worked!

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

update query syntax error in asp.net application

EDIT:
this issue has changed. HansUp solved this syntax issues with in the update statement. What is happening now is completely different. process is
user selects a gridview item
it redirects them to the update page and using a datareader, fills the text boxes and check boxes based on the id passed in the url
the user can then make their changes to the text boxes/ check boxes and then press the update button which runs the update query.
what i have found is happening is that although a user might change the text, when they submit the changes, the update query is still using whatever was loaded into that text box by the data reader on the page load. Here is the code below:
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdateBTN.Click
Dim tiresdim As Integer = 0
If TiresCHK.Checked = True Then
tiresdim = -1
ElseIf TiresCHK.Checked = False Then
tiresdim = 0
End If
Dim repairs As Integer = 0
If RepairsCheckBX.Checked = True Then
repairs = -1
ElseIf RepairsCheckBX.Checked = False Then
repairs = 0
End If
Dim onlotdim As Integer = 0
If OnLotCheckBX.Checked = True Then
onlotdim = -1
ElseIf OnLotCheckBX.Checked = False Then
onlotdim = 0
End If
Dim offpropdim As Integer = 0
If OffPropertyCheckBX.Checked = True Then
offpropdim = -1
ElseIf OffPropertyCheckBX.Checked = False Then
offpropdim = 0
End If
Dim soldim As Integer = 0
If SoldCheckBX.Checked = True Then
soldim = -1
ElseIf SoldCheckBX.Checked = False Then
soldim = 0
End If
Dim id = CType(Request.QueryString("param1"), Integer)
Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jason\Desktop\UsedCarProductionSched\app_data\UsedCars.accdb;Persist Security Info=False;")
Dim sql As String = "update Master set stocknum='" & StockNumTxt.Text & "',[year]='" & YearTxt.Text & "',make='" & MakeTxt.Text & "', model='" & ModelTxt.Text & "', color='" & ColorTxt.Text & "',location='" & LocationDropDownList.SelectedValue & "',tiresneeded=" & tiresdim & ",stockin=#" & StockInDateTxt.Text & "#,SvcRONum='" & SrvcROnumTxt.Text & "',ucistartdate=#" & UCIStartDateTxt.Text & "#,UCIEstCompleteDate=#" & UCIEstComDateTXT.Text & "#,repairs=" & repairs & ",CollisionRONum='" & CollisionRONumTXT.Text & "',[detail]=#" & DetailTXTbox.Text & "#, other='this has to work',onlot=" & onlotdim & ",offproperty=" & offpropdim & ",sold=" & soldim & " WHERE recnum=" & id
connection.Open()
Dim cmd As New OleDb.OleDbCommand(sql, connection)
cmd.ExecuteNonQuery()
connection.Close()
'Dim updateta As New DataSet1TableAdapters.Master1TableAdapter
'updateta.UpdateQuery(StockNumTxt.Text, YearTxt.Text, MakeTxt.Text, ModelTxt.Text, ColorTxt.Text, LocationDropDownList.SelectedValue, TiresCHK.Checked, StockInDateTxt.Text, SrvcROnumTxt.Text, UCIStartDateTxt.Text, UCIEstComDateTXT.Text, RepairsCheckBX.Checked, CollisionRONumTXT.Text, DetailTXTbox.Text, OtherTxt.Text, OnLotCheckBX.Checked, OffPropertyCheckBX.Checked, SoldCheckBX.Checked, Request.QueryString("param1"))
Response.Redirect("success.aspx")
End Sub
Function myCStr(ByVal test As Object) As String
If isdbnull(test) Then
Return ("")
Else
Return CStr(test)
End If
End Function
Public Shared Function IsDBNull( _
ByVal value As Object _
) As Boolean
Return DBNull.Value.Equals(value)
End Function
Private Sub getData(ByVal user As String)
'declare variables to fill
Dim stock As String, make As String, color As String, stockin As Date, ucistart As Date, repairs As Boolean, _
tires As Boolean, onlot As Boolean, sold As Boolean, year As Boolean, model As String, location As String, srvcRO As String, ucicompldate As Date, _
collRO As String, other As String, offprop As Boolean, detail As Date
Dim dt As New DataTable()
Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jason\Desktop\UsedCarProductionSched\app_data\UsedCars.accdb;Persist Security Info=False;")
connection.Open()
Dim sqlcmd As String = "SELECT * from Master WHERE RecNum = #recnum"
Dim FileCommand3 As New OleDb.OleDbCommand(sqlcmd, connection)
FileCommand3.Parameters.AddWithValue("#recnum", user)
Dim Reader3 As OleDb.OleDbDataReader = FileCommand3.ExecuteReader()
If Reader3.Read Then
stock = myCStr(Reader3("StockNum"))
make = myCStr(Reader3("Make"))
color = myCStr(Reader3("Color"))
stockin = IIf(Reader3("stockin") Is DBNull.Value, Nothing, Reader3("stockin"))
ucistart = IIf(Reader3("ucistartdate") Is DBNull.Value, Nothing, Reader3("ucistartdate"))
repairs = Reader3("Repairs")
tires = Reader3("tiresneeded")
onlot = Reader3("onlot")
sold = Reader3("sold")
year = myCStr(Reader3("year"))
model = myCStr(Reader3("model"))
location = myCStr(Reader3("location"))
srvcRO = myCStr(Reader3("svcROnum"))
ucicompldate = IIf(Reader3("uciestcompletedate") Is DBNull.Value, Nothing, Reader3("uciestcompletedate"))
collRO = myCStr(Reader3("collisionROnum"))
other = myCStr(Reader3("other"))
offprop = Reader3("offProperty")
detail = IIf(Reader3("detail") Is DBNull.Value, Nothing, Reader3("detail"))
End If
connection.Close()
If detail <> Nothing Then
DetailTXTbox.Text = detail.ToString("M/dd/yyyy")
Else : DetailTXTbox.Text = ""
End If
If ucicompldate <> Nothing Then
UCIEstComDateTXT.Text = ucicompldate.ToString("MM/dd/yyyy")
Else : UCIEstComDateTXT.Text = ""
End If
If stockin <> Nothing Then
StockInDateTxt.Text = stockin.ToString("MM/dd/yyyy")
Else : StockInDateTxt.Text = ""
End If
If ucistart <> Nothing Then
UCIStartDateTxt.Text = ucistart.ToString("M/dd/yyyy")
Else : UCIStartDateTxt.Text = ""
End If
StockNumTxt.Text = stock
MakeTxt.Text = make
ColorTxt.Text = color
RepairsCheckBX.Checked = repairs
TiresCHK.Checked = tires
OnLotCheckBX.Checked = onlot
SoldCheckBX.Checked = sold
YearTxt.Text = year
ModelTxt.Text = model
If location <> Nothing Then
LocationDropDownList.SelectedValue = location
End If
SrvcROnumTxt.Text = srvcRO
CollisionRONumTXT.Text = collRO
OtherTxt.Text = other
OffPropertyCheckBX.Checked = offprop
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
getData(Request.QueryString("param1"))
End Sub
My asp.net application is supposed to execute a simple update query against an access DB but instead it throws a syntax error. I have copy and pasted the exact query directly into my access DB and it executes properly. Here is the code:
Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jason\Desktop\UsedCarProductionSched\app_data\UsedCars.accdb;Persist Security Info=False;")
Dim sql As String = "update Master " _
+ "set stocknum='" & StockNumTxt.Text & "',year='" & YearTxt.Text & "',make='" & MakeTxt.Text & "', model='" & ModelTxt.Text & "', color='" & ColorTxt.Text & "',location='" & LocationDropDownList.SelectedValue & "',tiresneeded=" & tiresdim & ",stockin=#" & StockInDateTxt.Text & "#,SvcRONum='" & SrvcROnumTxt.Text & "',ucistartdate=#" & UCIStartDateTxt.Text & "#,UCIEstCompleteDate=#" & UCIEstComDateTXT.Text & "#,repairs=" & repairs & ",CollisionRONum='" & CollisionRONumTXT.Text & "',detail=#" & DetailTXTbox.Text & "#, other='" & OtherTxt.Text & "',onlot=" & onlotdim & ",offproperty=" & offpropdim & ",sold=" & soldim & " " _
+ "WHERE recnum=" & Request.QueryString("param1")
connection.Open()
Dim cmd As New OleDb.OleDbCommand(sql, connection)
cmd.ExecuteNonQuery()
connection.Close()
Two of your columns use reserved words as their names: year; detail. If you must keep those names, enclose them in square brackets in the UPDATE statement to avoid the possibility of confusing Access' database engine.
What data type is the year field? The finished statement in your comment includes year='True' And that's fine if "year" is text data type. But if it's a Yes/No field, lose the quotes from around the word True.
What is the syntax error? Also, you should be validating the input for the SQL before throwing that into the database update. If you have apostrophes in the text that will cause a problem. A parameterized query would be more ideal, too.
Sample for parameterized SQL operations, as suggested by SkinnyWhiteNinja
I have a table with 4 colunms, CollCode and CollSeq are the key, TermType and TermText are the modifiable data
The code explains how to insert, update or delete a row with parameters instaed if textvalues in the SQL.
The code is valid only for ACCESS, SQL SERVER or MYSQL require different code for the template and have different DbTypes
in the first part of the program:
' Insert
Dim DbConn As New OleDbConnection(SqlProv)
Dim SQLTwInsert As String = "INSERT INTO SearchTerms (CollCode, CollSeq, TermType, TermText) VALUES (?, ?, ?, ?)"
Dim DRTwInsert As OleDbDataReader = Nothing
Dim DCCTwInsert As OleDbCommand
Dim TwInsP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwInsP2 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwInsP3 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwInsP4 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
DCCTwInsert = New OleDbCommand(SQLTwInsert, DbConn)
DCCTwInsert.Parameters.Add(TwInsP1)
DCCTwInsert.Parameters.Add(TwInsP2)
DCCTwInsert.Parameters.Add(TwInsP3)
DCCTwInsert.Parameters.Add(TwInsP4)
' Delete
Dim SQLTwDelete As String = "DELETE FROM SearchTerms WHERE CollCode = ? AND CollSeq = ? AND TermType = ? AND TermText = ?"
Dim DRTwDelete As OleDbDataReader = Nothing
Dim DCCTwDelete As OleDbCommand
Dim TwDelP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwDelP2 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwDelP3 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwDelP4 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
DCCTwDelete = New OleDbCommand(SQLTwDelete, DbConn)
DCCTwDelete.Parameters.Add(TwDelP1)
DCCTwDelete.Parameters.Add(TwDelP2)
DCCTwDelete.Parameters.Add(TwDelP3)
DCCTwDelete.Parameters.Add(TwDelP4)
' Update
Dim SQLTwUpdate As String = "UPDATE SearchTerms SET TermType = ?, TermText = ? WHERE CollCode = ? AND CollSeq = ? AND TermType = ? AND TermText = ?"
Dim DRTwUpdate As OleDbDataReader = Nothing
Dim DCCTwUpdate As OleDbCommand
Dim TwUpdP1 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwUpdP2 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
Dim TwUpdP3 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwUpdP4 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwUpdP5 As New OleDbParameter("#oldTermType", OleDbType.VarChar, 4)
Dim TwUpdP6 As New OleDbParameter("#oldTermText", OleDbType.VarChar, 255)
DCCTwUpdate = New OleDbCommand(SQLTwUpdate, DbConn)
DCCTwUpdate.Parameters.Add(TwUpdP1)
DCCTwUpdate.Parameters.Add(TwUpdP2)
DCCTwUpdate.Parameters.Add(TwUpdP3)
DCCTwUpdate.Parameters.Add(TwUpdP4)
DCCTwUpdate.Parameters.Add(TwUpdP5)
DCCTwUpdate.Parameters.Add(TwUpdP6)
in the processing part of the program:
' Update
TwUpdP1.Value = new value TermType
TwUpdP2.Value = new value TermText
TwUpdP3.Value = key value CollCode
TwUpdP4.Value = key value CollSeq
TwUpdP5.Value = old value TermType to avoid updating a row that 1 millisecond earlier was modified by someone else
TwUpdP6.Value = old value TermText
Try
DRTwUpdate = DCCTwUpdate.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwUpdate Is Nothing) Then
DRTwUpdate.Dispose()
DRTwUpdate.Close()
End If
End Try
' Insert
TwInsP1.Value = new key value CollCode
TwInsP2.Value = new key value CollSeq
TwInsP3.Value = value TermType
TwInsP4.Value = value TermText
Try
DRTwInsert = DCCTwInsert.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwInsert Is Nothing) Then
DRTwInsert.Dispose()
DRTwInsert.Close()
End If
End Try
' Delete
TwDelP1.Value = key value CollCode
TwDelP2.Value = key value CollSeq
TwDelP3.Value = old value TermType to avoid deleting a row that 1 millisecond earlier was modified by someone else
TwDelP4.Value = old value TermText
Try
DRTwDelete = DCCTwDelete.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwDelete Is Nothing) Then
DRTwDelete.Dispose()
DRTwDelete.Close()
End If
End Try
Try it, it really avoids many problems, though a bit clumbsy to write it all.

Resources