Error handing page not trapping all errors - iis

I have this simple error checking page on my classic ASP website and have a custom error page set up so that scripting errors (500 and 500.100) call this error page so that errors are logged into a MySQL table:
<!--#INCLUDE file="db_connection.asp" -->
<%
On Error Resume Next
'crappy function I use
Function newstr(str)
newstr = Server.HTMLencode(str)
newstr = Replace(newstr, "'","''")
newstr = Replace(newstr, "\","\\")
newstr = Replace(newstr, chr(10), "<br />")
End Function
'get all form data and put it into a variable
For ix = 1 to Request.Form.Count
fieldName = Request.Form.Key(ix)
fieldValue = Request.Form.Item(ix)
bb = bb & fieldName & ": " & fieldValue & vbcrlf
Next
bb = newstr(bb)
set objError = Server.getLastError()
strNumber = objError.AspCode & " : " & Err.Number
strSource = objError.Category
strPage = objError.File
strDesc = objError.Description & " : " & ObjError.ASPDescription & " :: " & Err.Description
strDesc = newstr(strDesc)
strCode = Server.HTMLEncode(objError.Source)
If strCode = "" then strCode = "No code available"
strLine = ObjError.Line
strASPDesc = ObjError.ASPDescription
strRemoteAddr = Request.ServerVariables("REMOTE_ADDR")
strLocalAddr = Request.ServerVariables("LOCAL_ADDR")
ref = request.servervariables("HTTP_REFERER")
str = request.servervariables("QUERY_STRING")
ip_url = strRemoteAddr
ua = newstr(request.servervariables("HTTP_USER_AGENT"))
totalstring = strPage & "?" & str
sql = ""
sql = SQL & " INSERT INTO error_log ("
sql = SQL & " er_time, "
sql = SQL & " er_number, "
sql = SQL & " er_source, "
sql = SQL & " er_page, "
sql = SQL & " er_desc, "
sql = SQL & " er_code, "
sql = SQL & " er_line, "
sql = SQL & " er_remote_addr, "
sql = SQL & " er_local_addr, "
sql = SQL & " er_str, "
sql = SQL & " er_ref, "
sql = SQL & " er_type, "
sql = SQL & " ip_url, "
sql = SQL & " er_br, "
sql = SQL & " er_form"
sql = SQL & " ) VALUES ("
sql = SQL & " now(),"
sql = SQL & " '" &strNumber&"',"
sql = SQL & " '"&strSource&"',"
sql = SQL & " '"&strPage&"',"
sql = SQL & " '"&strDesc&"',"
sql = SQL & " '"&strCode&"',"
sql = SQL & " '"&strLine&"',"
sql = SQL & " '"&strRemoteAddr&"',"
sql = SQL & " '"&strLocalAddr&"',"
sql = SQL & " '"&totalstring&"',"
sql = SQL & " '"&ref&"',"
sql = SQL & " '500',"
sql = SQL & " '"&ip_url&"',"
sql = SQL & " '"&ua&"',"
sql = SQL & " '"&bb&"') "
oConn.Execute(sql)
%>
The trouble I'm finding is that lots of lines keep ending up in the error log, but are not triggering Server.getLastError, because all of the variables from that are NULL. And I know that someone isn't directly visiting the URL of the error page because the "strPage" variable, (set by objError.File) is populated.
However, if I visit the page that is erroring, it always works fine.
The pages which are in the error log always have a querystring associated with them - but the ID of that always varies - so e.g. it might be that the "totalstring" (made up of objError.File concatenated with a question mark followed by request.servervariables("QUERY_STRING") could be:
/music/view.asp?id=192
/designs/page.asp?id=5775
/designs/page.asp?id=5797
They all error in the same place, which is:
e = newstr(request("id"))
Where "newstr" is the function mentioned at the top of this page. I know that that function is a load of crap and risks SQL injections etc.
However, in this case, I can't work out why the pages are erroring as they always work fine for me and most of the site users.
What's strange is that the IP addresses of the users getting the errors are always from the same ISP - generally one ISP in Germany.
Could something suspicious be going on in the background? Is there any additional logging I could do to get to the bottom of this?
Update 30th July 2015
Thanks to answer provided by #John, I was able to get to the bottom of this, and avoided errors by putting this at the top of every page:
<%
''get the cookie data
ck = Request.ServerVariables("HTTP_COOKIE")
'' does the cookie data contain "; = true;" somewhere, does not matter where
v1 = instr(ck, "; =true;")
''if the cookie data starts with "=true;" OR if "; =true;" appears somewhere in the cookie, then redirect somewhere else
if left(ck,6) = "=true;" OR v1 > 0 then response.redirect ("somewhere-else.asp")
%>
More info also here:
https://forums.iis.net/p/1226865/2106015.aspx?Re+Request+Cookies+generate+80004005+2147467259+error+if+cookie+with+no+name
Seems to be some hacking type activity originating from ISP Hetzner Online AG

I have been getting a lot of similar errors where no error number is recorded. I found the problem due to the cookies that were being sent and at least one of the cookies having no name.
When you do Request("id") it checks the querystring, form post and then cookies. Classic ASP does not seem capable of handling cookies where there is no name and fails in this situation with an error.
Looking at the requests I am receiving they do look like unusual hack attempts targeting cookies.
To see if this is the case I would suggest you log the cookie HTTP header as well.
One option would be to change from Request to Request.QueryString or Request.Form depending on how you are expecting the parameter to be passed (GET or POST).
If that is not an option then you could add some code to check for this no name cookie problem, something like this should do the job:
On Error Resume Next
Request.Cookies("test")
If Err.Number <> 0 Then Server.Transfer("/common/500.asp")
On Error Goto 0
This just checks whether it is possible to read a cookie, and it doesn't matter what cookie name you use or whether the cookie exists or not. It will end execution if invalid cookies are sent. If you have an include file that is run on every request you could add this to the beginning.
See my own SO question for some further information.

Related

MSAccess 2007 Select Query RecordSet RecordCount from Excel 2007 VBA always returns 0 [duplicate]

Working in Access 2010 against an Access DB, I created a query in the QBE. As part of an overly complex quarterly reporting process, I now need to be able to execute that query with different parameters via VBA code. The SQL for the query is now embedded in my VBA module, and is modified on the fly, then executed. When run in the QBE, this particular instance of the query returns 400+ rows of data, but none are returned when executed in VBA via this code:
Dim Data As New ADODB.Recordset
Dim SQLString As String
SQLString = "SELECT PatientStatSchedDataDump.PtCompID, AppType.ProviderW, " & _
"PatientStatSchedDataDump.Date, PatientStatSchedDataDump.Status " & _
"FROM (AppType INNER JOIN PatientStatSchedDataDump ON AppType.AType = " & _
"PatientStatSchedDataDump.Type) LEFT JOIN GroupType ON AppType.Group = " & _
"GroupType.Group " & _
"WHERE (((PatientStatSchedDataDump.PtCompID) Like 'ClientName*' ) " & _
"AND ((PatientStatSchedDataDump.Date) BETWEEN #1/1/2014# AND #3/31/2014#) " & _
"AND ((GroupType.[Sort Order]) IN ('A', 'B', 'C', 'D', 'E')))"
Data.Open Source:=SQLString, ActiveConnection:=CurrentProject.Connection
If Not Data.EOF And Not Data.BOF Then
'the IF is never true - EOF & BOF are always True
NewSheet.Cells(InstCountRow + InstCount + 2, 1).CopyFromRecordset Data
End If
Data.Close
Set Data = Nothing
Again, if I create a new query in Access, paste the SQL code into the SQL window and run it, I get 400+ rows of results with this exact query
A query run from ADO requires ANSI wild cards: % instead of *; and _ instead of ?.
So change this ...
"WHERE (((PatientStatSchedDataDump.PtCompID) Like 'ClientName*' ) "
to this ...
"WHERE (((PatientStatSchedDataDump.PtCompID) Like 'ClientName%' ) "
If you want one query which works the same when run from ADO as it does when run in the QBE, you can use ALike instead of Like. With ALike, the db engine always expects ANSI wildcards.
"WHERE (((PatientStatSchedDataDump.PtCompID) ALike 'ClientName%' ) "

SQLClient Command Parameter Query String Length

I am connecting to a SQL Server and am trying to limit the results by adding parameters. The first parameter I added, #sdate, worked just fine. But, now I am trying to add a second parameter which is not working. I want the field, LP_EOC_DATA.PL, to only be returned if the length of the string is greater than 6 characters long. The code below executed, and like I say, the dates returned were correct, but it also returned values from LP_EOC_DATA.PL that had string lengths less than 6. Please let me know if you know how to get this to work. Thanks in advance.
Sub doSQL()
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim myReader As SqlDataReader
Dim sqlString As String = "SELECT LP_EOC_DATA.PL as PLs, LP_EOC_DATA.cDate as ReadDate, LP_EOC_LOV.LOCATION as Location " &
"FROM LP_EOC_DATA INNER JOIN LP_EOC_LOV ON LP_EOC_DATA.PIC = LP_EOC_LOV.PIC " &
"WHERE LP_EOC_DATA.cDate > (#sdate) AND LEN(LP_EOC_DATA.PL) > #slen1 " &
"UNION SELECT dbo.VT_DATA.PL as PLs, dbo.VT_DATA.cDate as ReadDate, dbo.VT_LOV.LOCATION as Location " &
"FROM dbo.VT_DATA INNER JOIN dbo.VT_LOV ON dbo.VT_DATA.PIC = dbo.VT_LOV.PIC " &
"WHERE dbo.VT_DATA.cDate > (#sdate) AND LEN(dbo.VT_DATA.PL) > #slen1 " &
"ORDER BY ReadDate;"
myConn = New SqlConnection("SERVER=ServerName;UID=uName;" &
"PWD=Password;")
myCmd = myConn.CreateCommand
myCmd.CommandText = sqlString
myCmd.Parameters.AddWithValue("#sdate", DateTimePicker1.Value)
myCmd.Parameters.AddWithValue("#slen1", 6)
'myCmd.Parameters.AddWithValue("#rx1", "'%[^0-9a-z]%'")
'myCmd.Parameters.AddWithValue("#rx2", " dbo.VT_DATA.PL NOT LIKE '%[^0-9a-z]%'")
myConn.Open()
myReader = myCmd.ExecuteReader()
Table.Load(myReader)
DataGridView1.Visible = True
DataGridView1.DataSource = Table
lblTotal.Text = Table.Rows.Count
End Sub
Also, as you can see, I am looking to add another parameter that only returns alphanumeric results from the same LP_EOC_DATA.PL field. I haven't got quite that far yet, but if you see something I'm doing wrong there too, I'd appreciate the input.
It helps if you format your SQL a little more. There's some structure, but it still comes off as a big wall of text. It's even harder for us to debug than it is for you, since we don't know your schema at all. There are also a number of other little things you should do different before we even address the question (Using block so connection is closed in case of exception, avoid AddWithValue() for index safety, isolate SQL from user interface, etc):
Function doSQL(StartDate As DateTime) As DataTable
Dim result As New DataTable
Dim sqlString As String = _
"SELECT LP_EOC_DATA.PL as PLs, LP_EOC_DATA.cDate as LPRReadDate, LP_EOC_LOV.LOCATION as Location " &
"FROM LP_EOC_DATA " &
"INNER JOIN LP_EOC_LOV ON LP_EOC_DATA.PIC = LP_EOC_LOV.PIC " &
"WHERE LP_EOC_DATA.cDate > #sdate AND LEN(COALESCE(LP_EOC_DATA.PL,'')) > #slen1 " &
"UNION " &
"SELECT dbo.VT_DATA.PL as PLs, dbo.VT_DATA.cDate as ReadDate, dbo.VT_LOV.LOCATION as LPRLocation " &
"FROM dbo.VT_DATA " &
"INNER JOIN dbo.VT_LOV ON dbo.VT_DATA.PIC = dbo.VT_LOV.PIC " &
"WHERE dbo.VT_DATA.cDate > #sdate AND LEN(COALESCE(dbo.VT_DATA.PL,'')) > #slen1 " &
"ORDER BY ReadDate;"
Using myConn As New SqlConnection("SERVER=ServerName;UID=uName;" &
"PWD=Password;"), _
myCmd As New SqlCommand(sqlString, myConn)
myCmd.Parameters.Add("#sdate", SqlDbType.DateTime).Value = StarDate
myCmd.Parameters.Add("#slen1", SqlDbType.Int).Value = 6
myConn.Open()
result.Load(myCmd.ExecuteReader())
End Using
Return result
End Function
And then call it like this:
Dim tbl As DataTable = doSql(DateTimePicker1.Value)
DataGridView1.Visible = True
DataGridView1.DataSource = tbl
lblTotal.Text = tbl.Rows.Count
As for the question, there are a few possibilities: NULL values can give unexpected results in this kind of situation (the code I posted already accounts for that). You may also have trouble with certain unicode whitespace padding your character count. Another possibility is char or nchar fields instead of varchar or nvarchar, though I don't think that's the issue here.
This is not an answer to the question per se but a reply to the request for an XML literal example. As that requires a few lines of code, I'd rather not put it in a comment.
Dim sql = <sql>
SELECT *
FROM MyTable
WHERE MyColumn = #MyColumn
</sql>
Dim command As New SqlCommand(sql.Value, connection)
Note that the element name can be anything you want but I usually use 'sql' when it's for SQL code.

errors importing CSV (delimited) into DAO database using vba and SQL from

I am stymied by an SQL mediated import of a CSV file using VBA code. I am using a Third EXCEL macro/spreadsheet, to analyze a LEFT JOIN of 2 files, one as an XLXS and the other as a CSV.
I suspect that part of the problem may be how the SQL command is used, for a FROM reference to an excel file. I am using Excel VBA, 2010, The 14 Database Access Engine.
I want to end with an SQL statement that pulls from an external comma delimited CSV file
I anticipate heading the macro with this pseudo code, in a stand-alone macro enabled excel file:
dbEngine = CreateObject(DAO.engine ... )
set DB = dbEngine.OpenDatabase(theNormalExternalExcellFile,....)
For the SQL statement, in pseudo-code, I want this:
SELECT fields
FROM [Table$] ' a normal external excel file
LEFT JOIN [an external CSV, comma delimited file]
ON...
GROUP...
I can successfully import an XLXS, or the CSV, independently, in a simple SQL statement, yet when I place the outside file references within an SQL's FROM clause, I get one of two errors, depending on how I play with the code: an Invalid File Path, or an error in the FROM Clause. The path is -not- invalid.
The error is shown, below, where it occurs, at the recordset instruction.
I also provide alternative SQL strings, which I had played with to test where in the code the error is generated.
'the Seating Chart
strPathSource = ThisWorkbook.Worksheets("Logic").Range("rngPathSource")
'strFileNameSource = ThisWorkbook.Worksheets("Logic").Range("rngFileNameSource")
'strFileNameSourceWOExt = Left(strFileNameSource, Len(strFileNameSource) - 4)
'the attendance
strPathAttendance = ThisWorkbook.Worksheets("Logic").Range("rngPathAttendance")
strFileNameAttendance = ThisWorkbook.Worksheets("Logic").Range("rngFileNameAttendance")
strFolderAttendance = ThisWorkbook.Worksheets("Logic").Range("rngFolderAttendance")
strFileNameAttendanceWOExt = Left(strFileNameAttendance, Len(strFileNameAttendance) - 4)
Set dbE = CreateObject("Dao.DBEngine.120")
Set db = dbe.OpenDatabase(strPathSource, True, False, "Excel 12.0;HDR=Yes")
''Set db = DAO.OpenDatabase(strFolderAttendance, True, False, "text;HDR=Yes;FMT=Delimited(,)")
'[Master$] is a tab on the spreadsheet at strPathSource
'[Attendance#csv]
' This reference to the table at strPathAttendance which otherwise works: [Attendance#csv]
' when not inside the FROM clause
strSQL = _
"SELECT tM.Job, Count(tA.Name) AS CountOfName" _
& " FROM [Master$] tM" _
& " LEFT JOIN" _
& " (SELECT * FROM [text;HDR=Yes;FMT=Delimited(,);Database='" _
& strPathAttendance & "'].[" & strFileNameAttendanceWOExt & "#csv]) tA" _
& " ON (tM.GivenName = tA.GivenName) AND (tM.SurName = tA.SurName)" _
& " GROUP BY tM.Job" _
& " ORDER BY tM.Job, Count(tA.Name)"
'Debug.Print strSQL
' This is the reported value for the string, strSQL, particularly the FROM clause:
' SELECT tM.Job, Count(tA.Name) AS CountOfName FROM [Master$] tM LEFT JOIN
' (SELECT * FROM
' [text;HDR=Yes;FMT=Delimited(,);Database=T:\Solutions Team Shared Folder\Seats -
' Attendance\Attendance.csv].[Attendance#csv]) tA
' ON (tM.GivenName = tA.GivenName) AND (tM.SurName = tA.SurName)
' GROUP BY tM.Job ORDER BY tM.Job, Count(tA.Name)
'' putting a single or double quote, around the database path, does not change the error
Set rstR = db.OpenRecordset(strSQL)
'Error:
' 'T:\...\...\Attendance.csv' is not a valid path. Make sure that
' the path name is spelled correctly and that you are connected to the server
' on which the file resides.
' ALT SQL strings, to test what's going on.
'strSQL = _
' "Select * FROM [Attendance#csv]"
'strSQL = _
' "Select * FROM (Select * FROM [Excel 12.0;HDR=Yes;Database=" & strPathSource & "].[Master$])"
'strSQL = _
' "SELECT * FROM [text;HDR=Yes;FMT=Delimited(,);Database=" _
' & strPathAttendance & "].[" & strFileNameAttendanceWOExt & "#csv]"
'strSQL = _
' "Select * FROM [Excel 12.0;HDR=Yes;Database=" & strPathSource & "].[Master$]"
When connected to text files with Jet/ACE SQL, the database parameter needs to reference the directory path not any specific text file. The period qualifier will then specify the individual file.
Therefore, simply remove the file name and extension from strPathAttendance (without quotes). So query should look like the below:
SELECT tM.Job, Count(tA.Name) AS CountOfName
FROM [Master$] tM
LEFT JOIN
(SELECT * FROM
[text;HDR=Yes;FMT=Delimited(,);Database=T:\Solutions Team Shared Folder\Seats -
Attendance].[Attendance#csv]) tA
ON (tM.GivenName = tA.GivenName) AND (tM.SurName = tA.SurName)
GROUP BY tM.Job
ORDER BY tM.Job, Count(tA.Name)

Delete table in access with String with 3 values

Good day,
Im getting an error (syntax error missing operator in a query expression for "and monitorNumber = Monit)
SQLDel = "DELETE FROM HBAU WHERE Peoplesoft ID ='" & PSID & "' and DATE =#" & InputDate & "# and MonitorNumber = Monit"
can anyone tell me whats missing...
If Monit is VBA variable, try this one:
SQLDel = "DELETE FROM HBAU WHERE [PeoplesoftID] =" & PSID & " and [DATE] =#" & InputDate & "# and [MonitorNumber] = " & Monit
also should Peoplesoft ID be PeoplesoftID? Note if your PeoplesoftID has numeric type, you don't need single quotes around PSID.
Aslo you may want to read this: Global Variables in SQL statement

Application Pool Status in IIS 7

I want to get status of a Application Pool. I have vbscript taken from here.
strArgAppPool = Wscript.Arguments.Unnamed.Item(0)
Const noError = False
' Establish the connection to the WMI provider
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
' Search the AppPool passed as argument in the list of application pools
Set oAppPool = oWebAdmin.Get("ApplicationPool.Name='" & strArgAppPool & "'")
' Create nice messages for pool states
Select Case oAppPool.GetState
Case 0
StateDescription = "STARTING"
outputStatus = "WARNING! "
outputCode = 1
Case 1
StateDescription = "STARTED"
outputStatus = "OK! "
outputCode = 0
Case 2
StateDescription = "STOPPING"
outputStatus = "WARNING! "
outputCode = 1
Case 3
StateDescription = "STOPPED"
outputStatus = "CRITICAL!! "
outputCode = 2
Case 4
StateDescription = "UNKNOWN"
outputStatus = "UNKNOWN? "
outputCode = 3
Case Else
StateDescription = "UNDEFINED VALUE"
outputStatus = "UNKNOWN? "
outputCode = 3
End Select
' Output
Wscript.Echo outputStatus & oAppPool.Name & ": " & StateDescription
' Error handling
If noError = true Then
' Error message
Wscript.echo "UNKNOWN: Error during the WMI query for app pool " & strArgAppPool & " !"
' Exit & return code
WScript.Quit(3)
Else
' Clean exit
WScript.Quit(outputCode)
End If
Through a batch file I am trying to run it as
status1.vbs "DefaultAppPool"
But I ended up with this
Is it some service is not started? I have tried running the vb script directly. I have tried passing arguments without quotes and all similar stuff. I don't write scripts, but got to do it this time.
Error dialog indicates line 5, Set oWebAdmin = GetObject("winmgmts:root\WebAdministration"). I have tried everything I could in last 5 hours. I have a readymade script and I am not able to run it. Shame and was not willing post this question all this while. But lost in end. Thanks for any help.
Also I have a working script for IIS 6. I am calling this script through PsExec on a remote server. But that's not working in IIS 7. Let me know if anyone want me to post it. Also I am using IIS 7 and Server 2008 R2 now and will be running this script using PsExec on remote server.
You don't have the role service IIS Management Scripts and Tools installed. Launch Server Manager, go to Roles → Web Server (IIS), and install the missing service.

Resources