Classic ASP Image upload handler for tinymce [duplicate] - asp-classic

I want to create a page with asp-classic where users can upload files or zipped folders.
I've searched in Google but every solution I have found uses a third-party file.
But I haven't been able to get those files to work.

long time since I've done that but we used an upload without third party components, just two vbscript classes (solution credit goes to Lewis Moten).
It looks like you can still find this "Lewis Moten solution" in the wild
If you include the clsUpload file, further upload process is as simple as:
Dim objUpload
Dim strFile, strPath
' Instantiate Upload Class '
Set objUpload = New clsUpload
strFile = objUpload.Fields("file").FileName
strPath = server.mappath("/data") & "/" & strFile
' Save the binary data to the file system '
objUpload("file").SaveAs strPath
Set objUpload = Nothing
That's all for the server-side...
On the client-side you just need your File input
<form name="Upload" enctype="multipart/form-data" method="post" action="clsUpload.asp">
<div>Upload file: </div>
<div><INPUT TYPE="file" NAME="file" >
<input type="button" name="FileUpload" value="Upload File"> </div>
</form>
Hope this helps..
Edit 23 June 2014
As pointed out by Dave Wut my reference to the solution "in the wild" was not completely consistent with the code snippet provided. Hereby the full classes that I had used historically (comments trimmed to stay below the 30000 SO limit). It was an early version of the Lewis Moten solution found at http://planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=8525&lngWId=4
1) Contents of clsUpload.asp
<!--METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.5 Library"
UUID="{00000205-0000-0010-8000-00AA006D2EA4}"
VERSION="2.5"
-->
<!--#INCLUDE FILE="clsField.asp"-->
<%
' ------------------------------------------------------------------------------
' Author: Lewis Moten
' Date: March 19, 2002
' ------------------------------------------------------------------------------
' Upload class retrieves multi-part form data posted to web page
' and parses it into objects that are easy to interface with.
' Requires MDAC (ADODB) COM components found on most servers today
' Additional compenents are not necessary.
'
Class clsUpload
' ------------------------------------------------------------------------------
Private mbinData ' bytes visitor sent to server
Private mlngChunkIndex ' byte where next chunk starts
Private mlngBytesReceived ' length of data
Private mstrDelimiter ' Delimiter between multipart/form-data (43 chars)
Private CR ' ANSI Carriage Return
Private LF ' ANSI Line Feed
Private CRLF ' ANSI Carriage Return & Line Feed
Private mobjFieldAry() ' Array to hold field objects
Private mlngCount ' Number of fields parsed
' ------------------------------------------------------------------------------
Private Sub RequestData
Dim llngLength ' Number of bytes received
' Determine number bytes visitor sent
mlngBytesReceived = Request.TotalBytes
' Store bytes recieved from visitor
mbinData = Request.BinaryRead(mlngBytesReceived)
End Sub
' ------------------------------------------------------------------------------
Private Sub ParseDelimiter()
' Delimiter seperates multiple pieces of form data
' "around" 43 characters in length
' next character afterwards is carriage return (except last line has two --)
' first part of delmiter is dashes followed by hex number
' hex number is possibly the browsers session id?
' Examples:
' -----------------------------7d230d1f940246
' -----------------------------7d22ee291ae0114
mstrDelimiter = MidB(mbinData, 1, InStrB(1, mbinData, CRLF) - 1)
End Sub
' ------------------------------------------------------------------------------
Private Sub ParseData()
' This procedure loops through each section (chunk) found within the
' delimiters and sends them to the parse chunk routine
Dim llngStart ' start position of chunk data
Dim llngLength ' Length of chunk
Dim llngEnd ' Last position of chunk data
Dim lbinChunk ' Binary contents of chunk
' Initialize at first character
llngStart = 1
' Find start position
llngStart = InStrB(llngStart, mbinData, mstrDelimiter & CRLF)
' While the start posotion was found
While Not llngStart = 0
' Find the end position (after the start position)
llngEnd = InStrB(llngStart + 1, mbinData, mstrDelimiter) - 2
' Determine Length of chunk
llngLength = llngEnd - llngStart
' Pull out the chunk
lbinChunk = MidB(mbinData, llngStart, llngLength)
' Parse the chunk
Call ParseChunk(lbinChunk)
' Look for next chunk after the start position
llngStart = InStrB(llngStart + 1, mbinData, mstrDelimiter & CRLF)
Wend
End Sub
' ------------------------------------------------------------------------------
Private Sub ParseChunk(ByRef pbinChunk)
' This procedure gets a chunk passed to it and parses its contents.
' There is a general format that the chunk follows.
' First, the deliminator appears
' Next, headers are listed on each line that define properties of the chunk.
' Content-Disposition: form-data: name="File1"; filename="C:\Photo.gif"
' Content-Type: image/gif
' After this, a blank line appears and is followed by the binary data.
Dim lstrName ' Name of field
Dim lstrFileName ' File name of binary data
Dim lstrContentType ' Content type of binary data
Dim lbinData ' Binary data
Dim lstrDisposition ' Content Disposition
Dim lstrValue ' Value of field
' Parse out the content dispostion
lstrDisposition = ParseDisposition(pbinChunk)
' And Parse the Name
lstrName = ParseName(lstrDisposition)
' And the file name
lstrFileName = ParseFileName(lstrDisposition)
' Parse out the Content Type
lstrContentType = ParseContentType(pbinChunk)
' If the content type is not defined, then assume the
' field is a normal form field
If lstrContentType = "" Then
' Parse Binary Data as Unicode
lstrValue = CStrU(ParseBinaryData(pbinChunk))
' Else assume the field is binary data
Else
' Parse Binary Data
lbinData = ParseBinaryData(pbinChunk)
End If
' Add a new field
Call AddField(lstrName, lstrFileName, lstrContentType, lstrValue, lbinData)
End Sub
' ------------------------------------------------------------------------------
Private Sub AddField(ByRef pstrName, ByRef pstrFileName, ByRef pstrContentType, ByRef pstrValue, ByRef pbinData)
Dim lobjField ' Field object class
' Add a new index to the field array
' Make certain not to destroy current fields
ReDim Preserve mobjFieldAry(mlngCount)
' Create new field object
Set lobjField = New clsField
' Set field properties
lobjField.Name = pstrName
lobjField.FilePath = pstrFileName
lobjField.ContentType = pstrContentType
' If field is not a binary file
If LenB(pbinData) = 0 Then
lobjField.BinaryData = ChrB(0)
lobjField.Value = pstrValue
lobjField.Length = Len(pstrValue)
' Else field is a binary file
Else
lobjField.BinaryData = pbinData
lobjField.Length = LenB(pbinData)
lobjField.Value = ""
End If
' Set field array index to new field
Set mobjFieldAry(mlngCount) = lobjField
' Incriment field count
mlngCount = mlngCount + 1
End Sub
' ------------------------------------------------------------------------------
Private Function ParseBinaryData(ByRef pbinChunk)
' Parses binary content of the chunk
Dim llngStart ' Start Position
' Find first occurence of a blank line
llngStart = InStrB(1, pbinChunk, CRLF & CRLF)
' If it doesn't exist, then return nothing
If llngStart = 0 Then Exit Function
' Incriment start to pass carriage returns and line feeds
llngStart = llngStart + 4
' Return the last part of the chunk after the start position
ParseBinaryData = MidB(pbinChunk, llngStart)
End Function
' ------------------------------------------------------------------------------
Private Function ParseContentType(ByRef pbinChunk)
' Parses the content type of a binary file.
' example: image/gif is the content type of a GIF image.
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Fid the first occurance of a line starting with Content-Type:
llngStart = InStrB(1, pbinChunk, CRLF & CStrB("Content-Type:"), vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the end of the line
llngEnd = InStrB(llngStart + 15, pbinChunk, CR)
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text "Content-Type:"
llngStart = llngStart + 15
' If the start position is the same or past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine length
llngLength = llngEnd - llngStart
' Pull out content type
' Convert to unicode
' Trim out whitespace
' Return results
ParseContentType = Trim(CStrU(MidB(pbinChunk, llngStart, llngLength)))
End Function
' ------------------------------------------------------------------------------
Private Function ParseDisposition(ByRef pbinChunk)
' Parses the content-disposition from a chunk of data
'
' Example:
'
' Content-Disposition: form-data: name="File1"; filename="C:\Photo.gif"
'
' Would Return:
' form-data: name="File1"; filename="C:\Photo.gif"
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Find first occurance of a line starting with Content-Disposition:
llngStart = InStrB(1, pbinChunk, CRLF & CStrB("Content-Disposition:"), vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the end of the line
llngEnd = InStrB(llngStart + 22, pbinChunk, CRLF)
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text "Content-Disposition:"
llngStart = llngStart + 22
' If the start position is the same or past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine Length
llngLength = llngEnd - llngStart
' Pull out content disposition
' Convert to Unicode
' Return Results
ParseDisposition = CStrU(MidB(pbinChunk, llngStart, llngLength))
End Function
' ------------------------------------------------------------------------------
Private Function ParseName(ByRef pstrDisposition)
' Parses the name of the field from the content disposition
'
' Example
'
' form-data: name="File1"; filename="C:\Photo.gif"
'
' Would Return:
' File1
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Find first occurance of text name="
llngStart = InStr(1, pstrDisposition, "name=""", vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the closing quote
llngEnd = InStr(llngStart + 6, pstrDisposition, """")
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text name="
llngStart = llngStart + 6
' If the start position is the same or past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine Length
llngLength = llngEnd - llngStart
' Pull out field name
' Return results
ParseName = Mid(pstrDisposition, llngStart, llngLength)
End Function
' ------------------------------------------------------------------------------
Private Function ParseFileName(ByRef pstrDisposition)
' Parses the name of the field from the content disposition
'
' Example
'
' form-data: name="File1"; filename="C:\Photo.gif"
'
' Would Return:
' C:\Photo.gif
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Find first occurance of text filename="
llngStart = InStr(1, pstrDisposition, "filename=""", vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the closing quote
llngEnd = InStr(llngStart + 10, pstrDisposition, """")
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text filename="
llngStart = llngStart + 10
' If the start position is the same of past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine length
llngLength = llngEnd - llngStart
' Pull out file name
' Return results
ParseFileName = Mid(pstrDisposition, llngStart, llngLength)
End Function
' ------------------------------------------------------------------------------
Public Property Get Count()
' Return number of fields found
Count = mlngCount
End Property
' ------------------------------------------------------------------------------
Public Default Property Get Fields(ByVal pstrName)
Dim llngIndex ' Index of current field
' If a number was passed
If IsNumeric(pstrName) Then
llngIndex = CLng(pstrName)
' If programmer requested an invalid number
If llngIndex > mlngCount - 1 Or llngIndex < 0 Then
' Raise an error
Call Err.Raise(vbObjectError + 1, "clsUpload.asp", "Object does not exist within the ordinal reference.")
Exit Property
End If
' Return the field class for the index specified
Set Fields = mobjFieldAry(pstrName)
' Else a field name was passed
Else
' convert name to lowercase
pstrName = LCase(pstrname)
' Loop through each field
For llngIndex = 0 To mlngCount - 1
' If name matches current fields name in lowercase
If LCase(mobjFieldAry(llngIndex).Name) = pstrName Then
' Return Field Class
Set Fields = mobjFieldAry(llngIndex)
Exit Property
End If
Next
End If
' If matches were not found, return an empty field
Set Fields = New clsField
' ' ERROR ON NonExistant:
' ' If matches were not found, raise an error of a non-existent field
' Call Err.Raise(vbObjectError + 1, "clsUpload.asp", "Object does not exist within the ordinal reference.")
' Exit Property
End Property
' ------------------------------------------------------------------------------
Private Sub Class_Terminate()
' This event is called when you destroy the class.
'
' Example:
' Set objUpload = Nothing
'
' Example:
' Response.End
'
' Example:
' Page finnishes executing ...
Dim llngIndex ' Current Field Index
' Loop through fields
For llngIndex = 0 To mlngCount - 1
' Release field object
Set mobjFieldAry(llngIndex) = Nothing
Next
' Redimension array and remove all data within
ReDim mobjFieldAry(-1)
End Sub
' ------------------------------------------------------------------------------
Private Sub Class_Initialize()
' This event is called when you instantiate the class.
'
' Example:
' Set objUpload = New clsUpload
' Redimension array with nothing
ReDim mobjFieldAry(-1)
' Compile ANSI equivilants of carriage returns and line feeds
CR = ChrB(Asc(vbCr)) ' vbCr Carriage Return
LF = ChrB(Asc(vbLf)) ' vbLf Line Feed
CRLF = CR & LF ' vbCrLf Carriage Return & Line Feed
' Set field count to zero
mlngCount = 0
' Request data
Call RequestData
' Parse out the delimiter
Call ParseDelimiter()
' Parse the data
Call ParseData
End Sub
' ------------------------------------------------------------------------------
Private Function CStrU(ByRef pstrANSI)
' Converts an ANSI string to Unicode
' Best used for small strings
Dim llngLength ' Length of ANSI string
Dim llngIndex ' Current position
' determine length
llngLength = LenB(pstrANSI)
' Loop through each character
For llngIndex = 1 To llngLength
' Pull out ANSI character
' Get Ascii value of ANSI character
' Get Unicode Character from Ascii
' Append character to results
CStrU = CStrU & Chr(AscB(MidB(pstrANSI, llngIndex, 1)))
Next
End Function
' ------------------------------------------------------------------------------
Private Function CStrB(ByRef pstrUnicode)
' Converts a Unicode string to ANSI
' Best used for small strings
Dim llngLength ' Length of ANSI string
Dim llngIndex ' Current position
' determine length
llngLength = Len(pstrUnicode)
' Loop through each character
For llngIndex = 1 To llngLength
' Pull out Unicode character
' Get Ascii value of Unicode character
' Get ANSI Character from Ascii
' Append character to results
CStrB = CStrB & ChrB(Asc(Mid(pstrUnicode, llngIndex, 1)))
Next
End Function
' ------------------------------------------------------------------------------
End Class
' ------------------------------------------------------------------------------
%>
2) Contents of clsField.asp
<%
' ------------------------------------------------------------------------------
' Author: Lewis Moten
' Date: March 19, 2002
' ------------------------------------------------------------------------------
' Field class represents interface to data passed within one field
'
' ------------------------------------------------------------------------------
Class clsField
Public Name ' Name of the field defined in form
Private mstrPath ' Full path to file on visitors computer
' C:\Documents and Settings\lmoten\Desktop\Photo.gif
Public FileDir ' Directory that file existed in on visitors computer
' C:\Documents and Settings\lmoten\Desktop
Public FileExt ' Extension of the file
' GIF
Public FileName ' Name of the file
' Photo.gif
Public ContentType ' Content / Mime type of file
' image/gif
Public Value ' Unicode value of field (used for normail form fields - not files)
Public BinaryData ' Binary data passed with field (for files)
Public Length ' byte size of value or binary data
Private mstrText ' Text buffer
' If text format of binary data is requested more then
' once, this value will be read to prevent extra processing
' ------------------------------------------------------------------------------
Public Property Get BLOB()
BLOB = BinaryData
End Property
' ------------------------------------------------------------------------------
Public Function BinaryAsText()
' Binary As Text returns the unicode equivilant of the binary data.
' this is useful if you expect a visitor to upload a text file that
' you will need to work with.
' NOTICE:
' NULL values will prematurely terminate your Unicode string.
' NULLs are usually found within binary files more often then plain-text files.
' a simple way around this may consist of replacing null values with another character
' such as a space " "
Dim lbinBytes
Dim lobjRs
' Don't convert binary data that does not exist
If Length = 0 Then Exit Function
If LenB(BinaryData) = 0 Then Exit Function
' If we previously converted binary to text, return the buffered content
If Not Len(mstrText) = 0 Then
BinaryAsText = mstrText
Exit Function
End If
' Convert Integer Subtype Array to Byte Subtype Array
lbinBytes = ASCII2Bytes(BinaryData)
' Convert Byte Subtype Array to Unicode String
mstrText = Bytes2Unicode(lbinBytes)
' Return Unicode Text
BinaryAsText = mstrText
End Function
' ------------------------------------------------------------------------------
Public Sub SaveAs(ByRef pstrFileName)
Dim lobjStream
Dim lobjRs
Dim lbinBytes
' Don't save files that do not posess binary data
If Length = 0 Then Exit Sub
If LenB(BinaryData) = 0 Then Exit Sub
' Create magical objects from never never land
Set lobjStream = Server.CreateObject("ADODB.Stream")
' Let stream know we are working with binary data
lobjStream.Type = adTypeBinary
' Open stream
Call lobjStream.Open()
' Convert Integer Subtype Array to Byte Subtype Array
lbinBytes = ASCII2Bytes(BinaryData)
' Write binary data to stream
Call lobjStream.Write(lbinBytes)
' Save the binary data to file system
' Overwrites file if previously exists!
Call lobjStream.SaveToFile(pstrFileName, adSaveCreateOverWrite)
' Close the stream object
Call lobjStream.Close()
' Release objects
Set lobjStream = Nothing
End Sub
' ------------------------------------------------------------------------------
Public Property Let FilePath(ByRef pstrPath)
mstrPath = pstrPath
' Parse File Ext
If Not InStrRev(pstrPath, ".") = 0 Then
FileExt = Mid(pstrPath, InStrRev(pstrPath, ".") + 1)
FileExt = UCase(FileExt)
End If
' Parse File Name
If Not InStrRev(pstrPath, "\") = 0 Then
FileName = Mid(pstrPath, InStrRev(pstrPath, "\") + 1)
End If
' Parse File Dir
If Not InStrRev(pstrPath, "\") = 0 Then
FileDir = Mid(pstrPath, 1, InStrRev(pstrPath, "\") - 1)
End If
End Property
' ------------------------------------------------------------------------------
Public Property Get FilePath()
FilePath = mstrPath
End Property
' ------------------------------------------------------------------------------
Private Function ASCII2Bytes(ByRef pbinBinaryData)
Dim lobjRs
Dim llngLength
Dim lbinBuffer
' get number of bytes
llngLength = LenB(pbinBinaryData)
Set lobjRs = Server.CreateObject("ADODB.Recordset")
' create field in an empty recordset to hold binary data
Call lobjRs.Fields.Append("BinaryData", adLongVarBinary, llngLength)
' Open recordset
Call lobjRs.Open()
' Add a new record to recordset
Call lobjRs.AddNew()
' Populate field with binary data
Call lobjRs.Fields("BinaryData").AppendChunk(pbinBinaryData & ChrB(0))
' Update / Convert Binary Data
' Although the data we have is binary - it has still been
' formatted as 4 bytes to represent each byte. When we
' update the recordset, the Integer Subtype Array that we
' passed into the Recordset will be converted into a
' Byte Subtype Array
Call lobjRs.Update()
' Request binary data and save to stream
lbinBuffer = lobjRs.Fields("BinaryData").GetChunk(llngLength)
' Close recordset
Call lobjRs.Close()
' Release recordset from memory
Set lobjRs = Nothing
' Return Bytes
ASCII2Bytes = lbinBuffer
End Function
' ------------------------------------------------------------------------------
Private Function Bytes2Unicode(ByRef pbinBytes)
Dim lobjRs
Dim llngLength
Dim lstrBuffer
llngLength = LenB(pbinBytes)
Set lobjRs = Server.CreateObject("ADODB.Recordset")
' Create field in an empty recordset to hold binary data
Call lobjRs.Fields.Append("BinaryData", adLongVarChar, llngLength)
' Open Recordset
Call lobjRs.Open()
' Add a new record to recordset
Call lobjRs.AddNew()
' Populate field with binary data
Call lobjRs.Fields("BinaryData").AppendChunk(pbinBytes)
' Update / Convert.
' Ensure bytes are proper subtype
Call lobjRs.Update()
' Request unicode value of binary data
lstrBuffer = lobjRs.Fields("BinaryData").Value
' Close recordset
Call lobjRs.Close()
' Release recordset from memory
Set lobjRs = Nothing
' Return Unicode
Bytes2Unicode = lstrBuffer
End Function
' ------------------------------------------------------------------------------
End Class
' ------------------------------------------------------------------------------
%>

Property FileName never set, I add this missing line in clsUpload.asp (between lines 157 and 158) in Private Sub AddField(...)
lobjField.Name = pstrName
lobjField.FilePath = pstrFileName
lobjField.FileName = Mid(pstrFileName, InStrRev(pstrFileName, "\") + 1) ' <= line added to set the file name
lobjField.ContentType = pstrContentType
You also have to declare the constant below:
Const adSaveCreateOverWrite = 2

Unfortunately, it won't be possible to setup an upload service without at least a little effort on using third party scripts AND making some adjustments to your server.
You may check however with your hosting provider a list of components already installed; most hosting services also maintain libraries/faq's/wiki's with almost ready examples of how to use those components. If there is none, there is still FreeAspUpload which is a DLL-free component so may be used on any Classic ASP server.
After determining which component/script you will use, you must also check for write permissions on the target upload folders. If you can't set the target folder with permission to write files, your uploads won't work. Check if the control panel of your hosting provider allow you to do that, or if you need to make a request for those changes.

Related

How to fully execute batch command before updating Access form control source in VBA [duplicate]

I have an executable that I call using the shell command:
Shell (ThisWorkbook.Path & "\ProcessData.exe")
The executable does some computations, then exports results back to Excel. I want to be able to change the format of the results AFTER they are exported.
In other words, i need the Shell command first to WAIT until the executable finishes its task, exports the data, and THEN do the next commands to format.
I tried the Shellandwait(), but without much luck.
I had:
Sub Test()
ShellandWait (ThisWorkbook.Path & "\ProcessData.exe")
'Additional lines to format cells as needed
End Sub
Unfortunately, still, formatting takes place first before the executable finishes.
Just for reference, here was my full code using ShellandWait
' Start the indicated program and wait for it
' to finish, hiding while we wait.
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32.dll" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
Private Const INFINITE = &HFFFF
Private Sub ShellAndWait(ByVal program_name As String)
Dim process_id As Long
Dim process_handle As Long
' Start the program.
On Error GoTo ShellError
process_id = Shell(program_name)
On Error GoTo 0
' Wait for the program to finish.
' Get the process handle.
process_handle = OpenProcess(SYNCHRONIZE, 0, process_id)
If process_handle <> 0 Then
WaitForSingleObject process_handle, INFINITE
CloseHandle process_handle
End If
Exit Sub
ShellError:
MsgBox "Error starting task " & _
txtProgram.Text & vbCrLf & _
Err.Description, vbOKOnly Or vbExclamation, _
"Error"
End Sub
Sub ProcessData()
ShellAndWait (ThisWorkbook.Path & "\Datacleanup.exe")
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
End Sub
Try the WshShell object instead of the native Shell function.
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Long
errorCode = wsh.Run("notepad.exe", windowStyle, waitOnReturn)
If errorCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
Though note that:
If bWaitOnReturn is set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).
So to detect whether the program executed successfully, you need waitOnReturn to be set to True as in my example above. Otherwise it will just return zero no matter what.
For early binding (gives access to Autocompletion), set a reference to "Windows Script Host Object Model" (Tools > Reference > set checkmark) and declare like this:
Dim wsh As WshShell
Set wsh = New WshShell
Now to run your process instead of Notepad... I expect your system will balk at paths containing space characters (...\My Documents\..., ...\Program Files\..., etc.), so you should enclose the path in "quotes":
Dim pth as String
pth = """" & ThisWorkbook.Path & "\ProcessData.exe" & """"
errorCode = wsh.Run(pth , windowStyle, waitOnReturn)
What you have will work once you add
Private Const SYNCHRONIZE = &H100000
which your missing. (Meaning 0 is being passed as the access right to OpenProcess which is not valid)
Making Option Explicit the top line of all your modules would have raised an error in this case
Shell-and-Wait in VBA (Compact Edition)
Sub ShellAndWait(pathFile As String)
With CreateObject("WScript.Shell")
.Run pathFile, 1, True
End With
End Sub
Example Usage:
Sub demo_Wait()
ShellAndWait ("notepad.exe")
Beep 'this won't run until Notepad window is closed
MsgBox "Done!"
End Sub
Adapted from (and more options at) Chip Pearson's site.
The WScript.Shell object's .Run() method as demonstrated in Jean-François Corbett's helpful answer is the right choice if you know that the command you invoke will finish in the expected time frame.
Below is SyncShell(), an alternative that allows you to specify a timeout, inspired by the great ShellAndWait() implementation. (The latter is a bit heavy-handed and sometimes a leaner alternative is preferable.)
' Windows API function declarations.
Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32.dll" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32.dll" (ByVal hProcess As Long, ByRef lpExitCodeOut As Long) As Integer
' Synchronously executes the specified command and returns its exit code.
' Waits indefinitely for the command to finish, unless you pass a
' timeout value in seconds for `timeoutInSecs`.
Private Function SyncShell(ByVal cmd As String, _
Optional ByVal windowStyle As VbAppWinStyle = vbMinimizedFocus, _
Optional ByVal timeoutInSecs As Double = -1) As Long
Dim pid As Long ' PID (process ID) as returned by Shell().
Dim h As Long ' Process handle
Dim sts As Long ' WinAPI return value
Dim timeoutMs As Long ' WINAPI timeout value
Dim exitCode As Long
' Invoke the command (invariably asynchronously) and store the PID returned.
' Note that this invocation may raise an error.
pid = Shell(cmd, windowStyle)
' Translate the PIP into a process *handle* with the
' SYNCHRONIZE and PROCESS_QUERY_LIMITED_INFORMATION access rights,
' so we can wait for the process to terminate and query its exit code.
' &H100000 == SYNCHRONIZE, &H1000 == PROCESS_QUERY_LIMITED_INFORMATION
h = OpenProcess(&H100000 Or &H1000, 0, pid)
If h = 0 Then
Err.Raise vbObjectError + 1024, , _
"Failed to obtain process handle for process with ID " & pid & "."
End If
' Now wait for the process to terminate.
If timeoutInSecs = -1 Then
timeoutMs = &HFFFF ' INFINITE
Else
timeoutMs = timeoutInSecs * 1000
End If
sts = WaitForSingleObject(h, timeoutMs)
If sts <> 0 Then
Err.Raise vbObjectError + 1025, , _
"Waiting for process with ID " & pid & _
" to terminate timed out, or an unexpected error occurred."
End If
' Obtain the process's exit code.
sts = GetExitCodeProcess(h, exitCode) ' Return value is a BOOL: 1 for true, 0 for false
If sts <> 1 Then
Err.Raise vbObjectError + 1026, , _
"Failed to obtain exit code for process ID " & pid & "."
End If
CloseHandle h
' Return the exit code.
SyncShell = exitCode
End Function
' Example
Sub Main()
Dim cmd As String
Dim exitCode As Long
cmd = "Notepad"
' Synchronously invoke the command and wait
' at most 5 seconds for it to terminate.
exitCode = SyncShell(cmd, vbNormalFocus, 5)
MsgBox "'" & cmd & "' finished with exit code " & exitCode & ".", vbInformation
End Sub
Simpler and Compressed Code with examples:
first declare your path
Dim path: path = ThisWorkbook.Path & "\ProcessData.exe"
And then use any one line of following code you like
1) Shown + waited + exited
VBA.CreateObject("WScript.Shell").Run path,1, True
2) Hidden + waited + exited
VBA.CreateObject("WScript.Shell").Run path,0, True
3) Shown + No waited
VBA.CreateObject("WScript.Shell").Run path,1, False
4) Hidden + No waited
VBA.CreateObject("WScript.Shell").Run path,0, False
I was looking for a simple solution too and finally ended up to make these two functions, so maybe for future enthusiast readers :)
1.) prog must be running, reads tasklist from dos, output status to
file, read file in vba
2.) start prog and wait till prog is closed with a wscript shell .exec waitonrun
3.) ask for confirmation to delete tmp file
Modify program name and path variables and run in one go.
Sub dosWOR_caller()
Dim pwatch As String, ppath As String, pfull As String
pwatch = "vlc.exe" 'process to watch, or process.exe (do NOT use on cmd.exe itself...)
ppath = "C:\Program Files\VideoLAN\VLC" 'path to the program, or ThisWorkbook.Path
pfull = ppath & "\" & pwatch 'extra quotes in cmd line
Dim fout As String 'tmp file for r/w status in 1)
fout = Environ("userprofile") & "\Desktop\dosWaitOnRun_log.txt"
Dim status As Boolean, t As Double
status = False
'1) wait until done
t = Timer
If Not status Then Debug.Print "run prog first for this one! then close it to stop dosWORrun ": Shell (pfull)
status = dosWORrun(pwatch, fout)
If status Then Debug.Print "elapsed time: "; Format(Timer - t, "#.00s")
'2) wait while running
t = Timer
Debug.Print "now running the prog and waiting you close it..."
status = dosWORexec(pfull)
If status = True Then Debug.Print "elapsed time: "; Format(Timer - t, "#.00s")
'3) or if you need user action
With CreateObject("wScript.Shell")
.Run "cmd.exe /c title=.:The end:. & set /p""=Just press [enter] to delete tmp file"" & del " & fout & " & set/p""=and again to quit ;)""", 1, True
End With
End Sub
Function dosWORrun(pwatch As String, fout As String) As Boolean
'redirect sdtout to file, then read status and loop
Dim i As Long, scatch() As String
dosWORrun = False
If pwatch = "cmd.exe" Then Exit Function
With CreateObject("wScript.Shell")
Do
i = i + 1
.Run "cmd /c >""" & fout & """ (tasklist |find """ & pwatch & """ >nul && echo.""still running""|| echo.""done"")", 0, True
scatch = fReadb(fout)
Debug.Print i; scatch(0)
Loop Until scatch(0) = """done"""
End With
dosWORrun = True
End Function
Function dosWORexec(pwatch As String) As Boolean
'the trick: with .exec method, use .stdout.readall of the WshlExec object to force vba to wait too!
Dim scatch() As String, y As Object
dosWORexec = False
With CreateObject("wScript.Shell")
Set y = .exec("cmd.exe /k """ & pwatch & """ & exit")
scatch = Split(y.stdout.readall, vbNewLine)
Debug.Print y.status
Set y = Nothing
End With
dosWORexec = True
End Function
Function fReadb(txtfile As String) As String()
'fast read
Dim ff As Long, data As String
'~~. Open as txt File and read it in one go into memory
ff = FreeFile
Open txtfile For Binary As #ff
data = Space$(LOF(1))
Get #ff, , data
Close #ff
'~~> Store content in array
fReadb = Split(data, vbCrLf)
'~~ skip last crlf
If UBound(fReadb) <> -1 Then ReDim Preserve fReadb(0 To UBound(fReadb) - 1)
End Function
I incorporated this into a routine, and it has worked fine (but not used very often) for several years - for which, many thanks !
But now I find it throws up an error :-
Run-time error '-2147024894 (80070002)':
Method 'Run' of object 'IWshSheB' failed
on the line -
ErrorCode = wsh.Run(myCommand, windowStyle, WaitOnReturn)
Very strange !
5 hours later !
I THINK the reason it fails is that dear MicroSoft ("dear" meaning expensive) has changed something radical - "Shell" USED to be "Shell to DOS", but has that been changed >=?
The "Command" that I want the Shell to run is simply DIR
In full, it is "DIR C:\Folder\ /S >myFIle.txt"
. . . . . . . . . . . . . . . . . . . . . .
An hour after that-
Yup !
I have "solved" it by using this Code, which works just fine :-
Sub ShellAndWait(PathFile As String, _
Optional Wait As Boolean = True, _
Optional Hidden As Boolean = True)
' Hidden = 0; Shown = 1
Dim Hash As Integer, myBat As String, Shown As Integer
Shown = 0
If Hidden Then Shown = 1
If Hidden <> 0 Then Hidden = 1
Hash = FreeFile
myBat = "C:\Users\Public\myBat.bat"
Open myBat For Output As #Hash
Print #Hash, PathFile
Close #Hash
With CreateObject("WScript.Shell")
.Run myBat, Shown, Wait
End With
End Sub
I would come at this by using the Timer function. Figure out roughly how long you'd like the macro to pause while the .exe does its thing, and then change the '10' in the commented line to whatever time (in seconds) that you'd like.
Strt = Timer
Shell (ThisWorkbook.Path & "\ProcessData.exe")
Do While Timer < Strt + 10 'This line loops the code for 10 seconds
Loop
UserForm2.Hide
'Additional lines to set formatting
This should do the trick, let me know if not.
Cheers, Ben.

Read large file line-by-line with ADO Stream?

I want to use ADO Stream to read lines from a local large text file with UTF-8 encoding so I try
Set objStream = CreateObject("ADODB.Stream")
objStream.Charset = "utf-8"
objStream.Type = 2
objStream.Open
objStream.LoadFromFile = strFile
objStream.LineSeparator = 10
Do Until objStream.EOS
strLine = objStream.ReadText(-2)
Loop
However the result is that the script takes lots of RAM and CPU usages. So is there any way to tell the script not to load all the file contents into memory, but just open it and read until it encounters any line separator?
As you work with Stream object, I think it's obvious, however, .LoadFromFile fill current stream with the whole file content, and no any cutomize option to load parial data from file.
As for reading 1 line, you done this already with .ReadText(-2), (-2 = adReadLine).
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Charset = "utf-8"
.Type = 2
.Open
'objStream.LoadFromFile = strFile ''I see a typo here
.LoadFromFile strFile
.LineSeparator = 10 ''that's Ok
'Do Until objStream.EOS ''no need this
strLine = .ReadText(-2)
'Loop
.Close ''add this though!
End with
Set objStream = Nothing
For .LineSeparator you can use just 3 constants:
Constant Value Description
adCRLF -1 Default. Carriage return line feed
adLF 10 Line feed only
adCR 13 Carriage return only
If you need to break your Do..Loop at other letter, as .ReadText is the only choice for reading text stream, you may use it in conjunction with InStr function and Exit Do then you find your custom separator.
Const cSeparator = "_" 'your custom separator
Dim strLine, strTotal, index
Do Until objStream.EOS
strLine = objStream.ReadText(-2)
index = InStr(1, strLine, cSeparator)
If index <> 0 Then
strTotal = strTotal & Left(strLine, index-1)
Exit Do
Else
strTotal = strTotal & strLine
End If
Loop
Shortly, this is the whole optimization you can do (or at least as far as I know).
If you look at this snippet from J. T. Roff's ADO book, you'll see that in theory you can read from a file line by line (without loading it completely into memory). I tried using the file: protocoll in the source parameter, but did not succeed.
So let's try another approach: To treat the .txt file as a UTF8 encoded trivial (one column) ADO database table, you need a schema.ini file in the source directory:
[linesutf8.txt]
ColNameHeader=False
CharacterSet=65001
Format=TabDelimited
Col1=SampleText CHAR WIDTH 100
Then you can do:
Dim sTDir : sTDir = "M:/lib/kurs0705/testdata"
Dim sFName : sFName = "[linesutf8.txt]"
Dim oDb : Set oDb = CreateObject("ADODB.Connection")
Dim sCs : sCs = Join(Array( _
"Provider=MSDASQL" _
, "Driver={Microsoft Text Driver (*.txt; *.csv)}" _
, "DBQ=" + sTDir _
), ";")
oDb.open sCs
WScript.Stdin.Readline
Dim oRs : Set oRs = oDb.Execute("SELECT * FROM " & sFName)
WScript.Stdin.Readline
Do Until oRS.EOF
WScript.Echo oRS.Fields(0).Value
oRs.MoveNext
Loop
oRs.Close
oDb.Close
For some background look here.

How to upload files with asp-classic

I want to create a page with asp-classic where users can upload files or zipped folders.
I've searched in Google but every solution I have found uses a third-party file.
But I haven't been able to get those files to work.
long time since I've done that but we used an upload without third party components, just two vbscript classes (solution credit goes to Lewis Moten).
It looks like you can still find this "Lewis Moten solution" in the wild
If you include the clsUpload file, further upload process is as simple as:
Dim objUpload
Dim strFile, strPath
' Instantiate Upload Class '
Set objUpload = New clsUpload
strFile = objUpload.Fields("file").FileName
strPath = server.mappath("/data") & "/" & strFile
' Save the binary data to the file system '
objUpload("file").SaveAs strPath
Set objUpload = Nothing
That's all for the server-side...
On the client-side you just need your File input
<form name="Upload" enctype="multipart/form-data" method="post" action="clsUpload.asp">
<div>Upload file: </div>
<div><INPUT TYPE="file" NAME="file" >
<input type="button" name="FileUpload" value="Upload File"> </div>
</form>
Hope this helps..
Edit 23 June 2014
As pointed out by Dave Wut my reference to the solution "in the wild" was not completely consistent with the code snippet provided. Hereby the full classes that I had used historically (comments trimmed to stay below the 30000 SO limit). It was an early version of the Lewis Moten solution found at http://planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=8525&lngWId=4
1) Contents of clsUpload.asp
<!--METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.5 Library"
UUID="{00000205-0000-0010-8000-00AA006D2EA4}"
VERSION="2.5"
-->
<!--#INCLUDE FILE="clsField.asp"-->
<%
' ------------------------------------------------------------------------------
' Author: Lewis Moten
' Date: March 19, 2002
' ------------------------------------------------------------------------------
' Upload class retrieves multi-part form data posted to web page
' and parses it into objects that are easy to interface with.
' Requires MDAC (ADODB) COM components found on most servers today
' Additional compenents are not necessary.
'
Class clsUpload
' ------------------------------------------------------------------------------
Private mbinData ' bytes visitor sent to server
Private mlngChunkIndex ' byte where next chunk starts
Private mlngBytesReceived ' length of data
Private mstrDelimiter ' Delimiter between multipart/form-data (43 chars)
Private CR ' ANSI Carriage Return
Private LF ' ANSI Line Feed
Private CRLF ' ANSI Carriage Return & Line Feed
Private mobjFieldAry() ' Array to hold field objects
Private mlngCount ' Number of fields parsed
' ------------------------------------------------------------------------------
Private Sub RequestData
Dim llngLength ' Number of bytes received
' Determine number bytes visitor sent
mlngBytesReceived = Request.TotalBytes
' Store bytes recieved from visitor
mbinData = Request.BinaryRead(mlngBytesReceived)
End Sub
' ------------------------------------------------------------------------------
Private Sub ParseDelimiter()
' Delimiter seperates multiple pieces of form data
' "around" 43 characters in length
' next character afterwards is carriage return (except last line has two --)
' first part of delmiter is dashes followed by hex number
' hex number is possibly the browsers session id?
' Examples:
' -----------------------------7d230d1f940246
' -----------------------------7d22ee291ae0114
mstrDelimiter = MidB(mbinData, 1, InStrB(1, mbinData, CRLF) - 1)
End Sub
' ------------------------------------------------------------------------------
Private Sub ParseData()
' This procedure loops through each section (chunk) found within the
' delimiters and sends them to the parse chunk routine
Dim llngStart ' start position of chunk data
Dim llngLength ' Length of chunk
Dim llngEnd ' Last position of chunk data
Dim lbinChunk ' Binary contents of chunk
' Initialize at first character
llngStart = 1
' Find start position
llngStart = InStrB(llngStart, mbinData, mstrDelimiter & CRLF)
' While the start posotion was found
While Not llngStart = 0
' Find the end position (after the start position)
llngEnd = InStrB(llngStart + 1, mbinData, mstrDelimiter) - 2
' Determine Length of chunk
llngLength = llngEnd - llngStart
' Pull out the chunk
lbinChunk = MidB(mbinData, llngStart, llngLength)
' Parse the chunk
Call ParseChunk(lbinChunk)
' Look for next chunk after the start position
llngStart = InStrB(llngStart + 1, mbinData, mstrDelimiter & CRLF)
Wend
End Sub
' ------------------------------------------------------------------------------
Private Sub ParseChunk(ByRef pbinChunk)
' This procedure gets a chunk passed to it and parses its contents.
' There is a general format that the chunk follows.
' First, the deliminator appears
' Next, headers are listed on each line that define properties of the chunk.
' Content-Disposition: form-data: name="File1"; filename="C:\Photo.gif"
' Content-Type: image/gif
' After this, a blank line appears and is followed by the binary data.
Dim lstrName ' Name of field
Dim lstrFileName ' File name of binary data
Dim lstrContentType ' Content type of binary data
Dim lbinData ' Binary data
Dim lstrDisposition ' Content Disposition
Dim lstrValue ' Value of field
' Parse out the content dispostion
lstrDisposition = ParseDisposition(pbinChunk)
' And Parse the Name
lstrName = ParseName(lstrDisposition)
' And the file name
lstrFileName = ParseFileName(lstrDisposition)
' Parse out the Content Type
lstrContentType = ParseContentType(pbinChunk)
' If the content type is not defined, then assume the
' field is a normal form field
If lstrContentType = "" Then
' Parse Binary Data as Unicode
lstrValue = CStrU(ParseBinaryData(pbinChunk))
' Else assume the field is binary data
Else
' Parse Binary Data
lbinData = ParseBinaryData(pbinChunk)
End If
' Add a new field
Call AddField(lstrName, lstrFileName, lstrContentType, lstrValue, lbinData)
End Sub
' ------------------------------------------------------------------------------
Private Sub AddField(ByRef pstrName, ByRef pstrFileName, ByRef pstrContentType, ByRef pstrValue, ByRef pbinData)
Dim lobjField ' Field object class
' Add a new index to the field array
' Make certain not to destroy current fields
ReDim Preserve mobjFieldAry(mlngCount)
' Create new field object
Set lobjField = New clsField
' Set field properties
lobjField.Name = pstrName
lobjField.FilePath = pstrFileName
lobjField.ContentType = pstrContentType
' If field is not a binary file
If LenB(pbinData) = 0 Then
lobjField.BinaryData = ChrB(0)
lobjField.Value = pstrValue
lobjField.Length = Len(pstrValue)
' Else field is a binary file
Else
lobjField.BinaryData = pbinData
lobjField.Length = LenB(pbinData)
lobjField.Value = ""
End If
' Set field array index to new field
Set mobjFieldAry(mlngCount) = lobjField
' Incriment field count
mlngCount = mlngCount + 1
End Sub
' ------------------------------------------------------------------------------
Private Function ParseBinaryData(ByRef pbinChunk)
' Parses binary content of the chunk
Dim llngStart ' Start Position
' Find first occurence of a blank line
llngStart = InStrB(1, pbinChunk, CRLF & CRLF)
' If it doesn't exist, then return nothing
If llngStart = 0 Then Exit Function
' Incriment start to pass carriage returns and line feeds
llngStart = llngStart + 4
' Return the last part of the chunk after the start position
ParseBinaryData = MidB(pbinChunk, llngStart)
End Function
' ------------------------------------------------------------------------------
Private Function ParseContentType(ByRef pbinChunk)
' Parses the content type of a binary file.
' example: image/gif is the content type of a GIF image.
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Fid the first occurance of a line starting with Content-Type:
llngStart = InStrB(1, pbinChunk, CRLF & CStrB("Content-Type:"), vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the end of the line
llngEnd = InStrB(llngStart + 15, pbinChunk, CR)
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text "Content-Type:"
llngStart = llngStart + 15
' If the start position is the same or past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine length
llngLength = llngEnd - llngStart
' Pull out content type
' Convert to unicode
' Trim out whitespace
' Return results
ParseContentType = Trim(CStrU(MidB(pbinChunk, llngStart, llngLength)))
End Function
' ------------------------------------------------------------------------------
Private Function ParseDisposition(ByRef pbinChunk)
' Parses the content-disposition from a chunk of data
'
' Example:
'
' Content-Disposition: form-data: name="File1"; filename="C:\Photo.gif"
'
' Would Return:
' form-data: name="File1"; filename="C:\Photo.gif"
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Find first occurance of a line starting with Content-Disposition:
llngStart = InStrB(1, pbinChunk, CRLF & CStrB("Content-Disposition:"), vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the end of the line
llngEnd = InStrB(llngStart + 22, pbinChunk, CRLF)
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text "Content-Disposition:"
llngStart = llngStart + 22
' If the start position is the same or past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine Length
llngLength = llngEnd - llngStart
' Pull out content disposition
' Convert to Unicode
' Return Results
ParseDisposition = CStrU(MidB(pbinChunk, llngStart, llngLength))
End Function
' ------------------------------------------------------------------------------
Private Function ParseName(ByRef pstrDisposition)
' Parses the name of the field from the content disposition
'
' Example
'
' form-data: name="File1"; filename="C:\Photo.gif"
'
' Would Return:
' File1
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Find first occurance of text name="
llngStart = InStr(1, pstrDisposition, "name=""", vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the closing quote
llngEnd = InStr(llngStart + 6, pstrDisposition, """")
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text name="
llngStart = llngStart + 6
' If the start position is the same or past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine Length
llngLength = llngEnd - llngStart
' Pull out field name
' Return results
ParseName = Mid(pstrDisposition, llngStart, llngLength)
End Function
' ------------------------------------------------------------------------------
Private Function ParseFileName(ByRef pstrDisposition)
' Parses the name of the field from the content disposition
'
' Example
'
' form-data: name="File1"; filename="C:\Photo.gif"
'
' Would Return:
' C:\Photo.gif
Dim llngStart ' Start Position
Dim llngEnd ' End Position
Dim llngLength ' Length
' Find first occurance of text filename="
llngStart = InStr(1, pstrDisposition, "filename=""", vbTextCompare)
' If not found, return nothing
If llngStart = 0 Then Exit Function
' Find the closing quote
llngEnd = InStr(llngStart + 10, pstrDisposition, """")
' If not found, return nothing
If llngEnd = 0 Then Exit Function
' Adjust start position to start after the text filename="
llngStart = llngStart + 10
' If the start position is the same of past the end, return nothing
If llngStart >= llngEnd Then Exit Function
' Determine length
llngLength = llngEnd - llngStart
' Pull out file name
' Return results
ParseFileName = Mid(pstrDisposition, llngStart, llngLength)
End Function
' ------------------------------------------------------------------------------
Public Property Get Count()
' Return number of fields found
Count = mlngCount
End Property
' ------------------------------------------------------------------------------
Public Default Property Get Fields(ByVal pstrName)
Dim llngIndex ' Index of current field
' If a number was passed
If IsNumeric(pstrName) Then
llngIndex = CLng(pstrName)
' If programmer requested an invalid number
If llngIndex > mlngCount - 1 Or llngIndex < 0 Then
' Raise an error
Call Err.Raise(vbObjectError + 1, "clsUpload.asp", "Object does not exist within the ordinal reference.")
Exit Property
End If
' Return the field class for the index specified
Set Fields = mobjFieldAry(pstrName)
' Else a field name was passed
Else
' convert name to lowercase
pstrName = LCase(pstrname)
' Loop through each field
For llngIndex = 0 To mlngCount - 1
' If name matches current fields name in lowercase
If LCase(mobjFieldAry(llngIndex).Name) = pstrName Then
' Return Field Class
Set Fields = mobjFieldAry(llngIndex)
Exit Property
End If
Next
End If
' If matches were not found, return an empty field
Set Fields = New clsField
' ' ERROR ON NonExistant:
' ' If matches were not found, raise an error of a non-existent field
' Call Err.Raise(vbObjectError + 1, "clsUpload.asp", "Object does not exist within the ordinal reference.")
' Exit Property
End Property
' ------------------------------------------------------------------------------
Private Sub Class_Terminate()
' This event is called when you destroy the class.
'
' Example:
' Set objUpload = Nothing
'
' Example:
' Response.End
'
' Example:
' Page finnishes executing ...
Dim llngIndex ' Current Field Index
' Loop through fields
For llngIndex = 0 To mlngCount - 1
' Release field object
Set mobjFieldAry(llngIndex) = Nothing
Next
' Redimension array and remove all data within
ReDim mobjFieldAry(-1)
End Sub
' ------------------------------------------------------------------------------
Private Sub Class_Initialize()
' This event is called when you instantiate the class.
'
' Example:
' Set objUpload = New clsUpload
' Redimension array with nothing
ReDim mobjFieldAry(-1)
' Compile ANSI equivilants of carriage returns and line feeds
CR = ChrB(Asc(vbCr)) ' vbCr Carriage Return
LF = ChrB(Asc(vbLf)) ' vbLf Line Feed
CRLF = CR & LF ' vbCrLf Carriage Return & Line Feed
' Set field count to zero
mlngCount = 0
' Request data
Call RequestData
' Parse out the delimiter
Call ParseDelimiter()
' Parse the data
Call ParseData
End Sub
' ------------------------------------------------------------------------------
Private Function CStrU(ByRef pstrANSI)
' Converts an ANSI string to Unicode
' Best used for small strings
Dim llngLength ' Length of ANSI string
Dim llngIndex ' Current position
' determine length
llngLength = LenB(pstrANSI)
' Loop through each character
For llngIndex = 1 To llngLength
' Pull out ANSI character
' Get Ascii value of ANSI character
' Get Unicode Character from Ascii
' Append character to results
CStrU = CStrU & Chr(AscB(MidB(pstrANSI, llngIndex, 1)))
Next
End Function
' ------------------------------------------------------------------------------
Private Function CStrB(ByRef pstrUnicode)
' Converts a Unicode string to ANSI
' Best used for small strings
Dim llngLength ' Length of ANSI string
Dim llngIndex ' Current position
' determine length
llngLength = Len(pstrUnicode)
' Loop through each character
For llngIndex = 1 To llngLength
' Pull out Unicode character
' Get Ascii value of Unicode character
' Get ANSI Character from Ascii
' Append character to results
CStrB = CStrB & ChrB(Asc(Mid(pstrUnicode, llngIndex, 1)))
Next
End Function
' ------------------------------------------------------------------------------
End Class
' ------------------------------------------------------------------------------
%>
2) Contents of clsField.asp
<%
' ------------------------------------------------------------------------------
' Author: Lewis Moten
' Date: March 19, 2002
' ------------------------------------------------------------------------------
' Field class represents interface to data passed within one field
'
' ------------------------------------------------------------------------------
Class clsField
Public Name ' Name of the field defined in form
Private mstrPath ' Full path to file on visitors computer
' C:\Documents and Settings\lmoten\Desktop\Photo.gif
Public FileDir ' Directory that file existed in on visitors computer
' C:\Documents and Settings\lmoten\Desktop
Public FileExt ' Extension of the file
' GIF
Public FileName ' Name of the file
' Photo.gif
Public ContentType ' Content / Mime type of file
' image/gif
Public Value ' Unicode value of field (used for normail form fields - not files)
Public BinaryData ' Binary data passed with field (for files)
Public Length ' byte size of value or binary data
Private mstrText ' Text buffer
' If text format of binary data is requested more then
' once, this value will be read to prevent extra processing
' ------------------------------------------------------------------------------
Public Property Get BLOB()
BLOB = BinaryData
End Property
' ------------------------------------------------------------------------------
Public Function BinaryAsText()
' Binary As Text returns the unicode equivilant of the binary data.
' this is useful if you expect a visitor to upload a text file that
' you will need to work with.
' NOTICE:
' NULL values will prematurely terminate your Unicode string.
' NULLs are usually found within binary files more often then plain-text files.
' a simple way around this may consist of replacing null values with another character
' such as a space " "
Dim lbinBytes
Dim lobjRs
' Don't convert binary data that does not exist
If Length = 0 Then Exit Function
If LenB(BinaryData) = 0 Then Exit Function
' If we previously converted binary to text, return the buffered content
If Not Len(mstrText) = 0 Then
BinaryAsText = mstrText
Exit Function
End If
' Convert Integer Subtype Array to Byte Subtype Array
lbinBytes = ASCII2Bytes(BinaryData)
' Convert Byte Subtype Array to Unicode String
mstrText = Bytes2Unicode(lbinBytes)
' Return Unicode Text
BinaryAsText = mstrText
End Function
' ------------------------------------------------------------------------------
Public Sub SaveAs(ByRef pstrFileName)
Dim lobjStream
Dim lobjRs
Dim lbinBytes
' Don't save files that do not posess binary data
If Length = 0 Then Exit Sub
If LenB(BinaryData) = 0 Then Exit Sub
' Create magical objects from never never land
Set lobjStream = Server.CreateObject("ADODB.Stream")
' Let stream know we are working with binary data
lobjStream.Type = adTypeBinary
' Open stream
Call lobjStream.Open()
' Convert Integer Subtype Array to Byte Subtype Array
lbinBytes = ASCII2Bytes(BinaryData)
' Write binary data to stream
Call lobjStream.Write(lbinBytes)
' Save the binary data to file system
' Overwrites file if previously exists!
Call lobjStream.SaveToFile(pstrFileName, adSaveCreateOverWrite)
' Close the stream object
Call lobjStream.Close()
' Release objects
Set lobjStream = Nothing
End Sub
' ------------------------------------------------------------------------------
Public Property Let FilePath(ByRef pstrPath)
mstrPath = pstrPath
' Parse File Ext
If Not InStrRev(pstrPath, ".") = 0 Then
FileExt = Mid(pstrPath, InStrRev(pstrPath, ".") + 1)
FileExt = UCase(FileExt)
End If
' Parse File Name
If Not InStrRev(pstrPath, "\") = 0 Then
FileName = Mid(pstrPath, InStrRev(pstrPath, "\") + 1)
End If
' Parse File Dir
If Not InStrRev(pstrPath, "\") = 0 Then
FileDir = Mid(pstrPath, 1, InStrRev(pstrPath, "\") - 1)
End If
End Property
' ------------------------------------------------------------------------------
Public Property Get FilePath()
FilePath = mstrPath
End Property
' ------------------------------------------------------------------------------
Private Function ASCII2Bytes(ByRef pbinBinaryData)
Dim lobjRs
Dim llngLength
Dim lbinBuffer
' get number of bytes
llngLength = LenB(pbinBinaryData)
Set lobjRs = Server.CreateObject("ADODB.Recordset")
' create field in an empty recordset to hold binary data
Call lobjRs.Fields.Append("BinaryData", adLongVarBinary, llngLength)
' Open recordset
Call lobjRs.Open()
' Add a new record to recordset
Call lobjRs.AddNew()
' Populate field with binary data
Call lobjRs.Fields("BinaryData").AppendChunk(pbinBinaryData & ChrB(0))
' Update / Convert Binary Data
' Although the data we have is binary - it has still been
' formatted as 4 bytes to represent each byte. When we
' update the recordset, the Integer Subtype Array that we
' passed into the Recordset will be converted into a
' Byte Subtype Array
Call lobjRs.Update()
' Request binary data and save to stream
lbinBuffer = lobjRs.Fields("BinaryData").GetChunk(llngLength)
' Close recordset
Call lobjRs.Close()
' Release recordset from memory
Set lobjRs = Nothing
' Return Bytes
ASCII2Bytes = lbinBuffer
End Function
' ------------------------------------------------------------------------------
Private Function Bytes2Unicode(ByRef pbinBytes)
Dim lobjRs
Dim llngLength
Dim lstrBuffer
llngLength = LenB(pbinBytes)
Set lobjRs = Server.CreateObject("ADODB.Recordset")
' Create field in an empty recordset to hold binary data
Call lobjRs.Fields.Append("BinaryData", adLongVarChar, llngLength)
' Open Recordset
Call lobjRs.Open()
' Add a new record to recordset
Call lobjRs.AddNew()
' Populate field with binary data
Call lobjRs.Fields("BinaryData").AppendChunk(pbinBytes)
' Update / Convert.
' Ensure bytes are proper subtype
Call lobjRs.Update()
' Request unicode value of binary data
lstrBuffer = lobjRs.Fields("BinaryData").Value
' Close recordset
Call lobjRs.Close()
' Release recordset from memory
Set lobjRs = Nothing
' Return Unicode
Bytes2Unicode = lstrBuffer
End Function
' ------------------------------------------------------------------------------
End Class
' ------------------------------------------------------------------------------
%>
Property FileName never set, I add this missing line in clsUpload.asp (between lines 157 and 158) in Private Sub AddField(...)
lobjField.Name = pstrName
lobjField.FilePath = pstrFileName
lobjField.FileName = Mid(pstrFileName, InStrRev(pstrFileName, "\") + 1) ' <= line added to set the file name
lobjField.ContentType = pstrContentType
You also have to declare the constant below:
Const adSaveCreateOverWrite = 2
Unfortunately, it won't be possible to setup an upload service without at least a little effort on using third party scripts AND making some adjustments to your server.
You may check however with your hosting provider a list of components already installed; most hosting services also maintain libraries/faq's/wiki's with almost ready examples of how to use those components. If there is none, there is still FreeAspUpload which is a DLL-free component so may be used on any Classic ASP server.
After determining which component/script you will use, you must also check for write permissions on the target upload folders. If you can't set the target folder with permission to write files, your uploads won't work. Check if the control panel of your hosting provider allow you to do that, or if you need to make a request for those changes.

search engine in asp classic

I already try a search engine script like below:
<HTML><BODY>
<B>Search Results for <%=Request("SearchText")%></B><BR>
<%
Const fsoForReading = 1
Dim strSearchText
strSearchText = Request("SearchText")
''# Now, we want to search all of the files
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Dim objFolder
Set objFolder = objFSO.GetFolder(Server.MapPath("/"))
Dim objFile, objTextStream, strFileContents, bolFileFound
bolFileFound = False
For Each objFile in objFolder.Files
If Response.IsClientConnected then
Set objTextStream = objFSO.OpenTextFile(objFile.Path,fsoForReading)
strFileContents = objTextStream.ReadAll
If InStr(1,strFileContents,strSearchText,1) then
Response.Write "<LI><A HREF=""/" & objFile.Name & _
""">" & objFile.Name & "</A><BR>"
bolFileFound = True
End If
objTextStream.Close
End If
Next
if Not bolFileFound then Response.Write "No matches found..."
Set objTextStream = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
%>
</BODY></HTML>
the output will show only the name of file, what i want is the title of the file.
my question is, how to get the string between in order to show up for the result? or is there any other script related to search engine in asp classic?
I'm not sure I get what you mean, but if you intend on grabbing the file name without the path nor extension, here's a snippet I use:
Public Function GetFileName(flname As String) As String
'From: http://www.freevbcode.com/ShowCode.asp?ID=1638
'By: Maria Rapini
'Get the filename without the path or extension.
'Input Values:
' flname - path and filename of file.
'Return Value:
' GetFileName - name of file without the extension.
Dim posn As Integer, i As Integer
Dim fName As String
posn = 0
'find the position of the last "\" character in filename
For i = 1 To Len(flname)
If (Mid(flname, i, 1) = "\") Then posn = i
Next i
'get filename without path
fName = Right(flname, Len(flname) - posn)
'get filename without extension
posn = InStr(fName, ".")
If posn <> 0 Then
fName = Left(fName, posn - 1)
End If
GetFileName = fName
End Function

Lookup Fields in HP Quality Center

I am interfacing with Quality Centre via Open Test Architecture API.
I would like to determined the allowed values of bug Fields that are linked to a lookup table.
These are available via drop downs in the standard frontend.
Thanks
Edit: A more Detailed explanation
We have some fields which will only allow specific values to placed in them.
For example:
NextAction can be one of the following { "1. Specify", "2. Analysis", "3. Design" }
But I have been unable to find a way to determine these allowed values programmatically.
Using the BugFactory object you can access the fields and their attributes. This is a direct copy / paste of Visual Basic from the OTA API Reference help file. If you want more help, try providing a more focused question, such as what you're trying to accomplish, which fields, and which language you're trying to access with.
Public Sub CheckValidValue(Optional TableName As String = "BUG")
Dim BugFact As BugFactory
Dim BugList As list
Dim aField As TDField
Dim fieldList As list
Dim rc, ErrCode As Long
Dim aBug As Bug
Dim msg$
Dim okCnt%, noNodeCnt%, errorCnt%, unknownCnt%
Dim dataType As Long
'------------------------------------------------
' User BugFactory.Fields to get a list of TDField
' objects in the bug table.
' This example uses the BugFactory, but this can
' be done with any class that implements IBaseFactory
'tdc is the global TDConnection object.
Set BugFact = tdc.BugFactory
Set fieldList = BugFact.Fields
'------------------------------------------
' Use List.Count to check how many items.
Debug.Print: Debug.Print
Debug.Print "There are " & fieldList.Count & _
" fields in this table."
Debug.Print "----------------------------------"
'Get any bug. To look at field attributes we
' need a valid object and since this example is
' not interested in the particular values of the object,
' it doesn't matter which bug.
Set BugList = BugFact.NewList("")
Set aBug = BugList(0)
'Walk through the list
For Each aField In fieldList
With aField
'Quit when we have enough for this example
If InStr(aField.Name, "BG_USER_10") > 0 Then Exit For
' For the DataTypeString() code,
' see example "Convert data types to string"
Debug.Print .Name & ", " & .Property & ", Data type is " _
& DataTypeString(.Type)
On Error Resume Next
'----------------------------------------------------
'Use TDField.IsValidValue to confirm that a value can
'be used for a field.
' Get the correct data type and check validity of an
' arbitrary value.
' Save the error code immediately after IsValidValue call
' before another call can change the err object.
dataType = aField.Type
Select Case dataType
Case TDOLE_LONG, TDOLE_ULONG
aField.IsValidValue 5, aBug
ErrCode = err.Number
Case TDOLE_FLOAT
aField.IsValidValue 5.5, aBug
ErrCode = err.Number
Case TDOLE_STRING
aField.IsValidValue "Joe", aBug
ErrCode = err.Number
Case Else
'These will be errors:
aField.IsValidValue _
"String to non-string value", aBug
ErrCode = err.Number
End Select
'Output an error code message
If ErrCode = 0 Then 'S_OK
msg = "Valid Value"
okCnt = okCnt + 1
Else
rc = ErrCode - vbObjectError
Select Case rc
Case FIELD_E_VERIFIED
msg = "Error: Invalid value for field"
errorCnt = errorCnt + 1
Case TDOLE_NONODE
msg = "Error: Field can not be set to this value"
noNodeCnt = noNodeCnt + 1
Case Else
msg = "Unrecognized error: " & rc _
& " , HRESULT = " & ErrCode
unknownCnt = unknownCnt + 1
End Select
End If
Debug.Print vbTab & msg
'
End With 'aField
Next aField
Debug.Print "----------------------------------"
Debug.Print "Number of fields with valid value = " & okCnt
Debug.Print "Number of fields with invalid type = " & errorCnt
Debug.Print "Number of fields with invalid value= " & noNodeCnt
Debug.Print "Number of fields with unknown error = " & unknownCnt
Debug.Print "----------------------------------"
End Sub
You can do this by looking up the list from the 'Customization' object. Here's how I'd do it using ruby:
qc = WIN32OLE.new('TDApiOle80.TDConnection')
qcserver = 'http://testdirector/qcbin/'
qc.InitConnectionEx(qcserver)
qc.Login($username, $password)
qc.Connect("$domain", "$project")
customization = #qc.Customization
list = custom.Lists.List("NextAction")
node = list.RootNode
children = node.Children
children.each do |child|
puts "#{child.Name} \n"
end

Resources