Reading CSV in Recordset? - asp-classic

Let me start off by saying that I am very greatful to have a place to go to when I need help with some code and I'm even more thankful when I see people trying to help out, so for everyone here Thank you for looking at my question/problem even if you don't have an answer.
With that said, on with my question/problem:
I have been trying to get this to work but I cannot seem to find the syntax error!! :-(
Can anyone please help me...
Here is the code:
dim strPathtoCSVFolder,strPathtoCSVFile,strPathtoCSVFileTWO
strPathtoCSVFolder="D:\classic_asp\test\" & Request.QueryString("XTNO") & "\Data\"
strPathtoCSVFile="Unit_" & Request.QueryString("XTNO") & "_Year_" & Request.QueryString("year") & "_Q_" & Request.QueryString("q") & "_MERGE_DataCsv.csv"
strPathtoCSVFileTWO="Unit_" & Request.QueryString("XTNO") & "_Year_" & Request.QueryString("year") & "_Q_" & Request.QueryString("q") & "_MERGE_DataCsv_SORTED.csv"
Set Conn = CreateObject("ADODB.Connection")
Set RS = CreateObject("ADODB.Recordset")
Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPathtoCSVFolder & ";Extended Properties=""text;HDR=YES;FMT=Delimited"""
dim strDirInfoX
strDirInfoX="SELECT STATE, SUM(GALLONS) as Total FROM " & strPathtoCSVFile & " GROUP BY STATE "
'''''' response.write strDirInfoX
dim strTxttoMem
dim strsource
strsource="RS.Open " & strDirInfoX & " , Conn, 1, 3, &H0001"
RS.Open strsource
'response.write strsource
redim FieldNames(rs.fields.count)
redim FieldTypes(rs.fields.count)
For i = 0 To (rs.Fields.Count - 1)
FieldNames(i) = cstr(trim(rs.Fields.Item(i).Name))
FieldTypes(i) = cstr(trim(rs.Fields.Item(i).Type))
Next
RS.Close
RS.Open strDirInfoX, Conn, 3, 3, &H0001
Do Until RS.EOF
'''' for i=0 to ubound(FieldNames)-1
''' response.write(FieldNames(i) & " = " & RS.Fields.Item(FieldNames(i)) & "<br>")
strTxttoMem=strTxttoMem & RS("STATE") & RS("total")
'' next
RS.MoveNext
Loop
RS.Close
Conn.Close
dim fs,tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.CreateTextFile(strPathtoCSVFolder & strPathtoCSVFileTWO)
tfile.WriteLine(strTxttoMem)
tfile.close
set tfile=nothing
set fs=nothing
Thank you so much for any help...

Well, without running your code, I spotted an error in this part:
dim strsource
strsource="RS.Open " & strDirInfoX & " , Conn, 1, 3, &H0001"
RS.Open strsource
or to shorten it, you are doing this:
RS.Open "RS.Open " & strDirInfoX & " , Conn, 1, 3, &H0001"
change it to RS.Open strDirInfoX, Conn, 1, 3, &H0001 and that part will run better.

This is almost impossible to answer, there could be multiple errors and much depends on what is declared before, eg an option explicit makes a huge difference (and is advisable).
Since debugging in the browser is difficult at best, you copy this code - that comes from an asp file i guess - and put it in a vbs script, replace the response.write with wscript.echo and run the code.
Then you get an error at some line, correct it and so on, afterward replace the echos's by response.write's and you'r done.
I also recommend useing Firefox and the Firebug plugin to do your testing, you will get more debugging info there, at least use the developer view in Chrome or IE
Success..

Been some time working on VBScript but shouldnt tfile.close be tfile.Close?

Did you try reading the file as a text file rather than connecting to it with an ADODB connection? Since it is a CSV file, you might be able to read it as a plain text file. You can split the content with comma and loop and get what you want.
If you want to access it using ADODB connection, try saving the file with an xlsx extention(Either copy the contents through code or save it manually. The same code might work).
Shamelessly adding a link to my blog on ADO
http://www.blogger.com/blogger.g?blogID=3033014869583885023#editor/target=post;postID=8274119342550879092

Related

vb.net string concat adds vbCrlf literal to the string

I am trying to build a string that includes a newline character and is getting the weirdest result. This string is going to be stored in a SQL database to be later used as part of an email. My code is the following:
Dim strBody As String = "Andy," & Environment.NewLine
When I inspect the value of strBody during a debugging session, it is the following:
"Andy," & vbCrlf
I am obviously expecting is to be more like:
"Andy,"
Knowing that what is after the , is a hidden character.
Ultimately, the problem is... when I include strBody as part of my SQL insert statement, it literally shows up as the following within my SQL insert statement:
'Andy," & vbCrLf & "'
I was using this code yesterday and it worked fine. I am using similar code within another function of the same asp.net project and it works fine. I have tried using + instead of &, I have tried to use vbCrLf instead of Environment.NewLine, I have tried using stringbuilder, I have tried using string.concat. All with the same results where the & vbCrLf is included in strBody.
Is there a setting that I accidentally changed?
I know this is a weird one... Any help is greatly appreciated.
This is only Visual Studio showing you that there is new line character (vbCrLf or Environment.NewLine). If you use that string anywhere, it will be stored correctly.
I believe you will need to use some combination of Char(10) and Char(13):
Dim strBody As String = "'Andy,'" & " + CHAR(13)+CHAR(10) + "
There is a discussion about these and other methods on this thread.
You can do like this if you just need to insert Environment.NewLine inside database.
Dim a As String = """ & Environment.NewLine & """
Dim strBody As String = String.Format("Andy,{0}", a)
'"Andy," & Environment.NewLine & ""

Classic ASP and MS Access Batch Update

I am using the following code to update an Access Database with Classic Asp:
<%# Language=VBScript %>
<% Option Explicit %>
<%
Response.Buffer = True
'First, we need to get the total number of items that could be updated
Dim iCount
iCount = Request("Count")
'We need to obtain each cost and ID
Dim strstudent, strcourse, strgrade, strcomments
'We will also need to build a SQL statement
Dim strSQL
Dim conn
set conn=server.CreateObject("ADODB.connection")
conn.ConnectionString="provider=Microsoft.jet.OLEDB.4.0;data source=C:\db\agsystem.mdb"
conn.Open
'Now, we want to loop through each form element
Dim iLoop
For iLoop = 0 to iCount
'student data
strstudent = Request(iLoop & ".Student")
'course data
strcourse = Request(iLoop & ".course")
'grade
if isNull(Request(iLoop & ".grade")) or Request(iLoop & ".grade")="" then
strgrade="null"
else
strgrade= Request(iLoop & ".grade")
end if
if isNull(Request(iLoop & ".comments")) or Request(iLoop & ".comments")="" then
strcomments=null
else
strcomments=Request(iLoop & ".comments")
end if
strSQL = "UPDATE testing SET semester2 = " & strgrade & ", commentss=" & "'" & strcomments & "'" & " WHERE newstudentid = " &"'"& strstudent&"'" & " and Courseid = " & "'"& strcourse & "'"
conn.Execute strSQL
Next
conn.Close
Set conn = Nothing
Response.Redirect "protected.asp"
%>
The problem is that when tested in the server it updates without any issues. But when access from a wireless network it won't update.
The target table to update has about 27,000 records
I need to know what I'm doing wrong or if there is another approach.
I found the error after carefully analyzing the situation.
Records in primary key that have spaces for example '2 OR 13' will not update. But records without spaces in primary key like '2CEN13' updates perfectly. I did not had time to solve it in my asp code, so i edited all records with spaces and that solve the problem.

Classic ASP Error: Operation is not allowed when the object is closed

I have cruised and implemented code from some of the other responses to this question, but I'm still having no luck. I am still getting the error.
If ((bReport And bIsDate And CheckPermissions("lotsales")) Or Request.QueryString("report")) Then
OpenDB
Dim oRs, sSQL, sSQL2, iCancellations, iSales, sDate, sInitDate, sEndDate, iPhaseID, iPhaseNumber, rowCount
sInitDate = Request("startDate")
sEndDate = Request("endDate")
sSQL = "sp_get_lot_sales_test '" & sInitDate & "', '" & sEndDate & "', " & sPhase & ", '" & sReportView & "'"
'response.write vbNewLine & "<!-- sql: " & sSQL & "-->" & vbNewLine
'response.write sSQL
'response.Flush
Set oRs = ExecuteCommand(sSQL,1)
End If
And then here is where the error occurs -
If (oRs.EOF) Then <-- fails here
Response.Write("<TR><TD ALIGN=""center"">There is no data to report on!</TD></TR>")
Else
Do While Not oRs.EOF
As a last resort I am going to go back to the stored procedure and deconstruct it to make sure all is well there. Does anyone have any insight as to why I might be getting the error? I am not issuing a close anywhere.
Here is the ExecuteCommand function -
Function ExecuteCommand(s,i)
On Error Resume Next
Set ExecuteCommand = oDBc.Execute(s, , i)
End Function
This may be old, but I frequently come across that error (operation is not allowed when object is closed).
What I do is in the stored procedure, I add the follwing:
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
right below the AS in the procedure.
That's all I do and the problem goes away.
I am maintaining some old Classic ASP code for a client, code that we took over from a prior developer, and this bug drove me crazy for 4 hours.
I finally discovered a few PRINT statements in the associated SQL stored procedure, which were there for troubleshooting or checking values but don't actually return rows, yet they caused this to fail:
Set cnContentDB = Server.CreateObject("ADODB.Connection")
cnContentDB2.Open sString
sSQL = "EXEC YourStoredProc"
Set oRS2 = Server.CreateObject("ADODB.Recordset")
oRS2.Open sSQL, cnContentDB
if not oR2.EOF then 'THIS WAS GIVING THE ERROR,
'EVEN THOUGH THE STORED PROC ALWAYS RETURNS RECORDS
I removed the Print statements, and the error went away.
Although this is years old, we still end up here looking for solutions.
The cause of this error for me was that the User did not have Execute permission on the Stored Procedure. Granting Execute permission resolved the error.
You need a connection object.
set conn = server.CreateObject("adodb.connection")
set oRs = conn.execute(sSql)

Infinite classic Asp do while loop

I have this same type of loop running on several pages, but the one that I said I'd get done in 1 day just... Ignores the out.movenext and prints only the first result out of a possible 10 results until it crashes. The SQL is fine. I got it with a tracer.
Changes:
I originally had the movenext last before the loop - but moved it up one line for tracing. Tried (out = out.movenext , out = out.next) to see if it would do anything. And I tried putting an integer count in to have it stop after 20 loops so I can debug it faster. The int changes, the data prints, but out doesn't advance.
strSQL = "SELECT [RecordID],[SubmitDate],[DataEntered] FROM [ManagerFileReview] where submitdate = '" & timetap & "'"
out = cnt.execute(strSQL)
out.movefirst
response.write "<table>"
Do while not out.eof
response.write "<tr><td>"
response.write "<table><thead></thead>"
response.write "<tr><td>Submit Date:</td><td>" & out(1) & "</td></tr>"
response.write "<tr><td>Data Entered:</td><td>" & out(2) & "rrrrrrrrrrr</td></tr>"
out.movenext
response.write "passed movenext</table></td></tr>"
loop
response.write "</table>"
Edit: Forgot the "SET" before the cnt.execute
The logic looks OK, unless I'm missing something. Even though out isn't listed as a reserved word with MS, I do wonder if it's the problem.
Found it.
Didn't have SET before the out = cnt.execute(strSQL)
Should have been
set out = cnt.execute(strSQL)

How to properly report / handle classic asp page errors and database errors

I have been trying to create an error handling path for our classic asp website. I have been searching for information for 3hrs now and have not found much even here on stack overflow. So if you can point me towards a duplicate great ... I couldn't find anything although it must exist.
My plan is the following ...
Have proper error handling in the stored procedures. Any errors that occur get inserted into an error table and are also raised back up to the application.
Have "On error resume next" set on the page. Then check the connection.errors collection for errors. As well as Server.GetLastError() property.
If there are any redirect to a page to to display safe error information and insert another record into another database table to tie the page name where the error occurred to the already existing database error in the database table mentioned above for later debugging purposes.
I have created the following page to to begin testing this out. However it is not working.
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
on error resume next
cmd.CommandText = "spReturnDBException"
cmd.CommandTimeout = 30 ' 2 minutes
cmd.Execute
dim objErr
set objErr = Server.GetLastError()
if objError.ASPCode <> 0 then
response.write("ASPCode=" & objErr.ASPCode)
response.write("")
response.write("ASPDescription=" & objErr.ASPDescription)
response.write("")
response.write("Category=" & objErr.Category)
response.write("")
response.write("Column=" & objErr.Column)
response.write("")
response.write("Description=" & objErr.Description)
response.write("")
response.write("File=" & objErr.File)
response.write("")
response.write("Line=" & objErr.Line)
response.write("")
response.write("Number=" & objErr.Number)
response.write("")
response.write("Source=" & objErr.Source)
else
response.write("There's nothing wrong.")
end if
Dim objErr2
for each objErr2 in objConn.Errors
response.write("<p>")
response.write("Description: ")
response.write(objErr2.Description & "<br />")
response.write("Help context: ")
response.write(objErr2.HelpContext & "<br />")
response.write("Help file: ")
response.write(objErr2.HelpFile & "<br />")
response.write("Native error: ")
response.write(objErr2.NativeError & "<br />")
response.write("Error number: ")
response.write(objErr2.Number & "<br />")
response.write("Error source: ")
response.write(objErr2.Source & "<br />")
response.write("SQL state: ")
response.write(objErr2.SQLState & "<br />")
response.write("</p>")
next
Free(cmd)
Free(con)
In the stored procedure I simply RAISERROR( N'Lets throw an error because I want to!', 17, 0 );
The output I get every time is as follows ...
ASPCode=ASPDescription=Category=Column=-1Description=File=Line=0Number=0Source=
Description: Help context: Help file: Native error: Error number: Error source: SQL state:
Why am I not getting any error information on the conn.Errors loop?
Resolved.
I was using a different connection object for the loop that loops through the connection.Errors ... copy paste error.
However on a side note ... I found it extremely difficult to find information on how to even do what I've so far.
here's some additional resources:
some general topics:
http://social.msdn.microsoft.com/search/en-US?query=Server.GetLastError%28%29&refinement=89
a specific example:
http://support.microsoft.com/kb/224070

Resources