SQL varbinay(max) column not saving image - asp.net

I have a problem saving an image from ASP.NET webforms showing data in SQL Server database table
0x000
My code to save the image in ASP.NET page is:
Dim Stream As IO.Stream
Dim FileLen As Integer
Dim FileOK As Boolean = False
Dim dt As New Data.DataTable
Dim SqlStr As String = String.Empty
If FileUpload1.HasFile Then
Dim FileExtension As String, FileSize As Integer, Height As Integer, Width As Integer
FileSize = FileUpload1.FileBytes.Count() / 1024
FileExtension = IO.Path.GetExtension(FileUpload1.FileName).ToLower()
Dim Img As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
Height = Img.Height
Width = Img.Width
If FileSize <= 100 Then
If Width <= 700 AndAlso Height <= 500 Then
If FileExtension = ".jpg" Or FileExtension = ".png" Or FileExtension = ".jpeg" Then
FileOK = True
Else
FileOK = False
End If
If FileOK Then
FileLen = FileUpload1.PostedFile.ContentLength
Dim fltp As String = FileUpload1.PostedFile.ContentType
Dim MyData(FileLen) As Byte
Stream = FileUpload1.FileContent
Stream.Read(MyData, 0, FileLen)
Dim decfileparameter As New Data.SqlClient.SqlParameter("#ImgBinary", Data.SqlDbType.Binary)
decfileparameter.Value = MyData
Dim Action As Integer = 1
SqlStr = "SaveUpdateSubServicesToMaster '" & Action & "','" & ddServiceTypeName.SelectedValue & "','" & TxtSubServiceName.Text & "','" & TxtPriceB4Txt.Text & "','" & TxtBasicPrice.Text & "','" & TxtAfterPrice.Text & "','" & TxtAboutSrvc.Text & "','" & TxtTrunTime.Text & "','" & TxtFinalBill.Text & "','" & TxtDuration.Text & "','" & DDIsSerAvl.SelectedValue & "','0',#ImgBinary"
Dim sqlConnString As String = Web.Configuration.WebConfigurationManager.ConnectionStrings("NewSHCService").ConnectionString
Dim con As New Data.SqlClient.SqlConnection(sqlConnString)
Dim sqlcmd As New Data.SqlClient.SqlCommand(SqlStr, con)
sqlcmd.Parameters.Add(decfileparameter)
con.Open()
Using sdr As Data.SqlClient.SqlDataReader = sqlcmd.ExecuteReader()
dt.Load(sdr)
End Using
con.Close()
as when storing data trough stored procedure taking varbinary(max) to insert data into table.
But it is not saving the image.
When I directly store image through
UPDATE dbo.ServiceSubTypeMaster
SET ServiceSubTypeImage = (SELECT BulkColumn
FROM OPENROWSET(BULK 'C:\Users\TanDev\Desktop\Imgs_New_Shc_Services\SameSize\134.jpg', SINGLE_BLOB) AS X)
WHERE ServiceSubTypeID = 137
it's showing image properly.

Related

value of type 1-dimensional array cannot be converted to string visual

In this threat help me with the each row ( Make a for each using SqlDataReader vb.net)
But when i wanna save the data ( on GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater, lot)
the varibles od the arrarys mater and lot show the error : value of type 1-dimensional array cannot be converted to string
Dim mater() As String
Dim planta() As String
Dim almacen() As String
Dim lot() As String
Dim cantidad() As String
Dim cantadiat() As String
Dim undad() As String
Dim Cantidadc() As String
Dim CantidadB() As String
Dim Session1() As String
Dim fecha() As String
Dim RowCounter As Integer = 0
RowCounter.ToString()
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
'Dim editCustQuery As String = "select Idmaterial , IdLote from s_RptInventarioSAP where idPlanta = '" & cboPlanta0.SelectedValue & "' and IdAlmacen = '" & cboAlmacen.SelectedValue & "'"
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Dim CustCommand As New SqlCommand(editCustQuery, Con34)
Dim sqladapter As SqlDataAdapter = New SqlDataAdapter(CustCommand)
Dim tableresult As New DataTable(editCustQuery)
sqladapter.Fill(tableresult)
Con34.Close()
For Each TableRow As DataRow In tableresult.Rows
mater = tableresult.Rows.Item(RowCounter).Item(0)
planta = tableresult.Rows.Item(RowCounter).Item(1)
almacen = tableresult.Rows.Item(RowCounter).Item(2)
lot = tableresult.Rows.Item(RowCounter).Item(3)
cantidad = tableresult.Rows.Item(RowCounter).Item(4)
cantadiat = tableresult.Rows.Item(RowCounter).Item(5)
undad = tableresult.Rows.Item(RowCounter).Item(6)
Cantidadc = tableresult.Rows.Item(RowCounter).Item(7)
CantidadB = tableresult.Rows.Item(RowCounter).Item(8)
Session1 = tableresult.Rows.Item(RowCounter).Item(9)
fecha = tableresult.Rows.Item(RowCounter).Item(10)
RowCounter = RowCounter + 1
Next
Dim resultado As String
resultado = GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater, lot)
'i = i + 1
With lbError0
.Visible = True
.Text = resultado
End With
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
Ok I see a couple errors.
Dim mater() As String
Dim planta() As String
Dim almacen() As String
Dim lot() As String
Dim cantidad() As String
Dim cantadiat() As String
Dim undad() As String
Dim Cantidadc() As String
Dim CantidadB() As String
Dim Session1() As String
Dim fecha() As String
Dim resultado() As String
Dim RowCounter As Integer = 0
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
'Dim editCustQuery As String = "select Idmaterial , IdLote from s_RptInventarioSAP where idPlanta = '" & cboPlanta0.SelectedValue & "' and IdAlmacen = '" & cboAlmacen.SelectedValue & "'"
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Dim CustCommand As New SqlCommand(editCustQuery, Con34)
Dim sqladapter As SqlDataAdapter = New SqlDataAdapter(CustCommand)
Dim tableresult As New DataTable(editCustQuery)
sqladapter.Fill(tableresult)
Con34.Close()
For Each TableRow As DataRow In tableresult.Rows
mater(RowCounter) = tableresult.Rows.Item(RowCounter).Item(0).toString
planta(RowCounter) = tableresult.Rows.Item(RowCounter).Item(1).toString
almacen(RowCounter) = tableresult.Rows.Item(RowCounter).Item(2).toString
lot(RowCounter) = tableresult.Rows.Item(RowCounter).Item(3).toString
cantidad(RowCounter) = tableresult.Rows.Item(RowCounter).Item(4).toString
cantadiat(RowCounter) = tableresult.Rows.Item(RowCounter).Item(5).toString
undad(RowCounter) = tableresult.Rows.Item(RowCounter).Item(6).toString
Cantidadc(RowCounter) = tableresult.Rows.Item(RowCounter).Item(7).toString
CantidadB(RowCounter) = tableresult.Rows.Item(RowCounter).Item(8).toString
Session1(RowCounter) = tableresult.Rows.Item(RowCounter).Item(9).toString
fecha(RowCounter) = tableresult.Rows.Item(RowCounter).Item(10).toString
resultado(RowCounter) = GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater(RowCounter), lot(RowCounter))
RowCounter = RowCounter + 1
Next
'i = i + 1
With lbError0
.Visible = True
.Text = resultado
End With
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
Ok this should work but there is something I don't understand you are displaying the result in a textbox I presume. but here is the trick. As I answer on the previous thread, the variable mater and lot are arrays, you can not call mater or lot directly. You have to specify what item of the array. With the modifications I did, resultado is another array so you can not call it directly you have to specify the item resultado().
I need more information what you will do with resultado.
For Each TableRow3 In tableresult3.Rows
mater3 = tableresult3.Rows.Item(RowCounter3).Item(0).ToString
lote3 = tableresult3.Rows.Item(RowCounter3).Item(1).ToString
Dim Con5 As New Data.SqlClient.SqlConnection
Dim StrSQL4 As String
Con5.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
StrSQL4 = "EXEC P_AsigDupla2 '" & Txtfecha.Text & "', '" & cboPlanta0.SelectedValue & "', '" & cboPlanta0.SelectedItem.Text & "', '" & cboAlmacen.SelectedValue & "', '" & cboAlmacen.SelectedItem.Text & "', '" & mater3 & "', '" & lote3 & "', '" & tbDupla.Text.ToUpper & "','" & estatus & "'"
Con5.Open()
Dim CmdAd As New Data.SqlClient.SqlCommand(StrSQL4, Con5)
CmdAd.ExecuteNonQuery()
Con5.Close()
RowCounter3 = RowCounter3 + 1

oleDbexception was unhandled by user code

I cannot see the added data in the data table when debugging starts it doesn't have any error but when I click button1 it shows me errors (unhandled by user code) unclosed quotation mark after the character string ')'
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As OleDbConnection
Dim strInsert As String
Dim cmdInsert As OleDbCommand
Dim vt As Byte, vm As Byte
Dim sze As Byte
con = New OleDbConnection("Integrated Security=SSPI;Packet Size=4096;Data Source=.;Tag with column collation when possible=False;Initial Catalog=borjara;Use Procedure for Prepare=1;Auto Translate=True;Persist Security Info=False;Provider=SQLOLEDB.1;Workstation ID=ABDI;Use Encryption for Data=False")
If RadioButton4.Checked = True Then vt = 0
If RadioButton5.Checked = True Then vt = 1
If RadioButton6.Checked = True Then vm = 0
If RadioButton7.Checked = True Then vm = 1
If RadioButton8.Checked = True Then vm = 2
If RadioButton9.Checked = True Then szs = 1
If RadioButton10.Checked = True Then szs = 0
con.Open()
strInsert = "insert Into t1(jens) Values (" & DropDownList1.SelectedItem.Text & "')"
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()//error is here
con.Close()
con.Open()
strInsert = "insert Into t1(bazsho) Values (" & DropDownList2.SelectedItem.Text & "')"
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()
con.Close()
con.Open()
strInsert = "insert Into t1(name and lastname,email,number,address,lenght,wideth,turi,glasstype,glass) Values (" & n & ",'" & TextBox1.Text(+" / " + TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "'," & vt & "," & vm & "," & szs & "')")
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()
con.Close()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
End Sub
End Class
It looks like there is no opening quote in the values of the first two Inserts.

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

I'm trying to insert info into two tables on a single btnclick. Its writing to only one table still. Can't see what I'm missing. [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If (Not Page.IsPostBack) Then
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("databob.mdb")
Dim strSQLCommand As String
strSQLCommand = "SELECT Customers.* FROM Customers ORDER BY Customers.CustomerID DESC;"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
End If
If (Not Page.IsPostBack) Then
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("databob.mdb")
Dim strSQLCommand2 As String
strSQLCommand2 = "SELECT CardType, CardNumber, Valid, Expiry, 3Digit FROM Orders ORDER BY Orders.OrderID DESC;"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand2, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
End If
End Sub
Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim strFirstName As String
Dim strLastName As String
Dim strAddress As String
Dim strPostcode As String
Dim strHomeNo As String
Dim strMobileNo As String
Dim strEmail As String
Dim strCardType As String
Dim strCardNumber As String
Dim strValid As String
Dim strExpiry As String
Dim str3Digit As String
strFirstName = tbxFirstName.Text
strLastName = tbxLastName.Text
strAddress = tbxAddress.Text
strPostcode = tbxPostcode.Text
strHomeNo = tbxHomeNo.Text
strMobileNo = tbxMobileNo.Text
strEmail = tbxEmail.Text
strCardType = ddlCardType.Text
strCardNumber = tbxCardNumber.Text
strValid = tbxValid.Text
strExpiry = tbxExpiry.Text
str3Digit = tbx3Digit.Text
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("databob.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Customers(FirstName, LastName, Address, Postcode, HomeNo, MobileNo, Email) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strAddress & "', '" & strPostcode & "', '" & strHomeNo & "', '" & strMobileNo & "', '" & strEmail & "');"
Dim strSQLCommand2 As String
strSQLCommand2 = "INSERT INTO Orders(CardType, CardNumber, Valid, Expiry, 3Digit) " & _
"Values ('" & strCardType & "', '" & strCardNumber & "', '" & strValid & "', '" & strExpiry & "', '" & str3Digit & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "SELECT Customers.* FROM Customers ORDER BY Customers.CustomerID DESC;"
strSQLCommand2 = "SELECT Orders.* FROM Orders ORDER BY Orders.OrderID DESC;"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
tbxFirstName.Text = ""
tbxLastName.Text = ""
tbxAddress.Text = ""
tbxPostcode.Text = ""
tbxHomeNo.Text = ""
tbxMobileNo.Text = ""
tbxEmail.Text = ""
ddlCardType.Text = ""
tbxCardNumber.Text = ""
tbxValid.Text = ""
tbxExpiry.Text = ""
tbx3Digit.Text = ""
End Sub
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
That executes the first one but you do not do it again for strSQLCommand2
-- as an aside please look into parameterization of your queries. You are just asking for sql injection with that.
INSERT INTO Orders(Orders( looks a tad fishy to me (unless that's a C&P error posting this question)
And as Ken points out, if you're wanting to run both queries (rather than replace one with the other), you probably want:
strSQLCommand = strSQLCommand & " INSERT INTO Orders(CardType, CardNumber, Valid, Expiry, 3Digit) " & _
Your problem is that you are trying to use same string variable to hold both sqls, in fact you are overwriting the first one with the second one, modify your code like this
Dim strSQLCommand As String
Dim strSQLCommand2 As String
strSQLCommand = "INSERT INTO Customers(FirstName, LastName, Address, Postcode, HomeNo, MobileNo, Email) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strAddress & "', '" & strPostcode & "', '" & strHomeNo & "', '" & strMobileNo & "', '" & strEmail & "');"
strSQLCommand2 = "INSERT INTO Orders(Orders(CardType, CardNumber, Valid, Expiry, 3Digit) " & _
"Values ('" & strCardType & "', '" & strCardNumber & "', '" & strValid & "', '" & strExpiry & "');"
and then afterwards you need to execute both statements, also you should add a transaction, something like this
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objTrans As System.Data.OleDb.OleDbTransaction;
objTrans=objOleDbConnection.BeginTransaction();
try
{
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbCommand.CommandText =strSQLCommand2;
objOleDbCommand.ExecuteNonQuery()
objTrans.Commit();
}
catch{Exception ex}
{
objTrans.Rollback();
}
finally
{
objOleDbConnection.Close()
}
Just pulling it out of my head, can be a typo on it, but you can get the idea

Insert into Access DB (loop)

I have this code and its coming up with an INSERT INTO statement error...
Its probably something but I have been at it for a while... please help.
'Add items to db'
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')"
myCommand2.Connection = con2
con2.Open()
myCommand2.ExecuteReader()
con2.Close()
test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" "
Next
End Function
I think you are getting an error by not enclosing the Date inside Pound signs. You have to do this in Jet (Access) when using variables not parameters.
VALUES('#" & DateTime.Now.Date & "#',...
I also took the liberty of refactoring this code for you since you are creating a new connection for each record which is bad news. Use a Try Catch Finally block and move all that stuff outside the For Loop (please see below)
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" <-- etc
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.Connection = con2
con2.Open()
Try
For intCounter = 0 To obDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _
& "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _
& "','" & Int32.Parse(objDR("quantity")) & "')"
myCommand2.ExecuteReader()
Next
Catch ex As Exception
'handle errors here
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
Remember to mark as answered if this helps.
I've sorted it out by removing the single quotes. Thanks everybody to contributed to this.

Resources