My page dies when I execute the second ASP object - asp.net

I don't know too much about ASP, here is my code:
<%
dim objCmd, objRS1, objRS2, strDate1, strDate2, strName, strStyle, datDate, strLastGroup, datNow
set objCmd = Server.CreateObject("ADODB.Command")
Set objRS1 = Server.CreateObject("ADODB.Recordset")
Set objRS2 = Server.CreateObject("ADODB.Recordset")
set objCmd.ActiveConnection = objConn
objCmd.CommandText = "Select Site_Pages.Filename, HeadingName, MatrixName, Site_Matrices.MatrixID, TurnaroundOverride, TurnaroundName, MAX(Turnaround) AS AutoTurnaround, TurnaroundGroup FROM Site_Headings, Site_Pages, Site_Matrices, Site_Items, Site_Items_Prices, Items WHERE Site_Headings.HeadingID = Site_Pages.HeadingID AND Site_Pages.ProdPageID = Site_Matrices.ProdPageID AND Site_Matrices.MatrixID = Site_Items.MatrixID AND Site_Items.ItemID = Site_Items_Prices.ItemID AND Site_Items_Prices.PriceID = Items.PriceID AND SiteID = 0 AND TurnaroundPage = 1 GROUP BY HeadingName, MatrixName, TurnaroundOverride, TurnaroundName, Site_Pages.Filename, TurnaroundGroup, TurnaroundSortOrder, Site_Matrices.MatrixID ORDER BY TurnaroundGroup, TurnaroundSortOrder, HeadingName, MatrixName, TurnaroundName"
set objRS1 = objCmd.Execute
if not objRS1.eof then
Call NewTable(objRS1("TurnaroundGroup"))
strLastGroup = objRS1("TurnaroundGroup")
end if
do until objRS1.eof
if strLastGroup <> objRS1("TurnaroundGroup") then
Call EndTable()
Call NewTable(objRS1("TurnaroundGroup"))
end if
strLastGroup = objRS1("TurnaroundGroup")
'decide todays date for checking dated turnaround overrides
datNow = dateadd("h", GetSetting("TimeOffset"), now())
'if before 7am, knock off a day
if hour(datnow) < 7 then datnow = dateadd("d", -1, datnow)
objCmd.CommandText = "SELECT Turnaround FROM DatedTurnarounds WHERE MatrixID = " & CLng(objRS1("MatrixID")) & " AND TDate = '" & Year(datNow) & PadWithZeros(Month(datNow)) & PadWithZeros(Day(datNow)) & " 00:00'"
set objRS2 = objCmd.Execute
if objRS1("TurnaroundOverride") = 0 OR IsNull(objRS1("TurnaroundOverride")) then
if objRS2.eof then 'use automatic (3-last)
datDate = AddDays(objRS1("AutoTurnaround")-1)
else 'use dated turnaround override (2-second)
datDate = AddDays(objRS2("Turnaround")-1)
end if
else 'use matrix overrride (1-first - overrides all)
datDate = AddDays(objRS1("TurnaroundOverride")-1)
end if
strDate1 = Left(WeekDayName(DatePart("w", datDate)), 3) & " " & DateSuffix(DatePart("d", datDate)) & " of " & MonthName(DatePart("m", datDate))
if objRS1("TurnaroundOverride") = 0 OR IsNull(objRS1("TurnaroundOverride")) then
if objRS2.eof then 'use automatic (3-last)
datDate = AddDays(objRS1("AutoTurnaround"))
else 'use dated turnaround override (2-second)
datDate = AddDays(objRS2("Turnaround"))
end if
else 'use matrix overrride (1-first - overrides all)
datDate = AddDays(objRS1("TurnaroundOverride"))
end if
objRS2.close
strDate2 = Left(WeekDayName(DatePart("w", datDate)), 3) & " " & DateSuffix(DatePart("d", datDate)) & " of " & MonthName(DatePart("m", datDate))
if objRS1("TurnaroundName") = "" OR IsNull(objRS1("TurnaroundName")) then
if objRS1("MatrixName") = "" OR IsNull(objRS1("MatrixName")) then
strName = objRS1("HeadingName")
else
strName = objRS1("MatrixName")
end if
else
strName = objRS1("TurnaroundName")
end if
if strStyle = "PriceMatrixRow1" then
strStyle = "PriceMatrixRow2"
else
strStyle = "PriceMatrixRow1"
end if
%>
I think the problem should be somewhere here
objCmd.CommandText = "SELECT Turnaround FROM DatedTurnarounds WHERE MatrixID = " & CLng(objRS1("MatrixID")) & " AND TDate = '" & Year(datNow) & PadWithZeros(Month(datNow)) & PadWithZeros(Day(datNow)) & " 00:00'"
set objRS2 = objCmd.Execute
I'm not sure if I can execute another object in an object though
Any help would be very much appreciated.

Related

Classic ASP internal error on contact form

My form takes me to an internal error page upon submission. I have all the fields defined, and my SMTP info passing through. It looks as if everything should work. But it simply doesn't.
Any suggestions is appreciated.
<%
'Declaring Variables
Dim smtpserver,youremail,yourpassword,ContactUs_Name,ContactUs_Email
Dim ContactUs_Subject,ContactUs_Body,Action,IsError
' Edit these 3 values accordingly
smtpserver = "mysmtperserver"
youremail = "myemail"
yourpassword = "mypassword"
' Grabbing variables from the form post
ContactUs_Name = Server.HTMLEncode(Request("ContactUs_Name"))
ContactUs_Email = Server.HTMLEncode(Request("ContactUs_Email"))
ContactUs_Subject = Server.HTMLEncode(Request("ContactUs_Subject"))
ContactUs_Body = Server.HTMLEncode(Request("ContactUs_Body"))
ContactUs_Captcha = Request("recaptcha_response_field")
Action = Request("Action")
' Used to check that the email entered is in a valid format
Function IsValidEmail(Email)
Dim ValidFlag,BadFlag,atCount,atLoop,SpecialFlag,UserName,DomainName,atChr,tAry1
ValidFlag = False
If (Email <> "") And (InStr(1, Email, "#") > 0) And (InStr(1, Email, ".") > 0) Then
atCount = 0
SpecialFlag = False
For atLoop = 1 To Len(Email)
atChr = Mid(Email, atLoop, 1)
If atChr = "#" Then atCount = atCount + 1
If (atChr >= Chr(32)) And (atChr <= Chr(44)) Then SpecialFlag = True
If (atChr = Chr(47)) Or (atChr = Chr(96)) Or (atChr >= Chr(123)) Then SpecialFlag = True
If (atChr >= Chr(58)) And (atChr <= Chr(63)) Then SpecialFlag = True
If (atChr >= Chr(91)) And (atChr <= Chr(94)) Then SpecialFlag = True
Next
If (atCount = 1) And (SpecialFlag = False) Then
BadFlag = False
tAry1 = Split(Email, "#")
UserName = tAry1(0)
DomainName = tAry1(1)
If (UserName = "") Or (DomainName = "") Then BadFlag = True
If Mid(DomainName, 1, 1) = "." then BadFlag = True
If Mid(DomainName, Len(DomainName), 1) = "." then BadFlag = True
ValidFlag = True
End If
End If
If BadFlag = True Then ValidFlag = False
IsValidEmail = ValidFlag
End Function
%>
<%
If Action = "SendEmail" Then
' Here we quickly check/validate the information entered
' These checks could easily be improved to look for more things
If IsValidEmail(ContactUs_Email) = "False" Then
IsError = "Yes"
Response.Write("<font color=""red"">Please enter valid Email address.</font><br>")
End If
If ContactUs_Name = "" Then
IsError = "Yes"
Response.Write("<font color=""red"">Please enter your Name.</font><br>")
End If
If ContactUs_Subject = "" Then
IsError = "Yes"
Response.Write("<font color=""red"">Please enter a Subject.</font><br>")
End If
If ContactUs_Body = "" Then
IsError = "Yes"
Response.Write("<font color=""red"">Please include Message.</font><br>")
End If
if ContactUs_Captcha = "" Then
IsError = "Yes"
Response.Write("<font color=""red"">Captcha Required.</font><br>")
End If
End If
' If there were no input errors and the action of the form is "SendEMail" we send the email off
If Action = "SendEmail" And IsError <> "Yes" Then
Dim strBody
' Here we create a nice looking html body for the email
strBody = strBody & "<font face=""Arial"">Contact Us Form submitted at " & Now() & vbCrLf & "<br><br>"
strBody = strBody & "From http://" & Request.ServerVariables("HTTP_HOST") & vbCrLf & "<br>"
strBody = strBody & "IP " & Request.ServerVariables("REMOTE_ADDR") & vbCrLf & "<br>"
strBody = strBody & "Name" & " : " & " " & Replace(ContactUs_Name,vbCr,"<br>") & "<br>"
strBody = strBody & "Email" & " : " & " " & Replace(ContactUs_Email,vbCr,"<br>") & "<br>"
strBody = strBody & "Subject" & " : " & " " & Replace(ContactUs_Subject,vbCr,"<br>") & "<br>"
strBody = strBody & "<br>" & Replace(ContactUs_Body,vbCr,"<br>") & "<br>"
strBody = strBody & "</font>"
Dim ObjSendMail
Set ObjSendMail = CreateObject("CDO.Message")
'This section provides the configuration information for the remote SMTP server.
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtpserver
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Use SSL for the connection (True or False)
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = youremail
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = yourpassword
ObjSendMail.Configuration.Fields.Update
'End remote SMTP server configuration section==
ObjSendMail.To = youremail
ObjSendMail.Subject = ContactUs_Subject
ObjSendMail.From = ContactUs_Email
' we are sending a html email.. simply switch the comments around to send a text email instead
ObjSendMail.HTMLBody = strBody
'ObjSendMail.TextBody = strBody
ObjSendMail.Send
Set ObjSendMail = Nothing
' change the success messages below to say or do whatever you like
' you could do a response.redirect or offer a hyperlink somewhere.. etc etc
%>
If you can't do much with custom error pages then you can use "On Error Resume Next" to trap errors, something like:
On Error Resume Next
'Put your code in here
'Write out error messages
If err.number > 0 then
response.write "Error: err.description & " on line number <strong>" & err.line & "</strong>"
END IF
On Error Goto 0
Caveat: I'd just recommend taking this out once you've got your code working as can mask issues if not used carefully. Instead look at getting some proper error handling and logging in place using custom error pages.
Just at a quick glance... this section looks to be missing an END IF
If (atCount = 1) And (SpecialFlag = False) Then
BadFlag = False
tAry1 = Split(Email, "#")
UserName = tAry1(0)
DomainName = tAry1(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

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

Converting an HTA into an ASP page?

I was given an HTA that I think was created by the HTA_Helpomatic. They want it converted into a classic ASP page. So I made a few basic changes, and I think I almost have it working. But I'm running into a problem - the ole 'VBScript Object Required' bit. It's doing this on the line Set objlst_groupnames = document.getElementById( "list_servicenames" )
Here's the original HTA script - can anyone help me figure out how to properly convert this to ASP? I had a similar page created, but it didn't work the way they wanted (You had to click on each service to toggle it, vs just clicking on a check box). Thanks.
<head>
<title>Start/Stop/Restart Windows Services</title>
<HTA:APPLICATION
APPLICATIONNAME="Start/Stop/Restart Windows Services"
BORDER="thin"
SCROLL="yes"
SINGLEINSTANCE="yes"
ID="oHTA"
>
<APPLICATION:HTA>
</head>
<script language="VBScript">
Sub Window_OnLoad
Set objlst_groupnames = document.getElementById( "list_servicenames" )
If objlst_groupnames Is Nothing Then
MsgBox "A problem was encountered while creating the listview." & vbCRLF & "Please see your administrator."
Else
With objlst_groupnames
.View = 3
.Width = 800
.Height = 600
.SortKey = 0
.Arrange = 0
.LabelEdit = 1
.SortOrder = 0
.Sorted = 1
.MultiSelect = 0
.LabelWrap = -1
.HideSelection = -1
.HideColumnHeaders = 0
.OLEDragMode = 0
.OLEDropMode = 0
.Checkboxes = 1
.FlatScrollBar = 0
.FullRowSelect = 1
.GridLines = 0
.HotTracking = 0
.HoverSelection = 0
.PictureAlignment = 0
.TextBackground = 0
.ForeColor = -2147483640
.BackColor = -2147483643
.BorderStyle = 1
.Appearance = 1
.MousePointer = 0
.Enabled = 1
.ColumnHeaders.Clear
.ColumnHeaders.Add , , "Caption", 150
.ColumnHeaders.Add , , "State", 150
.ColumnHeaders.Add , , "Name", 150
.ColumnHeaders.Add , , "Description", 150
.ColumnHeaders.Add , , "Start Mode", 150
.ListItems.Clear
End With
End If
sComputer = MachineName.Value
ListServices(sComputer)
End Sub
Sub ListServices(sComputer)
ON ERROR RESUME NEXT
sServiceName = ServiceName.Value
Set objList = document.getElementById( "list_servicenames" )
objList.ListItems.Clear
set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
if sServiceName = "" then
Set colItems = objWMIService.ExecQuery("Select * from Win32_Service")
else
Set colItems = objWMIService.ExecQuery("Select * From Win32_Service where DisplayName like '%" & sServiceName & "%'")
end if
For Each objItem in colItems
Set objListItem = objList.ListItems.Add
objListItem.Text = objItem.Caption
objListItem.ListSubItems.Add.Text = objItem.State
objListItem.ListSubItems.Add.Text = objItem.Name
objListItem.ListSubItems.Add.Text = objItem.Description
objListItem.ListSubItems.Add.Text = objItem.StartMode
Next
End Sub
Sub btn_start_onClick()
sComputer = MachineName.Value
for n = 1 to list_servicenames.ListItems.Count
if list_servicenames.ListItems(n).checked = True then
strService = list_servicenames.ListItems(n).ListSubItems(2).Text
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery ("Select * from Win32_Service where Name='" & strService & "'")
For each objService in colServiceList
errReturn = objService.StartService()
Next
end if
next
ListServices(sComputer)
End Sub
Sub btn_stop_onClick()
sComputer = MachineName.Value
for n = 1 to list_servicenames.ListItems.Count
if list_servicenames.ListItems(n).checked = True then
strService = list_servicenames.ListItems(n).ListSubItems(2).Text
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery ("Select * from Win32_Service where Name='" & strService & "'")
For each objService in colServiceList
errReturn = objService.StopService()
Next
end if
next
ListServices(sComputer)
End Sub
Sub btn_restart_onClick()
sComputer = MachineName.Value
'Stop services
for n = 1 to list_servicenames.ListItems.Count
if list_servicenames.ListItems(n).checked = True then
strService = list_servicenames.ListItems(n).ListSubItems(2).Text
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery ("Select * from Win32_Service where Name='" & strService & "'")
For each objService in colServiceList
errReturn = objService.StopService()
Next
end if
next
'Start services
for n = 1 to list_servicenames.ListItems.Count
if list_servicenames.ListItems(n).checked = True then
strService = list_servicenames.ListItems(n).ListSubItems(2).Text
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery ("Select * from Win32_Service where Name='" & strService & "'")
For each objService in colServiceList
errReturn = objService.StartService()
Next
end if
next
ListServices(sComputer)
End Sub
Sub btn_Refresh_onClick()
sComputer = MachineName.Value
ListServices(sComputer)
End Sub
Sub btn_exit_onClick()
Window.Close
End Sub
function list_servicenames_ColumnClick(colheader)
list_servicenames.SortKey = colheader.index-1
end Function
</script>
<body>
Enter Machine Name: <Input Type = "Text" Name = "MachineName">
<Input Type = "Button" Value = "Get Services" Name = "Run_Button" onClick = "Window_OnLoad"> Filter Services by Name: <Input Type = "Text" Name = "ServiceName"><P>
<input type="button" value="Refresh" name="btn_Refresh" id="btn_Refresh" title="Click to refresh the services list">
<input type="button" value="Start" name="btn_start" id="btn_start" title="Click to Start the Services">
<input type="button" value="Stop" name="btn_stop" id="btn_stop" title="Click to Stop the Service">
<input type="button" value="Restart" name="btn_restart" id="btn_restart" title="Click to Restart the Services">
<input type="button" value="Exit" name="btn_exit" id="btn_exit" title="Click to Exit Form ">
<br/>
<OBJECT id="list_servicenames" name="list_servicenames" classid="clsid:BDD1F04B-858B-11D1-B16A-00C0F0283628"></OBJECT>
</body>
To get a client-side click event to activate something on the server you must use something like AJAX.

putting values from database into a drop down list

my tool is in asp. i am using this code for a query in sql
dim req_id
req_id=Request.Form("Req_id")
if req_id<>"" then
Set conn=server.CreateObject("adodb.connection")
conn.Open session("Psrconnect")
Set rs=CreateObject("Adodb.Recordset")
rs.Open "select * from passwords where REQ_ID='"&req_id&"'", conn
i want to put the results of this query into a drop down list. how do i do it? any help is very much appreciated.
Slightly edited code from my working pages :
function HtmlFormOption( byval psReturnValue, byval psDisplayValue ,byval psCurrentDefault)
dim x
if IsNull(psCurrentDefault) then psCurrentDefault = ""
if IsNull(psReturnValue) then psReturnValue = ""
if lCase( cStr(psReturnValue) ) = lCase( cStr(psCurrentDefault)) then
x = "selected "
else
x = ""
end if
HtmlFormOption = "<option " & x & "value='" & psReturnValue & "'>" & psDisplayValue & "</option>"
end function
dim Result, sCode, sWaarde
Result = "<select name='NameCombobox' size='1'>" & vbCrlf
while not objRecLookup.Eof
sCode = objRecLookup.Fields(0) ' first field in result set
sWaarde = objRecLookup.Fields(1) ' second field in result set
if not IsNull(sCode) and not IsNull(sWaarde) then
Result = Result & HtmlFormOption( sCode, sWaarde , psCurrentDft )
end if
objRecLookup.MoveNext
wend
objRecLookup.Close
Result = Result & "</select>" & vbCrlf
And than Response.Write(Result)
Here's a simple solution:
<%
Dim objCommand, objRS
Set objCommand = Server.CreateObject("ADODB.Command")
with objCommand
.ActiveConnection = objConn
.CommandType = adCmdText
.CommandText = "SELECT * FROM PASSWORDS WHERE REQ_ID= '" & req_id & "'"
Set objRS = .Execute
end with
%><select name="selectbox"><%
While NOT objRS.EOF
%><option value="<%=objRS("COLUMN_NAME")%>"><%=objRS("COLUMN_NAME")%></option><%
objRS.MoveNext
Wend
%></select><%
objRS.Close
Set objRS = Nothing
Set objCommand = Nothing
%>

Categories

Resources