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
Related
My function needs to read an MS Word doc, replace some text, and then SAVE AS PDF.
Reading and saving PDF works great.
But I can't figure out how to replace text by using Word Object Model.
Here is my word_to_PDF() function which does it all.
Function word_to_PDF(Word_source_filepath, PDF_destin_filepath)
Dim wordApplication As ApplicationClass = New ApplicationClass()
Dim wordDocument As Document = Nothing
Dim paramExportFilePath As String = PDF_destin_filepath
Dim paramExportFormat As WdExportFormat = _
WdExportFormat.wdExportFormatPDF
Dim paramOpenAfterExport As Boolean = False
Dim paramExportOptimizeFor As WdExportOptimizeFor = _
WdExportOptimizeFor.wdExportOptimizeForPrint
Dim paramExportRange As WdExportRange = _
WdExportRange.wdExportAllDocument
Dim paramStartPage As Int32 = 0
Dim paramEndPage As Int32 = 0
Dim paramExportItem As WdExportItem = _
WdExportItem.wdExportDocumentContent
Dim paramIncludeDocProps As Boolean = True
Dim paramKeepIRM As Boolean = True
Dim paramCreateBookmarks As WdExportCreateBookmarks = _
WdExportCreateBookmarks.wdExportCreateWordBookmarks
Dim paramDocStructureTags As Boolean = True
Dim paramBitmapMissingFonts As Boolean = True
Dim paramUseISO19005_1 As Boolean = False
' Open the source document.
On Error Resume Next
wordDocument = wordApplication.Documents.Open(Word_source_filepath) ' Microsoft.Office.Interop.Word.Document
If Err.Number Then
Debug.WriteLine(Err.Description)
log_fault("word_to_PDF: Err# " & Err.Number & " " & Err.Description)
Stop '!!!
Else
' Export it in the specified format.
If Not wordDocument Is Nothing Then
Dim FindObject As wordDocument.Find = Application.Selection.Find <<<<<<<<<<<<<<< THIS GETS ERROR: "wordDocument.Find is not defined"
With FindObject
.ClearFormatting()
.Text = "find me"
.Replacement.ClearFormatting()
.Replacement.Text = "Found"
.Execute(Replace:=Word.WdReplace.wdReplaceAll)
End With
wordDocument.ExportAsFixedFormat(paramExportFilePath, _
paramExportFormat, paramOpenAfterExport, _
paramExportOptimizeFor, paramExportRange, paramStartPage, _
paramEndPage, paramExportItem, paramIncludeDocProps, _
paramKeepIRM, paramCreateBookmarks, _
paramDocStructureTags, paramBitmapMissingFonts, _
paramUseISO19005_1)
Else
'!!! ERR
stop_if_debug()
End If
End If
' Close and release the Document object:
If Not wordDocument Is Nothing Then
wordDocument.Close(False)
wordDocument = Nothing
End If
' Quit Word and release the ApplicationClass object.
If Not wordApplication Is Nothing Then
wordApplication.Quit()
wordApplication = Nothing
End If
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
Return True
Change your wordDocument.Find to just Word.Find.
Find is an interface on the Word namespace but not an object on the instanced class.
Here's some msdn documentation about what you are trying to do:
http://msdn.microsoft.com/en-us/library/f1f367bx.aspx
What's in the Word namespace
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word%28v=office.14%29.aspx
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;
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
This is a sample of my code. I am using Microsoft Visual Studio 2010, with asp.net version 2.0, when the user clicks the import button, the csv file will be saved in the database. My code contains errors, and I do not know how to solve them, please help!
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
StreamReader Sr = new StreamReader("filepath");
string line;
while ((line = Sr.ReadLine()) != null)
{
line = Sr.ReadLine();
}
const string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", Sr);
cmd.Parameters.AddWithValue("#IC_Number", Sr);
cmd.Parameters.AddWithValue("#EventName", Sr);
cmd.Parameters.AddWithValue("#GuestID", Sr);
con.Open();
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
con.Close();
}
Your insert query must be in your while
Sr is not your parameter, but line which contains an array of your data. So it is probably line[i] that you must give to AddWithValue
You are assigning line = Sr.ReadLine() twice in your code, just do it in the while
So try something like this:
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
con.Open();
StreamReader Sr = new StreamReader("filepath");
string line;
string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
while ((line = Sr.ReadLine()) != null)
{
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", line[0]);
cmd.Parameters.AddWithValue("#IC_Number", line[1]);
cmd.Parameters.AddWithValue("#EventName", line[2]);
cmd.Parameters.AddWithValue("#GuestID", line[3]);
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
}
con.Close();
}
i have done something like this however it was xls files i needed to import but not much differentce really, here is the code i used
Protected Sub ButtonImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonImport.Click
PanelView.Visible = False
PanelUpload.Visible = False
PanelImport.Visible = True
LabelImport.Text = "" 'reset to blank
Dim xConnstr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & (Server.MapPath("SiteTemplate.xls")) & ";" & _
"Extended Properties=Excel 8.0"
' create your excel connection object using the connection string
Dim objXConn As New System.Data.OleDb.OleDbConnection(xConnstr)
objXConn.Open()
Dim objCommand As New OleDbCommand("SELECT * FROM [importsites$]", objXConn)
'Creating the data reader
Dim reader As OleDbDataReader
reader = objCommand.ExecuteReader()
Dim counter As Integer = 0
While reader.Read()
counter = counter + 1
Dim siteID As Integer = 0
Dim siteIWSref As String = Convert.ToString(reader("siteIWSref"))
If siteIWSref = "" Then
siteIWSref = "."
End If
Dim siteUPRN As String = Convert.ToString(reader("siteUPRN"))
If siteUPRN = "" Then
siteUPRN = "."
End If
Dim siteName As String = Convert.ToString(reader("siteName"))
Dim siteAdd1 As String = Convert.ToString(reader("siteAdd1"))
Dim siteAdd2 As String = Convert.ToString(reader("siteAdd2"))
Dim siteAdd3 As String = Convert.ToString(reader("siteAdd3"))
Dim sitePcode As String = Convert.ToString(reader("sitePcode"))
Dim siteContact As String = Convert.ToString(reader("siteContact"))
Dim siteContactPos As String = Convert.ToString(reader("siteContactPos"))
Dim siteContactTel As String = Convert.ToString(reader("siteContactTel"))
Dim siteDesc As String = Convert.ToString(reader("siteDesc"))
Dim siteCompany As Integer = CInt(CompanyDD.SelectedValue)
Dim siteOccupants As String = Convert.ToString(reader("siteOccupants"))
Dim siteType As String = Convert.ToString(reader("siteType"))
siteID = ImportIntotblSite(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType)
LabelImport.Text &= siteID & siteIWSref & " " & siteUPRN & " " & siteName & " " & siteAdd1 & " " & siteAdd2 & " " & siteAdd3 & " " & " " & sitePcode & " " & siteContact & " " & siteContactPos & " " & siteContactTel & " " & siteDesc & " " & siteCompany & " " & siteOccupants & " " & " " & siteType & "<br>"
End While
reader.Close()
objCommand.Dispose()
objXConn.Close()
btnBack.Enabled = True
btnBack.Visible = True
btnSave.Visible = True
btnSave.Enabled = True
End Sub
Protected Function ImportIntotblSite(ByVal siteIWSref As String, ByVal siteUPRN As String, ByVal siteName As String, ByVal siteAdd1 As String, ByVal siteAdd2 As String, ByVal siteAdd3 As String, ByVal sitePcode As String, ByVal siteContact As String, ByVal siteContactPos As String, ByVal siteContactTel As String, ByVal siteDesc As String, ByVal siteCompany As Integer, ByVal siteOccupants As String, ByVal siteType As String) As Integer
siteIWSref = Left(siteIWSref, 20)
siteUPRN = Left(siteUPRN, 20)
siteName = Left(siteName, 60)
siteAdd1 = Left(siteAdd1, 50)
siteAdd2 = Left(siteAdd2, 50)
siteAdd3 = Left(siteAdd3, 50)
sitePcode = Left(sitePcode, 10)
siteContact = Left(siteContact, 35)
siteContactPos = Left(siteContactPos, 35)
siteContactTel = Left(siteContactTel, 20)
siteDesc = Left(siteDesc, 220)
siteOccupants = Left(siteOccupants, 120)
siteType = Left(siteType, 35)
Dim siteID As Integer = 0
Try
Dim SSAdapter As New importSitesDataSetTableAdapters.tblSiteTableAdapter
Dim SSDataTable As importSitesDataSet.tblSiteDataTable = Nothing
SSDataTable = SSAdapter.GetDataByNumbers(siteIWSref, siteName, siteCompany)
If siteName = "" Then
siteName = ""
End If
'see if the category already exists in the table, if not insert it
If Not SSDataTable Is Nothing Then
If siteName = "" Then
LabelImport.Text = LabelImport.Text & _
"<font color=red>ERROR: BLANK SITE NAME: ROW NOT IMPORTED : " & _
"ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
ElseIf SSDataTable.Rows.Count > 0 Then
If Not SSDataTable(0).siteID = Nothing Then
siteID = SSDataTable(0).siteID
LabelImport.Text = LabelImport.Text & _
"<font color=blue> Recorded already exists : " & _
"ID: " & siteID & _
"Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
End If
End If
If siteID = 0 And siteName <> "" Then
siteID = Convert.ToInt32(SSAdapter.InsertQuery(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType))
LabelImport.Text = LabelImport.Text & _
"<font color=green> ROW SUCCESSFULLY IMPORTED: " & _
" ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
Return siteID
'SSAdapter.Dispose()
Catch ex As Exception
LabelImport.Text = LabelImport.Text & "<font color=red>" & ex.ToString & ".</font><br>"
Return 0
End Try
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'TableButtons.Visible = False
'FileUploadExcel.Visible = False
'PanelUpload.Visible = False
btnYes.Visible = False
btnNo.Visible = False
btnBack.Enabled = False
btnBack.Visible = False
ButtonView.Enabled = False
ButtonImport.Enabled = False
btnSave.Visible = False
btnSave.Enabled = False
End Sub
try this and let me know how you get on.
there is a brilliant example of how to upload information onto an sql server at:
http://www.shiningstar.net/aspnet_articles/DataSet/DataSetProject.aspx
i am aware its for excel however surely there cant be that much difference.
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.