Post File name variable using tcpsend autoit - autoit

I need to know how to post file name variable to desired one instead of "upload.zip"
i know how to automate file name using php only but required autoit to post variable of file name using tcpsend method
Thanks
PHP code:
<?php
print_r($_POST);
print_r($_FILES);
copy($_FILES["upload"]["tmp_name"], "upload.zip");
?>
Autoit code:
ConsoleWrite(_PHPupload('192.168.1.2', _OSmacros(), 89, '/upload/index.php', 'application/zip') & #CRLF)
Func _PHPupload($pIP, $pMacros, $pPort, $phpPath, $pContent)
If FileExists($pFile) = 0 Then Return SetError(1, 1, '')
$pTcpc = TCPConnect($pIP, $pPort)
If #error Then Return SetError(1, 2, '')
Local $pBound = "-----" & Random(10000000, 99999999, 1)
Local $pData1 = "--" & $pBound & #CRLF
$pData1 &= 'Content-Disposition: form-data; name="upload"; filename="' & $pFile & '"' & #CRLF & 'Content-Type: ' & $pContent & #CRLF & #CRLF
Local $pData2 = #CRLF & "--" & $pBound & #CRLF & 'Content-Disposition: form-data ;name="test"' & #CRLF & #CRLF & "variable" & #CRLF
$pData2 &= "--" & $pBound & "--" & #CRLF & #CRLF
Local $pHeader = 'POST ' & $phpPath & ' HTTP/1.1' & #CRLF
$pHeader &= 'Host: ' & $pIP & #CRLF
$pHeader &= 'User-Agent: ' & $pMacros & #CRLF
$pHeader &= 'Content-Type: multipart/form-data; boundary=' & $pBound & #CRLF
$pHeader &= 'Content-Length: ' & (StringLen($pData1) + StringLen($pData2) + FileGetSize($pFile)) & #CRLF & #CRLF
Local $pFopen = FileOpen($pFile, $FO_READ)
If $pFopen = -1 Then Return SetError(1, 3, '')
Local $sFread = FileRead($pFopen)
TCPSend($pTcpc, $pHeader & $pData1 & $sFread & $pData2)
If #error Then Return SetError(1, 4, '')
Local $pBuffer = ""
While 1
$pBuffer &= TCPRecv($pTcpc, 1024)
If #error Then
Return SetError(1, 5, '')
Else
ExitLoop
EndIf
WEnd
MsgBox(64, "", $pBuffer)
EndFunc ;==>_PHPupload

$pFile is not declared, but even if it is, it wont work because its a
filepath and you are sending it as a filename at
filename="' & $pFile
This should work:
ConsoleWrite(_PHPupload('192.168.1.2', _OSmacros(), 89, '/upload/index.php', 'application/zip', "c:\somedir", "somefile.zip") & #CRLF)
Func _PHPupload($pIP, $pMacros, $pPort, $phpPath, $pContent, $pFilePath, $pFileName)
$pFile = $pFilePath & "\" & $pFileName
If FileExists($pFile) = 0 Then Return SetError(1, 1, '')
$pTcpc = TCPConnect($pIP, $pPort)
If #error Then Return SetError(1, 2, '')
Local $pBound = "-----" & Random(10000000, 99999999, 1)
Local $pData1 = "--" & $pBound & #CRLF
$pData1 &= 'Content-Disposition: form-data; name="upload"; filename="' & $pFileName & '"' & #CRLF & 'Content-Type: ' & $pContent & #CRLF & #CRLF
Local $pData2 = #CRLF & "--" & $pBound & #CRLF & 'Content-Disposition: form-data ;name="test"' & #CRLF & #CRLF & "variable" & #CRLF
$pData2 &= "--" & $pBound & "--" & #CRLF & #CRLF
Local $pHeader = 'POST ' & $phpPath & ' HTTP/1.1' & #CRLF
$pHeader &= 'Host: ' & $pIP & #CRLF
$pHeader &= 'User-Agent: ' & $pMacros & #CRLF
$pHeader &= 'Content-Type: multipart/form-data; boundary=' & $pBound & #CRLF
$pHeader &= 'Content-Length: ' & (StringLen($pData1) + StringLen($pData2) + FileGetSize($pFile)) & #CRLF & #CRLF
Local $pFopen = FileOpen($pFile, $FO_READ)
If $pFopen = -1 Then Return SetError(1, 3, '')
Local $sFread = FileRead($pFopen)
TCPSend($pTcpc, $pHeader & $pData1 & $sFread & $pData2)
If #error Then Return SetError(1, 4, '')
Local $pBuffer = ""
While 1
$pBuffer &= TCPRecv($pTcpc, 1024)
If #error Then
Return SetError(1, 5, '')
Else
ExitLoop
EndIf
WEnd
MsgBox(64, "", $pBuffer)
EndFunc ;==>_PHPupload

Related

send a file and parameter HTTP Post with VBS

I'm new working with HTTP protocol and haven't worked with VBS for some time.
The problem I'm having is sending a parameter and an upload file to a web service.
I just don't understand what some of the code is. Below is part of the code.
With CreateObject("MSXML2.ServerXMLHTTP")
.setOption 2, 13056 'http://msdn.microsoft.com/en-
us/library/ms763811(v=VS.85).aspx
.SetTimeouts 0, 60000, 300000, 300000
.Open "POST",
"https://192.168.100.100/api/import_file_here.json", False
.SetRequestHeader "Content-type", "multipart/form-data; boundary=" &
strBoundary 'THIS SEND THE FILE
.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded" '
THIS SEND THE PARAMETER.
.Send bytPD ' sends param
.Send bytPayLoad '''SEND FILE
I know I can't use .Send twice. I believe I need to make a change in the below code block.
With CreateObject("ADODB.Stream")
.Mode = 3
.Charset = "Windows-1252"
.Open
.Type = 2
.WriteText "--" & strBoundary & vbCrLf
'.WriteText "Content-Disposition: form-data; name=""file""; filename=""" &
strFile & """" & vbCrLf
.WriteText "Content-Disposition: form-data; name=""file"";
publication=""moveit_test_pub"""
'.WriteText "Content-Type: """ & strContentType & """" & vbCrLf & vbCrLf
.Position = 0
.Type = 1
.Write bytData
.Position = 0
.Type = 2
.Position = .Size
.WriteText vbCrLf & "--" & strBoundary & "--"
.Position = 0
.Type = 1
bytPayLoad = .Read
bytPD = "publication=moveit_test_pub"
bytPD = "publication=moveit_test_pub" is the parameter I need along with the file upload. I'm just not sure how to add it to the above block. If that's where I'm supposed to change. I'm posting the entire code below for reference.
Thanks for all your help!
strFilePath = "C:\SCAudience_TEST5.txt"
UploadFile strFilePath, strUplStatus, strUplResponse
MsgBox strUplStatus & vbCrLf & strUplResponse
Sub UploadFile(strPath, strStatus, strResponse)
Dim strFile, strExt, strContentType, strBoundary, bytPD, bytData,
bytPayLoad
On Error Resume Next
With CreateObject("Scripting.FileSystemObject")
If .FileExists(strPath) Then
strFile = .GetFileName(strPath)
strExt = .GetExtensionName(strPath)
Else
strStatus = "File not found"
Exit Sub
End IF
End With
With CreateObject("Scripting.Dictionary")
.Add "txt", "text/plain"
.Add "html", "text/html"
.Add "php", "application/x-php"
.Add "js", "application/x-javascript"
.Add "vbs", "application/x-vbs"
.Add "bat", "application/x-bat"
.Add "jpeg", "image/jpeg"
.Add "jpg", "image/jpeg"
.Add "png", "image/png"
.Add "exe", "application/exe"
.Add "doc", "application/msword"
.Add "docx", "application/vnd.openxmlformats-
officedocument.wordprocessingml.document"
.Add "xls", "application/vnd.ms-excel"
.Add "xlsx", "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet"
strContentType = .Item(LCase(strExt))
End With
If strContentType = "" Then
strStatus = "Invalid file type"
Exit Sub
End If
With CreateObject("ADODB.Stream")
.Type = 1
.Mode = 3
.Open
.LoadFromFile strPath
If Err.Number <> 0 Then
strStatus = Err.Description & " (" & Err.Number & ")"
Exit Sub
End If
bytData = .Read
bytPD = "publication=moveit_test_pub"
End With
strBoundary = String(6, "-") & Replace(Mid(CreateObject("Scriptlet.TypeLib").Guid, 2, 36), "-", "")
With CreateObject("ADODB.Stream")
.Mode = 3
.Charset = "Windows-1252"
.Open
.Type = 2
.WriteText "--" & strBoundary & vbCrLf
' .WriteText "Content-Disposition: form-data; name=""file""; filename=""" & strFile & """" & vbCrLf
.WriteText "Content-Disposition: form-data; name=""file""; publication=""moveit_test_pub"""
'.WriteText "Content-Type: """ & strContentType & """" & vbCrLf & vbCrLf
.Position = 0
.Type = 1
.Write bytData
.Position = 0
.Type = 2
.Position = .Size
'' .WriteText vbCrLf & "--" & strBoundary & "--"
.Position = 0
.Type = 1
bytPayLoad = .Read
bytPD = "publication=moveit_test_pub"
End With
With CreateObject("MSXML2.ServerXMLHTTP")
.setOption 2, 13056 'http://msdn.microsoft.com/en-us/library/ms763811(v=VS.85).aspx
.SetTimeouts 0, 60000, 300000, 300000
.Open "POST", "https://192.168.100.100/api/import_file_here.json", False
.SetRequestHeader "Content-type", "multipart/form-data; boundary=" & strBoundary 'THIS SEND THE FILE IF BOTH SELECTED SEND PARM AND TEXT OF FILE
.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded" ' THIS SEND THE PARAMETER.
''' .Send bytPD ' sends param
' .SetRequestHeader "Content-type", "multipart/form-data; boundary=" & strBoundary 'NEW LINE
.Send bytPayLoad '''SEND FILE
MsgBox bytPD
If Err.Number <> 0 Then
strStatus = Err.Description & " (" & Err.Number & ")"
Else
strStatus = .StatusText & " (" & .Status & ")"
End If
If .Status = "400" Then strResponse = .ResponseText
If .Status = "401" Then strResponse = .ResponseText
If .Status = "200" Then strResponse = .ResponseText
End With
End Sub
I found a solution. This was my logic:
with curl you can send a file + parameters with:
curl -XPOST '127.0.0.1:8000' -F 'file=#/Users/luca/Desktop/img.png' -F 'id=123456'
In this case you can see:
IP = 127.0.0.1 (localhost)
Port = 8000
Filename = img.png
Parameter = "id" with value 123456
If you use netcat in listening mode like this...
nc -l -p 8000
This means that it's listening for anything on port 8000 of the localhost = 127.0.0.1 (I'm using the Mac version of Netcat. You may need to change some parameters to make it work like this).
So: launch netcat in listening mode, launch the previous curl command and you will see the entire POST packet. Now you know how it is made.
It will look like that:
POST / HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: curl/7.54.0
Accept: */*
Content-Length: 427
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------60cd44468072da0e
--------------------------60cd44468072da0e
Content-Disposition: form-data; name="file"; filename="img.png"
Content-Type: application/octet-stream
?PNG
IHDR
??w&sRGB???gAMA??
?a pHYs??(J?IDAT(Scd``??D&(MU?
?bg?ܞ?IEND?B`?
--------------------------60cd44468072da0e
Content-Disposition: form-data; name="id"
123456
--------------------------60cd44468072da0e--
Now that you know how the working packet is made, you can replicate it.
For the header use:
httpServer.SetRequestHeader "Content-type", "multipart/form-data; boundary=------------------------2deddc24cb2a8ca2;"
(boundary is sort of delimiter. Check it on Google)
Then you can build the body of the POST request:
body = "--" & "------------------------2deddc24cb2a8ca2" & vbCrLf & _
"Content-Disposition: form-data; name=""file""; filename=""" & objFSO.GetFileName(objFile) & """" & vbCrLf & _
"Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _
FILE_CONTENT & vbCrLf & _
"--" & "------------------------2deddc24cb2a8ca2" & vbCrLf & _
"Content-Disposition: form-data; name=""id""" & vbCrLf & vbCrLf & _
ID & vbCrLf & _
"--" & "------------------------2deddc24cb2a8ca2" & "--" & vbCrLf & vbCrLf
NOTE:
in the body you can see that every boundary has an additional "--" string at the beginning (infact i wrote "--" & "------------------------2deddc24cb2a8ca2") and an additional "--" at the end of the last boundary.
The header must have ";" at the end of the line in vbs even if is not visible in the previous captured POST request. I don't know exactly why.
The FILE_CONTENT variable in the body is the content of your file
Take care for every vbCrLf (end of the line) or the POST request may not be valid.
PROBLEM:
The code you posted below should open a stream, write the first part of the body as a string, write the BINARY content of your file, write the last part of the body as a string.
Combining String and Binary data it's not working for me: i can send only the binary or only text file. If i convert the binary content to string, the remote server will get a corrupted (different) file...
example (binary file only):
Set stream = CreateObject("ADODB.Stream")
stream.Mode = 3
stream.Type = 1
stream.Open
stream.LoadFromFile("C:\Users\Luca\Desktop\i.png")
Set objHttp = CreateObject("MSXML2.ServerXMLHTTP")
objHttp.Open "POST", "http://10.0.2.2:8000/", False
objHttp.Send stream.Read(stream.Size)
example (text file only)
Set stream = CreateObject("ADODB.Stream")
stream.Mode = 3
stream.Type = 2
stream.Open
stream.LoadFromFile("C:\Users\Luca\Desktop\i.txt")
readBinaryFile = stream.Read
requestBody = "--------------------------2deddc24cb2a8ca2" & vbCrLf & _
"Content-Disposition: form-data; name=""file""; filename=""" & objFSO.GetFileName(objFile) & """" & vbCrLf & _
"Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _
readBinaryFile & vbCrLf & _
"--------------------------2deddc24cb2a8ca2" & vbCrLf & _
"Content-Disposition: form-data; name=""id""" & vbCrLf & vbCrLf & _
ID & vbCrLf & _
"--------------------------2deddc24cb2a8ca2--" & vbCrLf & vbCrLf
As i told you, if you change the stream.Type from 2 to 1 (for Binary) you will end to send a corrupted file.
My solution was to send the parameter as an extra Header value:
Example:
httpServer.Open "POST", "http://10.0.2.2:8000/", False
httpServer.SetRequestHeader "Content-type", "application/octet-stream;"
httpServer.SetRequestHeader "Id", ID
httpServer.Send stream.Read(stream.Size)
Now i can send the parameter (Id) AND the binary file...
NOTE: With Content-type: application/octet-stream you can send unknow file extension too

Why does my script return 0?

This AutoIt script counts number of words; characters (with and without spaces); lines; and estimated speaking time (assuming two words per second) for text selected by the user.
However, if the starting position is 0 for the input string (at the upper left-hand corner of the top of the file) the method returns 0 for everything, even when the main function works perfectly.
I cannot figure out why.
$input_str = GUICtrlRead($Textbox)
$selpos = _GUICtrlEdit_GetSel($Textbox)
MsgBox($MB_OK, $selpos[0], $selpos[1])
$selstring = StringMid($input_str, $selpos[0], ($selpos[1] - $selpos[0]))
$WordArray = StringRegExp($selstring, "[\s\.:;,]*([a-zA-Z0-9-_]+)[\s\.:;,]*", 3)
$SingleQuotes = StringRegExp($selstring, "'", 3)
$Result = ""
$Seconds = (UBound($WordArray) - UBound($SingleQuotes)) / 2
If $Seconds >= 3600 Then
If $Seconds / 3600 >= 2 Then
$Result = $Result & Int($Seconds / 3600) & " hours "
Else
$Result = $Result & Int($Seconds / 3600) & " hour "
EndIf
EndIf
If Mod($Seconds, 3600) >= 60 Then
If $Seconds / 60 >= 2 Then
$Result = $Result & Int(Mod($Seconds, 3600) / 60) & " minutes "
Else
$Result = $Result & Int(Mod($Seconds, 3600) / 60) & " minute "
EndIf
EndIf
If Mod($Seconds, 60) > 0 Then
If Mod($Seconds, 60) >= 2 Then
$Result = $Result & Int(Mod($Seconds, 60)) & " seconds "
Else
$Result = $Result & Int(Mod($Seconds, 60)) & " second "
EndIf
EndIf
MsgBox($MB_OK, "Selection Properties", _
"Number of characters (with spaces): " & StringLen($selstring) & #CRLF & _
"Number of Characters (without spaces): " & StringLen(StringStripWS($selstring, 8)) & #CRLF & _
"Number of words: " & (UBound($WordArray) - UBound($SingleQuotes)) & #CRLF & _
"Number of lines: " & _GUICtrlEdit_GetLineCount($selstring) & #CRLF & _
"Estimated speaking time: " & $Result _
)
If $selpos[0] = 0 then StringMid() returns an empty string since your start is out of bounds (as first position for StringMid() is 1).
$sTest = "A sample test string"
MsgBox(0, '' , StringMid($sTest , 0 , 8))
MsgBox(0, '' , StringMid($sTest , 1 , 8))

How to determine newline while reading a file

I have an AutoIt script that works, mostly. Reads a file, writes out what I want, but it does not preserve the original newline character. If I read a UNIX format file (LF only), it will write out a Windows format file (CR and LF).
Short of switching to something more robust, like Python, how do I solve this in AutoIt?
Opt("MustDeclareVars", 1) ;0 = no, 1 = require pre-declare
#include <File.au3>
#include <Array.au3>
Local $gInPath = $CmdLine[1]
Local $NumberOfLines = $CmdLine[2]
Local $gInDrive, $gInDir, $gInFName, $gInExt, $gOutPath
Local $gMsgBoxTitle = "Error in " & #ScriptName
Local $InLine
Local $LineCount
Local $oFileIn
Local $oFileOut
Local $FileStringAppend
If FileExists($gInPath) Then
Else
MsgBox(4096, $gMsgBoxTitle, "This file does not exist" & #CRLF & $gInPath)
Exit
EndIf
_PathSplit($gInPath, $gInDrive, $gInDir, $gInFName, $gInExt)
If $NumberOfLines >= 1000000 Then
$FileStringAppend = $NumberOfLines / 1000000 & "M"
ElseIf $NumberOfLines >= 1000 Then
$FileStringAppend = $NumberOfLines / 1000 & "K"
Else
$FileStringAppend = $NumberOfLines
EndIf
$gOutPath = _PathMake($gInDrive, $gInDir, $gInFName & "_" & $FileStringAppend, $gInExt)
If FileExists($gOutPath) Then
MsgBox(4096, $gMsgBoxTitle, "File already exists" & #CRLF & $gOutPath)
Exit
EndIf
$oFileIn = FileOpen($gInPath, 0)
$oFileOut = FileOpen($gOutPath, 1)
; Check if file opened for reading OK
If $oFileIn = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for read" & #CRLF & $gInPath)
Exit
EndIf
; Check if file opened for writing OK
If $oFileOut = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for write." & #CRLF & $gOutPath)
Exit
EndIf
; Read in lines of text until the EOF is reached
$LineCount = 0
While 1
$InLine = FileReadLine($oFileIn)
$LineCount += 1
If #error = -1 Then ExitLoop
If $LineCount > $NumberOfLines Then ExitLoop
FileWriteLine($oFileOut, $InLine & #CRLF)
WEnd
FileClose($oFileIn)
FileClose($oFileOut)
Looking at the function documentation at this link - https://www.autoitscript.com/autoit3/docs/functions/FileWriteLine.htm . It appears you can leave off the & #CRLF in your FileWriteLine command.
AutoIt should use the same line terminator that is read in, or
"If the line does NOT end in #CR or #LF then a DOS linefeed (#CRLF)
will be automatically added."
Here's the solution I came up. It works, but I'm not sure it's the cleanest.
Opt("MustDeclareVars", 1) ;0 = no, 1 = require pre-declare
#include <File.au3>
#include <Array.au3>
Local $gInPath = $CmdLine[1]
Local $NumberOfLines = $CmdLine[2]
Local $gInDrive, $gInDir, $gInFName, $gInExt, $gOutPath
Local $gMsgBoxTitle = "Error in " & #ScriptName
Local $InLine
Local $LineCount
Local $oFileIn
Local $oFileOut
Local $FileStringAppend
Local Const $CHAR_READ_BLOCK = 100
Local $CharsRead = 0
Local $CrFound = 0
Local $LfFound = 0
Local $Newline
Local $InBlock
If FileExists($gInPath) Then
Else
MsgBox(4096, $gMsgBoxTitle, "This file does not exist" & #CRLF & $gInPath)
Exit
EndIf
_PathSplit($gInPath, $gInDrive, $gInDir, $gInFName, $gInExt)
If $NumberOfLines >= 1000000 Then
$FileStringAppend = $NumberOfLines / 1000000 & "M"
ElseIf $NumberOfLines >= 1000 Then
$FileStringAppend = $NumberOfLines / 1000 & "K"
Else
$FileStringAppend = $NumberOfLines
EndIf
$gOutPath = _PathMake($gInDrive, $gInDir, $gInFName & "_" & $FileStringAppend, $gInExt)
If FileExists($gOutPath) Then
MsgBox(4096, $gMsgBoxTitle, "File already exists" & #CRLF & $gOutPath)
Exit
EndIf
$oFileIn = FileOpen($gInPath, 0)
$oFileOut = FileOpen($gOutPath, 1)
; Check if file opened for reading OK
If $oFileIn = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for read" & #CRLF & $gInPath)
Exit
EndIf
; Check if file opened for writing OK
If $oFileOut = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for write." & #CRLF & $gOutPath)
Exit
EndIf
While $CrFound = 0 And $LfFound = 0
$CharsRead += $CHAR_READ_BLOCK
$InBlock = FileRead($oFileIn, $CharsRead)
If StringRight($InBlock, 1) = #CR Then
$InBlock = $InBlock & FileRead($oFileIn, $CharsRead)
EndIf
$CrFound = StringInStr($InBlock, #CR)
$LfFound = StringInStr($InBlock, #LF)
If $CrFound > 0 And $LfFound > 0 Then
$Newline = #CRLF
ElseIf $CrFound > 0 Then
$Newline = #CR
Else
$Newline = #LF
EndIf
WEnd
; Read first line of text
$InLine = FileReadLine($oFileIn, 1)
$LineCount = 1
FileWriteLine($oFileOut, $InLine & $Newline)
; Read in lines of text until the EOF is reached
While 1
$InLine = FileReadLine($oFileIn)
$LineCount += 1
If #error = -1 Then ExitLoop
If $LineCount > $NumberOfLines Then ExitLoop
FileWriteLine($oFileOut, $InLine & $Newline)
WEnd
FileClose($oFileIn)
FileClose($oFileOut)

ADODB.Recordset error '800a0e78' Operation is not allowed when the object is closed

Set RsItem = Conn.Execute("EXEC E_UpdateDevBehaviourSmalls #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID")& " ,#cCompID=" & cCompetenceid & " ,#reason=" &reason & " ,#comptype=" & comptype &",#GID=" & GID & " ,#Behaviour='" & MakeSendable(Behaviour) & "' ,#Deadline='" & deadlinedatetime & "' ,#DevBehaviour='" & MakeSendable(DevBehaviour) & "' ,#Why='" & MakeSendable(Why) & "' ,#ExtraNote='" & MakeSendable(ExtraNote) & "'")
if GID = 0 then
if not RsItem.eof then
GID = RsItem.fields(0).value
if reason = 0 then
'add dummy devbehaviour detail
Set RsItem =Conn.Execute("EXEC E_UpdateDevBehaviourDetail #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#GID=" & GID & " ,#DID=0 ,#TextField1='dummy' ,#educ= 0 ,#TextField2='dummy' ,#TextField3='dummy' ,#TextField4='dummy'")
end if
end if
end if
When I try to execute the code above (full code below) I got the following error:
(It gets stuck at the following part: if not RsItem.fields(0).value)
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
Can anyone help me with this error?
<%
Dim DID
Dim GID
Dim cCompetenceid
Dim Behaviour
Dim Deadline
Dim DevBehaviour
Dim Why
Dim ExtraNote
MakeConn
Session("OnlinePageID") = 106
InsertLogItem "S:12"
If Session("EUserType")=1 Then
If UCase(Request("Action"))="SAVEDETAIL" Then
If not Request("DID")="" Then
DID = Request("DID")
Else
DID = 0
End If
Conn.Execute("EXEC E_UpdateDevBehaviourDetail #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#GID=" & Request("GID") & " ,#DID=" & DID & " ,#TextField1='" & MakeSendable(Request("TextField1")) & "' ,#TextField2='" & MakeSendable(Request("TextField2")) & "' ,#TextField3='" & MakeSendable(Request("TextField3")) & "' ,#TextField4='" & MakeSendable(Request("TextField4")) & "'")
Conn.Execute("EXEC E_SignIDP #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#SignStatus=0")
End If
End If
'response.write Session("EUserType") & "<br>"
If Session("EUserType")=1 Then
Select Case UCase(Request("Action"))
Case "EDIT"
If not Request("GID")="" Then
'response.write "EXEC E_GetDevBehavior #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#GID=" & Request("GID") & "<br>"
Set RsItem = Conn.Execute("EXEC E_GetDevBehavior #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#GID=" & Request("GID"))
If not RsItem.EOF Then
Behaviour = Replace (RsItem("Behaviour"),"''","'")
Deadline = RsItem("Deadline")
DevBehaviour = Replace (RsItem("DevBehaviour"),"''","'")
Why = Replace (RsItem("Why"),"''","'")
ExtraNote = Replace (RsItem("ExtraNote"),"''","'")
Else
Response.End
End If
'RsItem.close
'Set RsItem = nothing
Else
End If
Case "SAVE"
If not Request("GID")="" Then
Set RsItem = Conn.Execute("EXEC E_GetDevBehavior #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#GID=" & Request("GID"))
If not RsItem.EOF Then
Behaviour = Replace (RsItem("Behaviour"),"''","'")
Deadline = RsItem("Deadline")
DevBehaviour = Replace (RsItem("DevBehaviour"),"''","'")
Why = Replace (RsItem("Why"),"''","'")
ExtraNote = Replace (RsItem("ExtraNote"),"''","'")
Else
Response.End
End If
'RsItem.close
'Set RsItem = nothing
end if
dag = Day(Now())
maand = Month(Now())
jaar = Year(Now())
uur = Hour(Time)
minuten = Minute(Time)
seconden = Second(Time)
if len(dag)< 2 then dag ="0" & dag
if len(maand) < 2 then maand ="0" & maand
if len(uur) < 2 then uur ="0" & uur
if len(minuten) < 2 then minuten ="0" & minuten
if len(seconden) < 2 then seconden ="0" & seconden
datum= jaar & "-" & maand & "-" & dag
tijd = uur & ":" & minuten& ":" & seconden
datumtijd = datum & " " & tijd
Conn.Execute("EXEC E_UpdatePOPStartDate #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID"))
Conn.Execute("EXEC E_UpdateStartDate #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#StartDate='" & datumtijd & "'")
If not Request("GID")="" Then
GID = Request("GID")
newcomp = false
Else
GID = 0
Deadline = CDate(FormatDate("31/12/"&year(now)))
newcomp = true
End If
'response.write Request("cCompetenceid") &"<br>"
if not Request("cCompetenceid") = "" then
cCompetenceid = Request("cCompetenceid")
else
cCompetenceid = 0
end if
if not Request("reason") = "" then
reason = Request("reason")
else
reason = 0
end if
if not Request("comptype") = "" then
comptype = Request("comptype")
else
comptype = 1
end if
Select Case (Request("COMPID"))
Case 1460
Behaviour = Request("Behaviour")
Case 1461
Deadline = Request("DeadlineDay") & "-" & Request("DeadlineMonth") & "-" & Request("DeadlineYear")
Deadline = CDate(FormatDate(Deadline))
Case 1462
DevBehaviour = Request("DevBehaviour")
Case 1463
Why = Request("Why")
Case 1464
ExtraNote = Request("ExtraNote")
End Select
deadlinedate = CDate(Deadline)
deadlineyear = year(deadlinedate)
deadlinemonth = month(deadlinedate)
deadlineday = day(deadlinedate)
deadlinedatetime = deadlineyear & "-" & deadlinemonth & "-" & deadlineday & " 00:00:00"
'response.write "EXEC E_UpdateDevBehaviourSmalls #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID")& " ,#cCompID=" & cCompetenceid & " ,#reason=" &reason & " ,#comptype=" & comptype &",#GID=" & GID & " ,#Behaviour='" & MakeSendable(Behaviour) & "' ,#Deadline='" & deadlinedatetime & "' ,#DevBehaviour='" & MakeSendable(DevBehaviour) & "' ,#Why='" & MakeSendable(Why) & "' ,#ExtraNote='" & MakeSendable(ExtraNote) & "'"
'response.end
Set RsItem = Conn.Execute("EXEC E_UpdateDevBehaviourSmalls #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID")& " ,#cCompID=" & cCompetenceid & " ,#reason=" &reason & " ,#comptype=" & comptype &",#GID=" & GID & " ,#Behaviour='" & MakeSendable(Behaviour) & "' ,#Deadline='" & deadlinedatetime & "' ,#DevBehaviour='" & MakeSendable(DevBehaviour) & "' ,#Why='" & MakeSendable(Why) & "' ,#ExtraNote='" & MakeSendable(ExtraNote) & "'")
if GID = 0 then
if not RsItem.eof then
GID = RsItem.fields(0).value
if reason = 0 then
' add dummy devbehaviour detail
Set RsItem =Conn.Execute("EXEC E_UpdateDevBehaviourDetail #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#GID=" & GID & " ,#DID=0 ,#TextField1='dummy' ,#educ= 0 ,#TextField2='dummy' ,#TextField3='dummy' ,#TextField4='dummy'")
end if
end if
end if
'RsItem.close
'Set RsItem = nothing
Conn.Execute("EXEC E_SignIDP #ClientID=" & Session("ClientID") & " ,#UserID=" & Session("EUserID") & " ,#SignStatus=0")
if newcomp = true then
tempstr = "../popoverview.asp"
ClientScript("parent.location.href = '../bottomframe.asp?GID=" & GID & "&" & SetID &"&ViewID=4'" )
else
response.write " in"
tempstr = "compoverview.asp?Action=Edit&GID="&GID
response.redirect tempstr
' ClientScript("location.href =" & tempstr)
end if
End Select
End If
conn.close
set conn= nothing
%>
Stored procedure:
USE [Q]
GO
/****** Object: StoredProcedure [dbo].[E_UpdateDevBehaviourSmalls] Script Date: 17/10/2013 15:05:53 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[E_UpdateDevBehaviourSmalls]
(#ClientID int,
#UserID int,
#cCompID int,
#reason int,
#comptype int,
#GID int,
#Behaviour varchar(250),
#Deadline datetime,
#DevBehaviour text,
#Why text,
#ExtraNote text)
AS
If (#GID = 0)
BEGIN
INSERT INTO DevBehaviour(ClientID,UserID,Behaviour,Deadline,DevBehaviour,Why,ExtraNote,cCompId,reason,comptype)
VALUES(#ClientID,#UserID,#Behaviour,#Deadline,#DevBehaviour,#Why,#ExtraNote, #cCompID,#reason,#comptype)
SELECT ##identity
END
Else
BEGIN
UPDATE DevBehaviour
SET Behaviour=#Behaviour, Deadline=#Deadline, DevBehaviour=#DevBehaviour, Why=#Why, ExtraNote=#ExtraNote, cCompId = #cCompID, reason = #reason, comptype = #comptype
WHERE (ClientID = #ClientID) AND (UserID = #UserID) AND (GID = #GID)
END
I was able to reproduce your problem. Please try the stored proc below (using nocount)
USE [Q]
GO
/****** Object: StoredProcedure [dbo].[E_UpdateDevBehaviourSmalls] Script Date: 17/10/2013 15:05:53 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[E_UpdateDevBehaviourSmalls]
(#ClientID int,
#UserID int,
#cCompID int,
#reason int,
#comptype int,
#GID int,
#Behaviour varchar(250),
#Deadline datetime,
#DevBehaviour text,
#Why text,
#ExtraNote text)
AS
set nocount on
If (#GID = 0)
BEGIN
INSERT INTO DevBehaviour(ClientID,UserID,Behaviour,Deadline,DevBehaviour,Why,ExtraNote,cCompId,reason,comptype)
VALUES(#ClientID,#UserID,#Behaviour,#Deadline,#DevBehaviour,#Why,#ExtraNote, #cCompID,#reason,#comptype)
SELECT ##identity
END
Else
BEGIN
UPDATE DevBehaviour
SET Behaviour=#Behaviour, Deadline=#Deadline, DevBehaviour=#DevBehaviour, Why=#Why, ExtraNote=#ExtraNote, cCompId = #cCompID, reason = #reason, comptype = #comptype
WHERE (ClientID = #ClientID) AND (UserID = #UserID) AND (GID = #GID)
END
set nocount off

How to add the email sending script

I'm new to VbScript. I have to make a form for uploading a file and sending to specified email as attachment.
For uploading I used this script http://www.freeaspupload.net/freeaspupload/viewsource.asp
Now my application saves file to server.
The second part looks like this:
<% OPTION EXPLICIT
If Request.Cookies("QuoteRequest") = "Quote" THEN
Dim fileName
Dim strMsg
Dim mail
Dim strSubject
Dim strFrom
Dim strReply
Dim strChoice
Dim AddCheck
Dim MyCheckDate
Dim strMailBlindCopy
Dim smtpserver
Dim youremail
Dim public_mailer
Dim public_password
smtpserver = ""
youremail = ""
public_mailer = ""
public_password = ""
AddCheck = Request.Form("Str_xxrand234Myanswer")
'Use this next line if you want a blind copy send for your records
'strMailBlindCopy = "info#ciupac.com"
'IF AddCheck = "" or NULL THEN
IF len(AddCheck)>2 OR len(AddCheck)<1 OR IsNumeric(AddCheck)=FALSE THEN
response.write "<h2>Sorry an error has occurred, please click here to return to the form</h2>" & AddCheck
Else
Dim ObjSendMail
Set ObjSendMail = CreateObject("CDO.Message")
'This section provides the configuration information for the remote SMTP server.
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtpserver
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Use SSL for the connection (True or False)
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
' If your server requires outgoing authentication uncomment the lines bleow and use a valid email address and password.
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = public_mailer
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = public_password
ObjSendMail.Configuration.Fields.Update
strFrom = "Quote Request Form"
strReply = Request.Form("txtemail")
strSubject = "Quote Request Form"
strMsg = strMsg & "<b>Your Name:</b> " & Request.Form("txtname") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Your Company Name:</b> " & Request.Form("txtcompany") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Your Order Number:</b> " & Request.Form("txtyourorder") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Our Order Number:</b> " & Request.Form("txtourorder") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Destination Postal Code:</b> " & Request.Form("txtpostal") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Order Date:</b> " & Request.Form("txtdate") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Your E-mail Address:</b> " & Request.Form("txtemail") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Telephone #:</b> " & Request.Form("txtphone") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Comments:</b> " & Request.Form("txtcomments") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Market Served:</b> " & Request.Form("option1") & ", " & Request.Form("option2") & ", " & Request.Form("option3") & ", " & Request.Form("option4") & ", " & Request.Form("option5") & ", " & Request.Form("option6") & ", " & Request.Form("option7") & ", " & Request.Form("option8") & ", " & Request.Form("option9") & ", " & Request.Form("option10") & ", " & Request.Form("option11") & ", " & Request.Form("option12") & ", " & Request.Form("option13") & ", " & Request.Form("option14") & vbCrLF & vbCrLF & "<BR>" & "<BR>"
strMsg = strMsg & "<b>Topic of Interest:</b> " & Request.Form("option15") & ", " & Request.Form("option16") & ", " & Request.Form("option17") & ", " & Request.Form("option18") & ", " & Request.Form("option19") & ", " & Request.Form("option20") & ", " & Request.Form("option21") & ", " & Request.Form("option22") & ", " & Request.Form("option23") & ", " & Request.Form("option24") & ", " & Request.Form("option25") & ", " & Request.Form("option26") & ", " & Request.Form("option27") & ", " & Request.Form("option28") & ", " & Request.Form("option29") & ", " & Request.Form("option30") & ", " & Request.Form("option31") & ", " & Request.Form("option32") & vbCrLF & vbCrLF
fileName = Request.Form("file")
Dim strMailTo
strMailTo =""
ObjSendMail.To = strMailTo
ObjSendMail.Subject = strSubject
ObjSendMail.From = strReply
ObjSendMail.HTMLBody = strMsg
If Len(fileName)Then
ObjSendMail.AddAttachment "C:\attachments\" & fileName
End If
ObjSendMail.Send
Set ObjSendMail = Nothing
Response.Redirect("thank-you.asp")
END IF
ELSE
Dim txtname
Response.Write "ERROR <P>"
fname=Request.Cookies("QuoteRequest")
response.write("QuoteRequest=" & txtname)
END IF
%>
These two scripts work well independently, but when I try to include the email send part to upload the Cannot use Request.Form collection after calling BinaryRead error appears.
How do I need to call the email sender?
Due to the special ENCTYPE="multipart/form-data" attribute of your form, you cannot use the Reqest.Form collection. Use Upload.Form instead, but only after you call Upload.Save (SaveVirtual, SaveToMemory).

Resources