Output XMLHttp response line by line - vbscript

I need to grab a log file from a URL and then print the log file line by line. I can successfully get the file this way:
Dim filePath,fileName
filePath = "http://localhost/osat/spawn_pi_logs"
fileName = "/Spawn.log"
FilePath = filePath & fileName
Set req = CreateObject("Msxml2.XMLHttp.6.0")
req.open "GET", FilePath, False
req.send
If req.Status = 200 Then
Response.Write "Found the file<br>"
Response.Write req.responsetext
End If
That code writes the text of my log file to the screen in one huge ugly blob. I want to walk through it, format it, search it, etc and write it out with code similar to this:
Do While Not TextStream.AtEndOfStream
Dim sLine
sLine = TextStream.readLine
sLine = sLine & "<br>"
Response.Write sLine
Loop
However, how do I convert my req object (which has a generic stream at req.ResponseStream) and convert it to a Text Stream?

You can save the response to a text file by incorporating an ADO Stream and writing the responseBody:
If req.Status = 200 Then
With CreateObject("ADODB.Stream")
.Type = 1 'adTypeBinary
.Open
.Write req.responseBody
.SaveToFile "c:\myfile.txt"
.Close
End With
End If
Then you can open your text file using OpenTextFile() and read it as a TextStream.
But, you could just split your responseText into an array with the Split() function and not worry about saving and reading a text file:
If req.Status = 200 Then
' Create a line array...
a = Split(req.responseText, vbCrLf)
For i = 0 To UBound(a)
' Process each line
Next
End If

Thank you PHD443322. This code works great:
a = Split(req.responsetext, vbCrLf)
for each x in a
response.write(x & "<br />")
next
The key was not only the Split command, but also using the VBScript vbCrLf constant to set the delimiter.

Related

How to append text from one file to another file after a specific line using VBScript?

I need to insert the contents of a text file into another existing text file after the line with a specific word in it.
Here is my code.
'//OPEN FILE and READ
Set objFileToRead = fso.OpenTextFile(ActiveDocument.Path & "\file.txt", 1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close
objStartFolder = ActiveDocument.Path
Set objFolder = fso.GetFolder(objStartFolder)
Set colFiles = objFolder.files
For Each objFile In colFiles
If fso.GetExtensionName(objFile.Name) = "opf" Then
filename = objFile.Name
End If
Next
MsgBox filename
'///PASTE
If fso.FileExists(ActiveDocument.Path & "\" & filename) Then
MsgBox filename
Set objFile = fso.OpenTextFile(ActiveDocument.Path & "\" & filename)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine, "<manifest>") = 1 Then
MsgBox filename
objFile.WriteLine vbCrLf & strFileText
objFile.Close
End If
Loop
End If
I get a bad file error in the following line
objFile.WriteLine vbCrLf & strFileText
Can anyone please tell me what is wrong and what I have to do?
You can't write to a file that was opened for reading.
Either write the modified content to a temporary file and replace the original file with it afterwards:
p = fso.BuildPathActiveDocument.Path, filename)
Set f1 = fso.OpenTextFile(p)
Set f2 = fso.OpenTextFile(p & ".tmp", 2, True)
Do Until f1.AtEndOfStream
line = f1.ReadLine
f2.WriteLine line
If InStr(line, "<manifest>") = 1 Then f2.WriteLine strFileText
Loop
f1.Close
f2.Close
fso.DeleteFile p, True
fso.GetFile(p & ".tmp").Name = filename
or read the entire content into memory before writing the modified content back to the original file:
p = fso.BuildPathActiveDocument.Path, filename)
txt = Split(fso.OpenTextFile(p).ReadAll, vbNewLine)
Set f = fso.OpenTextFile(p, 2)
For Each line In original
f.WriteLine line
If InStr(line, "<manifest>") = 1 Then f.WriteLine strFileText
Next
f.Close
Note that the latter shouldn't be used for large files, lest your computer come grinding to a halt due to memory exhaustion.

Deleting ONLY trailing spaces and spaces in empty fields

I have a CSV with data like below
"01","567 "," ","This is a message"
I need to delete the trailing spaces and spaces in blank fields, while leaving the spaces in between data.
My code:
Dim inStream : Set inStream...
With inStream
.open
.type = 2
.charset = "utf-8"
.loadfromfile src
Dim outStream : Set outStream...
outStream.open
outStream.type = 2
While Not .EOS
arrLine = split(.read, ",")
strLine = trim(arrLine(0))
If ubound(arrLine) > 0 Then
For intField = 1 To ubound(arrLine)
strLine = strLine & "," & trim(arrLine(intField))
Next
End If
outStream.write(strLine)
outStream.savetofile dest, create
WEnd
outStream.close
.close
End With
You can split your CSV line into an array and then loop through and use the 'Trim' function on each item.
There are surprisingly good vbscript examples like this on google.

Text files handles differently

I am trying to read from a csv.txt file using Ado Recordset
I get no results back when trying..
When I copy the contents of the original file into a new text file, and read from that file, it works just fine.
Any ideas what the reason for this might be?
The second file is smaller in size, about 1/2. That's the only difference I can see. This is driving me mad :-)
'Edit
Update with code & schema.ini
Code:
Sub ImportTextFiles()
Dim objAdoDbConnection As ADODB.Connection
Dim objAdoDbRecordset As ADODB.Recordset
Dim strAdodbConnection As String
Dim pathSource As String
Dim filename As String
pathSource = "C:\Users\me\Desktop\Reports\"
filename = "test1.txt"
'filename = "test2.txt"
strAdodbConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & pathSource _
& ";Extended Properties=""text;HDR=yes;FMT=Delimited"";"
Set objAdoDbConnection = CreateObject("Adodb.Connection")
Set objAdoDbRecordset = CreateObject("ADODB.Recordset")
With objAdoDbConnection
.Open (strAdodbConnection)
With objAdoDbRecordset
.Open "Select top 10 * FROM " & filename & " WHERE [Date] > #01/01/2000# ", objAdoDbConnection, adOpenStatic, adLockOptimistic, adCmdText
If Not objAdoDbRecordset.EOF Then objAdoDbRecordset.MoveFirst
Do While Not objAdoDbRecordset.EOF
Debug.Print "Field(0): " & objAdoDbRecordset(0).Value
objAdoDbRecordset.MoveNext
Loop
.Close
End With
.Close
End With
Set objAdoDbRecordset = Nothing
Set objAdoDbConnection = Nothing
End Sub
Schema.ini:
[Test1.txt]
col1=date text
col2=interval integer
col3=application text
[Test2.txt]
col1=date text
col2=interval integer
col3=application text
notepadd++ gave me the answer, file1 is ucs-2 encoded, the newly created utf-8

"Type Mismatch" when downloading image

I'm creating a program that helps me download images from a weather website, so I can get radar images. It creates a file named "radar" and then the time. For example if it was 5:00 PM it would be named Radar500.png.
The downloading works fine, but it says I have an error on a certain line:
Const adSaveCreateOverWrite = 2
Const adTypeBinary = 1
if hour(time) > 12 then
a=hour(time)-12
else
if hour(time) = 0 then
a="12"
else
a=hour(time)
b=minute(time)
end if
end if
b=minute(time)
strSource = ""
strDest = "C:\Users\Gabriel\Desktop\Overnight weather\radar"+a+"s"+b+".jpg"
WScript.Echo "path: "+strDest
'*****************************************************************
'** Download the image
strResult = GetImage(strSource, strDest)
If strResult = "OK" Then
wscript.quit(0)
Else
wscript.quit(1)
End If
Function GetImage(strPath, strDest)
Dim objXMLHTTP, nF, arr, objFSO, objFile
Dim objRec, objStream
'create XMLHTTP component
Set objXMLHTTP = CreateObject("Microsoft.XMLHTTP")
'get the image specified by strPath
objXMLHTTP.Open "GET", strPath, False
objXMLHTTP.Send
'check if retrieval was successful
If objXMLHTTP.statusText = "OK" Then
'create binary stream to write image output
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open
objStream.Write objXMLHTTP.ResponseBody
objStream.SavetoFile strDest, adSaveCreateOverwrite
objStream.Close
GetImage = "OK"
Else
GetImage = objXMLHTTP.statusText
End If
End Function
They say the error is at Line 29 Char 1.
Use strDest = "C:\Users\...\radar" & a & "s" & b & ".jpg". As per MSDN: Addition Operator (+) (VBScript)
Although you can also use the + operator to concatenate two
character strings, you should use the & operator for concatenation
to eliminate ambiguity. When you use the + operator, you may not be
able to determine whether addition or string concatenation will occur.
The type of the expressions determines the behavior of the +
operator in the following way:
If Then
Both expressions are numeric Add
Both expressions are strings Concatenate
One expression is numeric and the other is a string Error: type mismatch
...
Your script should work with next changes:
assign a valid strSource value, e.g. strSource = "http://www.goes.noaa.gov/FULLDISK/GMIR.JPG"
objXMLHTTP.Open "GET", strSource, False. Note strSource instead of your strDest

remove nul characters from text file using vbs

I have text files that are approximately 6MB in size. There are some lines that contain the NULL (Chr(0))character that I would like to remove.
I have two methods to do this: using Asc()=0 but this takes approximately 50s to complete, the other method uses InStr (line, Chr(0)) =0 (fast ~ 4sec)but the results remove vital info from the lines which contain the NULL characters.
First line of text file as example:
##MMCIBN.000NULL7NULL076059NULL7653NULL1375686349NULL2528NULL780608NULL10700NULL\NULL_NC_ACT.DIR\CFG_RESET.INI
First method (works but VERY slow)
function normalise (textFile )
Set fso = CreateObject("Scripting.FileSystemObject")
writeTo = fso.BuildPath(tempFolder, saveTo & ("\Output.arc"))
Set objOutFile = fso.CreateTextFile(writeTo)
Set objFile = fso.OpenTextFile(textFile,1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
If Asc(strCharacters) = 0 Then
objOutFile.Write ""
nul = true
Else
if nul = true then
objOutFile.Write(VbLf & strCharacters)
else
objOutFile.Write(strCharacters)
end if
nul = false
End If
Loop
objOutFile.close
end function
The output looks like this:
##MMCIBN.000
7
076059
7653
1375686349
2528
780608
10700
\
_NC_ACT.DIR\CFG_RESET.INI
Second method code:
filename = WScript.Arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
sDate = Year(Now()) & Right("0" & Month(now()), 2) & Right("00" & Day(Now()), 2)
file = fso.BuildPath(fso.GetFile(filename).ParentFolder.Path, saveTo & "Output " & sDate & ".arc")
Set objOutFile = fso.CreateTextFile(file)
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
line = f.ReadLine
If (InStr(line, Chr(0)) > 0) Then
line = Left(line, InStr(line, Chr(0)) - 1) & Right(line, InStr(line, Chr(0)) + 1)
end if
objOutFile.WriteLine line
Loop
f.Close
but then the output is:
##MMCIBN.000\CFG_RESET.INI
Can someone please guide me how to remove the NULLS quickly without losing information. I have thought to try and use the second method to scan for which line numbers need updating and then feed this to the first method to try and speed things up, but quite honestly I have no idea where to even start doing this!
Thanks in advance...
It looks like the first method is just replacing each NULL with a newline. If that's all you need, you can just do this:
Updated:
OK, sounds like you need to replace each set of NULLs with a newline. Let's try this instead:
strText = fso.OpenTextFile(textFile, 1).ReadAll()
With New RegExp
.Pattern = "\x00+"
.Global = True
strText = .Replace(strText, vbCrLf)
End With
objOutFile.Write strText
Update 2:
I think the Read/ReadAll methods of the TextStream class are having trouble dealing with the mix of text and binary data. Let's use an ADO Stream object to read the data instead.
' Read the "text" file using a Stream object...
Const adTypeText = 2
With CreateObject("ADODB.Stream")
.Type = adTypeText
.Open
.LoadFromFile textFile
.Charset = "us-ascii"
strText = .ReadText()
End With
' Now do our regex replacement...
With New RegExp
.Pattern = "\x00+"
.Global = True
strText = .Replace(strText, vbCrLf)
End With
' Now write using a standard TextStream...
With fso.CreateTextFile(file)
.Write strText
.Close
End With
I tried this method (update2) for reading a MS-Access lock file (Null characters terminated strings in 64 byte records) and the ADODB.Stream didn't want to open an already in use file. So I changed that part to :
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(Lfile)
z = f.Size
set ts = f.OpenAsTextStream(ForReading, 0) 'TristateFalse
strLog = ts.Read(z)
ts.Close
set f = nothing
' replace 00 with spaces
With New RegExp
.Pattern = "\x00+"
.Global = True
strLog = .Replace(strLog, " ")
End With
' read MS-Access computername and username
for r = 1 to len(strLog) step 64
fnd = trim(mid(strLog,r, 32)) & ", " & trim(mid(strLog,r+32, 32)) & vbCrLf
strRpt = strRpt & fnd
next

Resources