Performance issue with this code [closed] - asp.net

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

Related

VB.net Input string was not in a correct format

Here is a picture of error
Keep Getting error
input string was not in correct format
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
My guess is the CInt but it works in another similar application . Not sure what is going on . Here is the code
product-detail.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Partial Class HTML_Product_Detail
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("ProductID") <> "" Then
Dim strConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
Dim connProduct As SqlConnection
Dim cmdProduct As SqlCommand
Dim drProduct As SqlDataReader
Dim strSQL As String = "Select * from Product Where ProductID = " & Request.QueryString("ProductID")
connProduct = New SqlConnection(strConn)
cmdProduct = New SqlCommand(strSQL, connProduct)
connProduct.Open()
drProduct = cmdProduct.ExecuteReader(CommandBehavior.CloseConnection)
'drProduct.Read()
If drProduct.Read() Then
lblProductName.Text = drProduct.Item("ProductName")
lblProductDescription.Text = drProduct.Item("ProductName")
lblPrice.Text = drProduct.Item("Price")
lblProductNo.Text = drProduct.Item("ProductNo")
imgProduct.ImageUrl = "images/product-detail/" + Trim(drProduct.Item("ProductNo")) + ".jpg"
End If
End If
End Sub
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' *** get product price
Dim dr As SqlDataReader
Dim strSQLStatement As String
Dim cmdSQL As SqlCommand
Dim strConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
strSQLStatement = "SELECT * FROM Product WHERE ProductNo = '" & lblProductNo.Text & "'"
Dim conn As New SqlConnection(strConnectionString)
conn.Open()
cmdSQL = New SqlCommand(strSQLStatement, conn)
dr = cmdSQL.ExecuteReader()
Dim decPrice As Decimal
If dr.Read() Then
decPrice = dr.Item("Price")
End If
conn.Close()
'*** get CartID
Dim strCartID As String
If HttpContext.Current.Request.Cookies("CartID") Is Nothing Then
strCartID = GetRandomCartIDUsingGUID(10)
Dim CookieTo As New HttpCookie("CartID", strCartID)
HttpContext.Current.Response.AppendCookie(CookieTo)
Else
Dim CookieBack As HttpCookie
CookieBack = HttpContext.Current.Request.Cookies("CartID")
strCartID = CookieBack.Value
End If
'Check if this product already exist in the cart
Dim dr2 As SqlDataReader
Dim strSQLStatement2 As String
Dim cmdSQL2 As SqlCommand
strSQLStatement2 = "SELECT * FROM cart WHERE CartID ='" & strCartID & "' and ProductID = '" & Trim(lblProductNo.Text) & "'"
'Reponse.Write(strSQlStatement2)
Dim conn2 As New SqlConnection(strConnectionString)
cmdSQL2 = New SqlCommand(strSQLStatement2, conn2)
conn2.Open()
dr2 = cmdSQL2.ExecuteReader()
If dr2.Read() Then
Dim intQuantityNew As Integer = dr2.Item("Quantity") + CInt(tbQuantity.Text)
strSQLStatement = ""
cmdSQL = New SqlCommand(strSQLStatement, conn)
Else
Dim dr3 As SqlDataReader
Dim strSQLStatement3 As String
Dim cmdSQL3 As SqlCommand
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
'Response.Write(strSQLStatement3)
Dim conn3 As New SqlConnection(strConnectionString)
conn3.Open()
cmdSQL3 = New SqlCommand(strSQLStatement3, conn3)
dr3 = cmdSQL3.ExecuteReader()
End If
'Response.Redirect("ViewCart.aspx")
End Sub
Public Function GetRandomCartIDUsingGUID(ByVal length As Integer) As String
'Get the GUID
Dim guidResult As String = System.Guid.NewGuid().ToString()
'Remove the hyphens
guidResult = guidResult.Replace("-", String.Empty)
'Make sure length is valid
If length <= 0 OrElse length > guidResult.Length Then
Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
End If
'Return the first length bytes
Return guidResult.Substring(0, length)
End Function
End Class
The issue is almost certainly here:
CInt(tbQuantity.Text)
The exception information even says:
Conversion from string "" to type 'Integer' is not valid.
You cannot convert a String to an Integer if the text doesn't represent a valid value and an empty string obviously doesn't represent a number. Validate the data first or else validate and convert in one go using Integer.Tryparse.

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

Customized ToolTip on MSChart Data

I'm trying to show a 'customized' ToolTip on an MSChart on an asp.net page, using vb.net
The chart displays OK, but I'm trying to get it to show the 'YEAR' as part of the tooltip, as well as the XY values.
I can't figure out how to do it.
Here's the code that I'm using to build the chart:
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
Sql = "SELECT att_Topic, att_Value, att_Year from Att "
Sql += " WHERE att_Year = '" & t_YEARS(i) & "' "
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
dt.Rows.Add(dr(0), dr(1), dr(2))
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
Chart1.DataSource = dt
Chart1.Series("Series1").XValueMember = "Topic"
Chart1.Series("Series1").YValueMembers = "Value"
Chart1.Series("Series1").ToolTip = "#VALX - #VALY"
Chart1.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
Chart1.DataBind()
Well, there may be a better answer, but I figured out a work-around anyhow ... I'm adding the YEAR to the axislabel. Then, in chart1_customize, changing the color of the bar, based on different axislabel. Seems to work.
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
showDATA = False
Sql = "SELECT att_Topic, att_Value, att_Year, att_Data from BWS_Att "
If (RBL_LIMIT.SelectedValue = 1) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Location' "
Sql += " AND att_Data IN ('" & String.Join("','", t_LOCS) & "')"
ElseIf (RBL_LIMIT.SelectedValue = 2) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Department' "
Sql += " AND att_Data IN ('" & String.Join("','", t_DEPTS) & "')"
Else
Sql += " WHERE att_Attrib = 'Company' "
End If
Sql += " AND att_Year = '" & t_YEARS(i) & "' "
Sql += " AND att_Topic IN ('" & String.Join("','", t_CATS) & "')"
Sql += " Order By att_ind"
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
'dt.Rows.Add(dr(0), dr(1), dr(2))
thisYR = dr(2).ToString
If (lastYR <> thisYR) Then
Chart1.Series("Series1").Points.Add(vbEmpty)
Chart1.Series("Series1").Points.Add(vbEmpty)
lastYR = thisYR
End If
If (showDATA = True) Then
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & "|" & dr(3).ToString & ":" & dr(0).ToString, dr(1))
Else
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & ":" & dr(0).ToString, dr(1))
End If
Chart1.Series("Series1").ToolTip = " #AXISLABEL | #VALY"
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
~~~~~~~~~~
Private Sub Chart1_Customize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Chart1.Customize
Dim C() As Drawing.Color = { _
Drawing.Color.Khaki, _
Drawing.Color.DarkSalmon, _
Drawing.Color.Goldenrod, _
Drawing.Color.MediumAquamarine, _
Drawing.Color.Tan _
}
Dim CN As Int16 = 0
Dim thisC As Int16 = 0
Dim LAST As String = String.Empty
For Each dp As System.Web.UI.DataVisualization.Charting.DataPoint In Chart1.Series("Series1").Points
Dim x As Array = dp.AxisLabel.Split(":")
If (x(0) <> "") Then
Dim H As String = x(0)
If (LAST <> H) Then
CN += 1
LAST = H
thisC = (CN Mod 5)
End If
dp.Color = C(thisC)
End If
Next
End Sub

Invalid Cast Exception with Update Panel

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

How to save uploaded .csv file into SQL Server Management database using asp.net

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.

Resources