ASP script to find keywords from Search - search

I'm looking for an ASP script that can parse a referral string from a search engine and extract just the keywords from it. I know this can be done using PHP, but I happen to working on a website that uses ASP.
Can this be done using ASP? Or, would it be better to find a Javascript/jQuery version?

Yes, it can be done in Classic ASP. E.g.:
<%
Dim i, url, querystring, keywords
url = Request.ServerVariables("HTTP_REFERER")
If url <> "" Then
Response.Write "Referrer: "
Response.Write url
Response.Write "<br>"
querystring = Request.ServerVariables("QUERY_STRING")
If querystring <> "" Then
keywords = Split(querystring, "&")
If IsArray(keywords) Then
For i = 0 To UBound(keywords)
Response.Write keywords(i)
Response.Write "<br>"
Next
End If
End If
End If
%>

Related

Export a csv using classic asp

I am trying to export a csv from classic asp. The data is being fetched by oracle DB. The query returns more than 2500 rows. Here is the code I am trying to use :
<%
sub Write_CSV_From_Recordset(RS)
if RS.EOF then
'
' There is no data to be written
'
exit sub
end if
dim RX
set RX = new RegExp
RX.Pattern = "\r|\n|,|"""
dim i
dim Field
dim Separator
'
' Writing the header row (header row contains field names)
'
Separator = ""
for i = 0 to RS.Fields.Count - 1
Field = RS.Fields(i).Name
if RX.Test(Field) then
'
' According to recommendations:
' - Fields that contain CR/LF, Comma or Double-quote should be enclosed in double-quotes
' - Double-quote itself must be escaped by preceeding with another double-quote
'
Field = """" & Replace(Field, """", """""") & """"
end if
Response.Write Separator & Field
Separator = ","
next
Response.Write vbNewLine
'
' Writing the data rows
'
do until RS.EOF
Separator = ""
for i = 0 to RS.Fields.Count - 1
'
' Note the concatenation with empty string below
' This assures that NULL values are converted to empty string
'
Field = RS.Fields(i).Value & ""
if RX.Test(Field) then
Field = """" & Replace(Field, """", """""") & """"
end if
Response.Write Separator & Field
Separator = ","
next
Response.Write vbNewLine
RS.MoveNext
loop
end sub
Response.Buffer = True
Response.ContentType = "text/csv"
Response.AddHeader "Content-Disposition", "attachment; filename=Export.csv"
theSQL = Session("Query")
Set RS = Connection.Execute(theSQL)
Write_CSV_From_Recordset RS
%>
<html>
<head>
<title>Excel/CSV Export</title>
</head>
<body>
</body>
</html>
But all I am getting is site unreachable error. I tried to even display the data on the page and export to excel by changing content-type and file extension. That works for less number of rows. But when the number of records fetched by the query is more, it will just give site unreachable error.
Could anybody help me out in resolving this issue.
sounds like your page is timing out, since it works for smaller amounts of data (I think that's what I understood you to say). you could try extending the timeout setting for the page (which is 90 seconds by default) by putting the following code at the top of your page:
Server.ScriptTimeout[=NumSeconds]
I would also move your Response.Buffer = true line to the top of the page, and within your do while loop, flush out the response line by line. Since it's going to an excel file, it won't look any different to the end user:
do until RS.EOF
Separator = ""
for i = 0 to RS.Fields.Count - 1
'
' Note the concatenation with empty string below
' This assures that NULL values are converted to empty string
'
Field = RS.Fields(i).Value & ""
if RX.Test(Field) then
Field = """" & Replace(Field, """", """""") & """"
end if
Response.Write Separator & Field
Separator = ","
next
Response.Write vbNewLine
Response.Flush '<-----add this line here
RS.MoveNext
if this doesn't work, it would be helpful to see the exact error message you're getting.
It also sounds like you may not be getting detailed error messages.
In IIS, under ASP, Debugging Properties, set Send Errors to Browser to true.
In Error Pages, Edit Feature Settings, select Detail Errors.
Then make sure your browser is NOT set to friendly error messages.
If it happens that one of those is not set correctly, then you won't be getting the line number and error that you need.
If all of those are set correctly, then the other advice to increase your session and script timeouts is good advice.
Besides the server.scripttimeout, which is 90 seconds by default;
Check in IIS if, for your website under the ASP settings, the limits properties aren't too strict. There are two options, Maximum requesting Entity Body Limit is for allowing big uploads, Response Buffering Limit is for allowing big downloads. If your CSV exceeds this limit, it won't download.
I see that you have already set your content-type correctly. If you are rendering a CSV to the browser, it should have response.ContentType = "text/csv" before you do any output.
Somewhat unrelated, it is also possible to render your recordset into a CSV immediately (in a single line of code) in ASP, using the GetString() function:
csv = RS.GetString(2,,vbCrLf,",","")

Webservice and FilterXML to pull data from website

I have a spreadsheet that I have tried to "automate" in the past. The best response I got was to use VBA - tried, failed, even with all of the author's suggestions. Just recently I heard of this new function in 2013 version and want to know if I can incorporate it.
I am trying to pull the "XXXX mi" from this page (http://www.gcmap.com/mapui?P=sfo-JFK) using a formula.
Can anyone suggest the proper formula, I have scoured the blogs, the support pages, the YouTube videos, I am just not good with XML but this data is crucial to me. I even went into the source info for the page and used firebug on Mozilla, still am lost). The rest of the spreadsheet does all of the backwork (hyperlink, abbreviate airport, etc...) this is the one thing I have left to automate.
Any and all help appreciated.
Thanks a billion.
The total distance is within the last <TD> element of the only <TABLE> within the <DIV> with an ID of dist_body.
Function total_distance(Optional qry As String = "SFO-JFK")
Dim str As String, htmlBDY As Object
On Error GoTo bm_Report_Error
With CreateObject("WinHttp.WinHttpRequest.5.1")
.Open "GET", "http://www.gcmap.com/mapui?P=" & qry, False
.Send
If .Status = "200" Then
Set htmlBDY = CreateObject("HTMLFile")
htmlBDY.body.innerHTML = .responseText
With htmlBDY
'the div as a unique ID
With .getElementById("dist_body")
'should only be one table in this div
With .getElementsByTagName("table")(0)
'get the last TD in this table
With .getElementsByTagName("td")(.getElementsByTagName("td").Length - 1)
str = .innerText
GoTo bm_Exit_Function
End With
End With
End With
End With
Else
str = "Error: " & .Status
GoTo bm_Exit_Function
End If
End With
GoTo bm_Exit_Function
bm_Report_Error:
str = Err.Number & " - " & Err.Description
bm_Exit_Function:
total_distance = str
End Function
I've tried to minimize var sets and assignments as much as possible.
            
Remember that you are pulling in a non-breaking space (e.g.  `) between the numerical distance and the mi label.

Find an email with subject starting with specific text

I am trying to find an email, by subject starting with specific text, to then download an attachment from that email.
I am using a variable with Restrict function, however issue seems to be because of usage of wildcards.
Sub findemail()
cntofmkts = Range("A" & Rows.Count).End(xlUp).Row
cntofmkts = cntofmkts - 1
ftodaydate = Format(Date, "yyyy-mm-dd")
Do
If i > cntofmkts Then Exit Do
MarketName = Range("A" & j).Value
Findvariable = "XXX_" & MarketName & "_ABC_" & ftodaydate
For Each oOlItm In oOlInb.Items.Restrict("[Subject] = *Findvariable*")
eSender = oOlItm.SenderEmailAddress
dtRecvd = oOlItm.ReceivedTime
dtSent = oOlItm.CreationTime
sSubj = oOlItm.Subject
sMsg = oOlItm.Body
If oOlItm.Attachments.Count <> 0 Then
For Each oOlAtch In oOlItm.Attachments
'~~> Download the attachment
oOlAtch.SaveAsFile NewFileName & oOlAtch.Filename
Exit For
Next
Else
MsgBox "The First item doesn't have an attachment"
End If
Exit For
Next
i = i + 1
j = j + 1
Loop
End sub
The first thing you should mind is that the Restrict() method does not evaluate the variable by it's name. You will have to concatenate the variable to the string.
Another one is, if you look at the example from MSDN site, you will see that there is not support for wildcards, so you will have to use the SQL syntax and the searched text in the filter expression must be between quotes.
' this namespace is for Subject
filterStr = "#SQL=""http://schemas.microsoft.com/mapi/proptag/0x0037001f"" like '%" & Findvariable & "%'"
It seems that urn:schemas:httpmail:subject also works and is easier to understand, but I can't confirm this now:
filterStr = "#SQL=""urn:schemas:httpmail:subject"" like '%" & Findvariable & "%'"
The string comparison that DASL filters support includes equivalence, prefix, phrase, and substring matching.
For Each oOlItm In oOlInb.Items.Restrict("[Subject] = Findvariable")
It looks like you are searching for the exact match. But what you need is to find a substring using the following syntax:
criteria = "#SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " like '%question%'"
Note that when you filter on the Subject property, prefixes such as "RE: " and "FW: " are ignored.
See Filtering Items Using a String Comparison for more information.
P.S. The Restrict method is an alternative to using the Find method or FindNext method to iterate over specific items within a collection. The Find or FindNext methods are faster than filtering if there are a small number of items. The Restrict method is significantly faster if there is a large number of items in the collection, especially if only a few items in a large collection are expected to be found.

Retrieving sharepoint lists using SOAP

I am trying to pull specific data points from a sharepoint list using VBA and SOAP. However, I am very new to both VBA and sharepoint, so there a few things that do not make sense to me. Currently, I'm trying to use this site as a reference:
http://depressedpress.com/2014/04/05/accessing-sharepoint-lists-with-visual-basic-for-applications/
I am having problems trying to locate where to find the credential information on the sharepoint site. Where would I go exactly to find the username, password, and SOAP URL?
I wrote the simple SharePoint list SOAP query below in VBA. I was able to run it within Excel and pull data from SharePoint. SOAP is not easy to work with as you need to have all the XML correct or it fails.
You can get a list of the services with examples by opening the /_vti_bin/Lists.asmx link on your SharePoint server, e.g.,
http://yourserver.com/_vti_bin/Lists.asmx And if you get a blank page then it means your version of SharePoint doesn't support SOAP web services.
Example: Queries the SharePoint UserInfo list for data using VBA
Sub spListQuery()
Dim webUrl, wsdl, action, soap, xhr As XMLHTTP60
itemId = 1
listName = "UserInfo"
webUrl = "http://yourserver.com" 'set to SharePoint site url
wsdl = "/_vti_bin/Lists.asmx"
action = "http://schemas.microsoft.com/sharepoint/soap/GetListItems"
soap = "<?xml version=""1.0"" encoding=""utf-8""?>" & _
"<soap:Envelope " & _
"xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" " & _
"xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" " & _
"xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">" & _
"<soap:Body>" & _
"<GetListItems xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">" & _
"<listName>" & listName & "</listName>" & _
"<query><Query>" & _
"<Where><Eq><FieldRef Name=""ID""/><Value Type=""Integer"">" & itemId & "</Value></Eq></Where>" & _
"</Query></query>" & _
"<viewFields><ViewFields/></viewFields>" & _
"</GetListItems>" & _
"</soap:Body>" & _
"</soap:Envelope>"
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xhr.Open "POST", webUrl & wsdl, False
xhr.setRequestHeader "Content-Type", "text/xml; charset=utf-8"
xhr.setRequestHeader "SOAPAction", action
xhr.Send soap
MsgBox xhr.Status & ":" & xhr.statusText & vbCrLf & xhr.responseText
End Sub

Using VBScript to create CSV files. A function to deal with values to make Excel happy

I would like opinions/suggestions for improvement etc on the following function. It will be wrapped around every value being passed into a CSV file on a classic ASP page. As is below it is handling all situations we are up against, for now....
I would like to know why If Len(txt) = 0 Then fails when it is run in the page that creates the CSV file althouh runs fine when in a regular ASP page. I ma having to use If "" & txt = "" Then to make it work on both pages
function insertCSV(txt)
'If Len(txt) = 0 Then
If "" & txt = "" Then
Exit Function
Else
Dim tmp
tmp = txt
if isNumeric(tmp) then
if left(tmp, 1) = "0" then
tmp = """" & tmp & """"
else
tmp = tmp
end if
else
tmp = Replace(tmp, """", """""")
if instr(tmp, ",") or instr(tmp, """") then tmp = """" & tmp & """"
if instr(tmp, "®") then tmp = replace(tmp, "®", "®")
if instr(tmp, "™") then tmp = replace(tmp, "™", "™")
if instr(tmp, "©") then tmp = replace(tmp, "©", "©")
if instr(tmp, vbcrlf) then tmp = replace(tmp, vbcrlf, "")
if instr(tmp, "Â") then tmp = replace(tmp, "Â", "")
end if
insertCSV = tmp
End If
end function
Few things:
This section:
If "" & txt = "" Then
insertCSV = ""
Else
If you just want to return an empty string if txt is empty, you can just do this:
If Len(txt) = 0 Then Exit Function
You don't need to use End If for single-line If statements.
This line:
if isNumeric(tmp) AND left(tmp, 1) <> "0" then tmp = tmp end if
You're assigning the value back to itself? What purpose does this serve?
Don't you want to replace just the symbol © with ©? The way you have it written, you're replacing the entire text with © (same goes for your other tests).
I would think you'd want to do this instead:
If InStr(tmp, "©") Then tmp = Replace(tmp, "©", "©")
Try making those changes and then post an updated version of your routine and let's see how it looks.
Update (based on latest comments)
If the database already has values stored like ’ then you need to consider that the web application is inserting the data using the wrong encoding and you are ending up with a mismatch in encoding in the database.
Answer to Convert UTF-8 String Classic ASP to SQL Database
You don't need any of that the issue is Excel interprets the CSV as ASCII when you are sending it as UTF-8.
There is a useful trick that fools Excel into using the correct encoding rather then assuming ASCII, I use this technique all the time and works well. It involves writing a BOM (Byte Order Mark) to the stream before displaying your data that tells Excel the data is UTF-8 not ASCII encoded.
'BOM to dup Excel into encoding the CSV correctly instead of using ASCII!!!
Call Response.BinaryWrite(ChrB(239) & ChrB(187) & ChrB(191))
This should be specified before you use Response.Write() to output your text from the insertCSV() function.
Using this kind of code
if instr(tmp, "Â") then
is just wrong when what the output (Â) is trying to do is tell you something is wrong with the encoding.
Useful Links
Microsoft Excel mangles Diacritics in .csv files?
How can I output a UTF-8 CSV in PHP that Excel will read properly?
Which encoding opens CSV files correctly with Excel on both Mac and Windows? (still applies in this case)

Resources