i'm developing a client to send images to a server using multipart/form-data,
my partner is a using a mac and i'm on win8.
i'm sending everything the way it works on a mac but from the client side it can't pass through the webservice and the error message is: "bad content body"
this is my code:
string boundary = "96c334567890";
byte[] sub = AuxiliaryMethods.ReadFileInCloudStorage(urlImg, i);
//POST
// Create a request using a URL that can receive a post.
WebRequest request = (HttpWebRequest)WebRequest.Create(urlImgPost);
// Create POST data and convert it to a byte array.
string strAux = "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"photo" + i + ".jpg\"" + "\r\n" +
"Content-Type: image/jpeg" + "\r\n\r\n" +
System.Text.Encoding.UTF8.GetString(sub) + "\r\n" +
boundary + "--";
byte[] byteArray = Encoding.UTF8.GetBytes(strAux);
// Set the Method property of the request to POST.
request.Method = "POST";
request.Headers.Add("Authorization: Token token=token");
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Set the ContentType property of the WebRequest.
request.ContentType = "multipart/form-data; boundary="+boundary;
and my header and body should look something like this:
POST https://apidev.test.pt/images HTTP/1.1
Authorization: Token token=token
Content-Type: multipart/form-data; boundary=96c334567890
Host: apidev.test.pt
Content-Length: 764939
--96c334567890
content-disposition: form-data; name="file"; filename="photo1.jpg"
content-type: image/jpeg
(image binary data)
96c334567890--
should i be adding something because i'm on a windows system or is my request beeing done the wrong way?
this is formatted with the RFC2388
To upload a file to server
strBoundary = AlphaNumString(32)
strBody = "--" & strBoundary & vbCrLf
strBody = strBody & "Content-Disposition: form-data; name=""" & UploadName & """; filename=""" & filename & """" & vbCrLf
strBody = strBody & "Content-Type: " & MimeType & vbCrLf
strBody = strBody & vbCrLf & strData
strBody = strBody & vbCrLf & "--" & strBoundary & "--"
Length = Len(strBody)
strHTTP = "POST " & DestUrl.URI & "?" & DestUrl.Query & " HTTP/1.0" & vbCrLf
strHTTP = strHTTP & "Host: " & DestUrl.Host & vbCrLf
strHTTP = strHTTP & "Content-Type: multipart/form-data, boundary=" & strBoundary & vbCrLf
strHTTP = strHTTP & "Content-Length: " & Length & vbCrLf & vbCrLf
strHTTP = strHTTP & strBody
Related
Update - 2/14/21
Ok, this is where I'm at now. the code below works! Yay! However, there are no records in the database to read.
''''
<%
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital catalog=" & db_name & "; User ID=" & db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
If IsObject(conn) then
response.write "The connection is active!<br />"
if conn.State = 1 then
response.write "A connection is made, and is open.<br />"
end if
end if
'Query the tables I need
Set rs= conn.execute("SELECT * FROM [" & db_name & "].[" & db_schema & "].[" & db_tablename & "]")
do until rs.EOF
count = count + 1
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br>")
next
Response.Write("<br>")
rs.MoveNext
loop
Set conn = nothing
response.write "Records found = " & count
%>
''''
So with the part above is actually working again. I set out to add a record to the database with the code below. It seems to work as it does not cause an error. However, it is not adding the record though.
''''
<%
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
count = 0
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital catalog=" & db_name & "; User ID=" & db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
If IsObject(conn) then
response.write "The connection is active!<br />"
if conn.State = 1 then
response.write "A connection is made, and is open.<br />"
end if
end if
sql="INSERT INTO " & db_name & "." & db_schema & "." & db_tablename & " (fname,lname,email,upassword)"
sql=sql & " VALUES "
sql=sql & "('John',"
sql=sql & "'Doe',"
sql=sql & "'JohnD#email.com',"
sql=sql & "'12345')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
Set conn = nothing
%>
''''
This is where I have been stuck. It is not writing to the database. It just runs and nothing gets done. If I remove the resume next portion, it still works with no error but, still, no record being written cause the resume next. I have tried two different users to run the code. Both of which have read and write permission. Now what? I'll just keep trying until someone puts me out of my misery... lol!
Well, it seems a friend and I finally found out what was going on. The code actually works but, for some reason, the database's ID field is not auto-incrementing. So, in order to add a record, we had to first check to see how many records are in the DB then add 1 to the count to use for our new records id. Seems every solution leads to a new issue. That's programing...
Just in case any of that makes sense or even if it doesn't make sense, here the id's properties.
ID (PK, uniqueidentifier, not null)
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
count = 0
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital
catalog=" & db_name & "; intergaraded security = false ; User ID=" &
db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
'If IsObject(conn) then
' response.write "The connection is active!<br />"
' if conn.State = 1 then
' response.write "A connection is made, and is open.<br />"
' end if
'end if
Set rs= conn.execute("Select top 1 id from " & db_name & "." & db_schema & "." & db_tablename & " order by id desc")
on error resume next
do until rs.EOF
for each x in rs.Fields
count = x.value
'response.write x.value & "<br>"
next
rs.MoveNext
loop
'conn.Execute sql,recaffected
if err<>0 then
Response.Write("<br>id: " & err.description)
else
'Response.Write("<h3>" & count & " record in db</h3>")
end if
'conn.close
Set rs= conn.execute("Select top 1 id from " & db_name & "." & db_schema & "." & db_tablename & " order by id desc")
sql=sql & " VALUES "
sql=sql & "(" & cstr(count + 1) & ","
sql=sql & "'John',"
sql=sql & "'Doe',"
sql=sql & "'user#website.com',"
sql=sql & "'1234abcd')"
'response.write sql & "<br>"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("<br>insert: " & err.description)
else
'Response.Write("<br>" & recaffected & " record added</h3>")
end if
conn.close
Set conn = nothing
I left all the error checking in there but, it is all commented out. I hope this is the last time I have to come back to this. Goodluck!
I have a database with a table called LaptopTrolleyWU that has the following structure:
ComputerName varchar(50)
TimeStamp datetime
Log varchar(MAX)
I am trying to insert text into the Log field from a VBScript script, but cannot work out the syntax in order to do so.
This is what I have so far:
For I = 0 to updatesToInstall.Count - 1
WScript.Echo I + 1 & "> " & _
updatesToInstall.Item(i).Title & _
": " & installationResult.GetUpdateResult(i).ResultCode
objFile.WriteLine(I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode)
Connection.Execute "INSERT INTO LaptopTrolleyWU (Log) VALUES ('" & I + 1 & "'> '" & updatesToInstall.Item(i).Title & "': '" & installationResult.GetUpdateResult(i).ResultCode & "')"
Next
End If
I get an error that reads
'Microsoft OLE DB Provider for ODBC Drivers: [Microsoft][ODBC SQL
Server Driver][SQL Server][Incorrect syntax near ')'.
What am I doing wrong?
If it helps, this is how I originally connect to the DB, which I might have done incorrectly...
Set Connection = CreateObject("ADODB.Connection")
Set Recordset = CreateObject("ADODB.Recordset")
Dim ConnectionString
ConnectionString = "Driver={SQL Server};Server=server;Trusted_Connection=no;Database=LaptopTrolly;Uid=Laptop;Pwd=password"
Connection.Open ConnectionString
This is what I did in the end:
strLogText = I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
strSQLCmd = "INSERT INTO dbo.LaptopTrolleyWU (ComputerName,TimeStamp,Log) VALUES ('" + strComputerName + "', '" + dtTimeStamp + "' , '" + strLogText + "')"
Connection.Execute strSQLCmd
Your task is to write the value of a string expression into a log file and a database field (I assume the .Echo is just for debugging). Then you should invest into a variable to hold the value of the expression and use that twice:
v = I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
Writing to a file is easy, because you just need the plain data:
objFile.WriteLine v
(no spurious param list ()!). You need an INSERT statement to put v into the database; the value of v has to be single quoted:
>> v = "pipapo"
>> s = Replace("INSERT INTO LaptopTrolleyWU (Log) VALUES ('#v')", "#v", v)
>> WScript.Echo s
>>
INSERT INTO LaptopTrolleyWU (Log) VALUES ('pipapo')
>>
If you then do
WScript.Echo s
Connection.Execute s
you can be sure that the statement you execute is the code you have visually inspected.
Your expressions differ:
I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
I + 1 & "'> '" & updatesToInstall.Item(i).Title & "': '" & installationResult.GetUpdateResult(i).ResultCode
The extra single quotes in the INSERT statement make the SQL parser assume you want to compare string literals.
Hey all i am trying to get a connection to my SQL server version 10.50.2500 in Classic ASP
My code in the .asp page is (including all connection strings I've tried using):
Set objConn = Server.CreateObject("ADODB.Connection")
Set objRS = Server.CreateObject("ADODB.Recordset")
'objConn.ConnectionString = "Provider={SQL Server};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;User ID=xxxx;Pwd=xxxx"
'objConn.ConnectionString = "Driver={SQL Server};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx;"
'objConn.ConnectionString = "Provider=SQLNCLI10;Server=xxx.xxx.xxx.xxx,1433;Database=JForm;Uid=xxxx;Pwd=xxxx;Persist Security Info=True"
'objConn.ConnectionString = "Provider=SQLNCLI;Server=.\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx"
objConn.ConnectionString = "Driver={SQL Server Native Client 10.0};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx"
strSQL = "UPDATE jURLS " & _
"SET rssFeedURL = 'http://www.xxxx.com/rss/" & rss & "'," & _
"csvURL = 'http://www.xxxx.com/csv/" & csv & "'," & _
"jFormName = '" & forname & "'," & _
"isActive = " & active & " " & _
"WHERE jFormName = '" & forname & "'"
objConn.open
objRS.Open strSQL, objConn, 1,3
'If Not objRS.EOF Then
'iterate through records here
'Else
'no records found
'End If
objRS.close
Set objRS=Nothing
objConn.close
Set objConn=Nothing
It seems to crash on the objConn.open. However, it only gives me a 500 - Internal server error. and not an error thats helpful!
Once i take the database code from the page and leave everything else, it works without the 500 - Internal server error being displayed.
What else can i try in order to get this to work?
you have an extra comma here :
"isActive = " & active & "," & _
change it to:
"isActive = " & active & " " & _
about the connection error, try debugging using the connection.errors collection
On Error Resume Next
objConn.open
for each errobj in objConn.Errors
Response.write errobj.Number & "<br />"
Response.write errobj.Description & "<br />"
next
On Error Goto 0
Try:
response.write(strSQL) <-- this will allow you to look at your current SQL statement and see if it makes sense.
set objRS = objConn.execute(strSQL)
Using VBScript, is there any way to allow for multiple simultaneous writes to a text file from multiple computers? I need to run a script from multiple computers at the same time. The script will perform a DEFRAG and save the results to a text file. After that, the script will read from the DEFRAG log file, pull the fragmentation percentage, and write it to another MASTER log file that is meant to contain these results from every computer across the enterprise. If I always only run the script from one computer at a time, then everything works find and dandy. However, once I use a distribution point to throw the script out to the enterprise, the script works perfectly up until the point where more than one computer attempts to access the MASTER log file at the same time. That's when I'm running into access denied errors and the like. Here's what I've got so far...
strDrivePreCheckStarted = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
a=("===================================================================================")
b=(" Script started on " & strDrivePreCheckStarted)
Set objWMIService = GetObject( "winmgmts:\\.\root\cimv2" )
Set colSettings = objWMIService.ExecQuery ( "Select * from Win32_ComputerSystem", , 48 )
For Each objComputer in colSettings
CompNam = objComputer.Name
If CompNam = "" Then
CompNam = "ComputerNameNotFound"
End If
CompMfr = replace(objComputer.Manufacturer,",","")
If CompMfr = "" Then
CompMfr = "ComputerMfrNotFound"
End If
CompMdl = objComputer.Model
If CompNam = "" Then
CompNam = "ComputerModelNotFound"
End If
Next
Set dClient = GetObject( "winmgmts://" & CompNam & "/root/ccm:SMS_Client" )
Set result = dClient.ExecMethod_("GetAssignedSite")
mClient = result.sSiteCode
If mClient = "OLD" Then
mClient = "SMS"
End If
If mClient = "NEW" Then
mClient = "SCCM"
End If
If mClient = "" Then
mClient = "UNKNOWN"
End If
c=(" Computer: " & "[" & mClient & "] " & CompNam & " (" & CompMfr & " " & CompMdl & ")")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set wshShell = CreateObject("WScript.Shell")
Set objShell = WScript.CreateObject("WScript.Shell")
Set strWinDir = FSO.GetSpecialFolder(0)
Set strSys32 = FSO.GetSpecialFolder(1)
Set strTempDir = FSO.GetSpecialFolder(2)
strLogsDir = "\\fileserver\shared\logs\"
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const OverwriteExisting = False
If FSO.FileExists(strLogsDir & CompNam & ".TXT") Then
WScript.Quit
Else
If FSO.FileExists(strLogsDir & CompNam & "_CHKDSK.LOG") Then
WScript.Quit
Else
If FSO.FileExists(strLogsDir & CompNam & "_DEFRAG.LOG") Then
WScript.Quit
Else
strCHKDSKStarted = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
d=(" CHKDSK Started: " & strCHKDSKStarted)
If FSO.FileExists(strSys32 & "\chkdsk.exe") Then
strCHKDSKReturn = objShell.Run("%COMSPEC% /c chkdsk.exe C: > " & chr(34) & strLogsDir & CompNam & "_CHKDSK.LOG" & chr(34), 0, True)
End If
If FSO.FileExists(strLogsDir & CompNam & "_CHKDSK.LOG") Then
Set ChkDskLog = FSO.OpenTextFile(strLogsDir & CompNam & "_CHKDSK.LOG", ForReading, True)
Do While ChkDskLog.AtEndOfStream <> True
Curline = ChkDskLog.ReadLine
If InStr(Curline, "KB in bad sectors.") Then
Curline = Trim(Curline)
strKBpos = InStr(1, Curline, "KB")-2
strBadKB = Left(Curline, strKBpos)
strBadKB = Trim(strBadKB)
If strBadKB > 0 Then
ChkDskFail = "Failed"
e=(" " & strBadKB & "KB Of Bad Sectors Found In Used Space")
f=(" Drive has Failed Integrity Check")
Else
ChkDskFail = "Passed"
e=(" " & strBadKB & "KB Of Bad Sectors Found In Used Space")
f=(" Drive has Passed Integrity Check")
End If
End If
Loop
If strBadKB = "" Then
ChkDskFail = "Failed"
e=(" Check Disk Log Existed But Was Incomplete: " & Date & " # " & Time)
f=(" Drive has Failed Integrity Check")
End If
Else
ChkDskFail = "Passed"
e=(" No Bad Sectors Found in Used Space")
f=(" Drive has Passed Integrity Check")
End If
ChkDskLog.Close
strCHKDSKFinished = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
g=(" CHKDSK Finished: " & strCHKDSKFinished)
strDEFRAGStarted = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
h=(" DEFRAG Started: " & strDEFRAGStarted)
If FSO.FileExists(strSys32 & "\defrag.exe") Then
strDEFRAGReturn = objShell.Run("%COMSPEC% /c defrag.exe C: -a -v > " & chr(34) & strLogsDir & CompNam & "_DEFRAG.LOG" & chr(34), 0, True)
End If
If FSO.FileExists(strLogsDir & CompNam & "_DEFRAG.LOG") Then
Set DefragLog = FSO.OpenTextFile(strLogsDir & CompNam & "_DEFRAG.LOG", ForReading, True)
Do While DefragLog.AtEndOfStream <> True
CurLine = DefragLog.ReadLine
If InStr(CurLine, "Total fragmentation") Then
FragPosition = InStr(1,CurLine," %",1)-2
CurLine = CurLine
strFragAmount = Right(CurLine,4)
strFragAmount = Left(strFragAmount,2)
strFragAmount = Ltrim(strFragAmount)
End If
Loop
Else
DefragFail = "Failed"
i=(" Log File Could not be Located. Please try Again.")
j=(" Drive has Passed Defragmentation Check")
End If
If strFragAmount = "" Then
DefragFail = "Failed"
i=(" An Unknown Error has Occured. Please try Again.")
j=(" Run 'DEFRAG -v' from this machine manually.")
Else
If strFragAmount < 30 Then
DefragFail = "Passed"
i=(" Drive is " & strFragAmount & "% Fragmented")
j=(" Drive has Passed Defragmentation Check")
End If
If strFragAmount >= 30 Then
DefragFail = "Failed"
i=(" Drive is " & strFragAmount & "% Fragmented")
j=(" Drive has Failed Defragmentation Check")
End If
End If
DefragLog.Close
strDEFRAGFinished = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
k=(" DEFRAG Finished: " & strDEFRAGFinished)
strDrivePreCheckFinished = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
l=(" Script finished on " & strDRIVEPreCheckFinished)
m=("===================================================================================")
Set TXTLog = FSO.CreateTextFile(strLogsDir & CompNam & ".TXT", True)
TXTLog.WriteLine(strDrivePreCheckStarted & "," & mClient & "," & CompNam & "," & CompMfr & "," & CompMdl & "," & strCHKDSKStarted & "," & strBadKB & "KB" & "," & ChkDskFail & "," & strCHKDSKFinished & "," & strDEFRAGStarted & "," & strFragAmount & "%" & "," & DefragFail & "," & strDEFRAGFinished & "," & strDrivePreCheckFinished)
TXTLog.Close
If FSO.FileExists(strLogsDir & "_FDE.CSV") Then
Set CSVLog = FSO.OpenTextFile(strLogsDir & "_FDE.CSV", ForAppending, True)
CSVLog.WriteLine(strDrivePreCheckStarted & "," & mClient & "," & CompNam & "," & CompMfr & "," & CompMdl & "," & strCHKDSKStarted & "," & strBadKB & "KB" & "," & ChkDskFail & "," & strCHKDSKFinished & "," & strDEFRAGStarted & "," & strFragAmount & "%" & "," & DefragFail & "," & strDEFRAGFinished & "," & strDrivePreCheckFinished)
Else
Set CSVLog = FSO.CreateTextFile(strLogsDir & "_FDE.CSV", True)
CSVLog.WriteLine("Pre-Check Started,Management Client,Asset Tag,Computer Manufacturer,Computer Model,CHKDSK Started,CHKDSK Bad Sectors,CHKDSK Results,CHKDSK Finished,DEFRAG Started,DEFRAG Amount,DEFRAG Results,DEFRAG Finished,Pre-Check Finished")
CSVLog.WriteLine(strDrivePreCheckStarted & "," & mClient & "," & CompNam & "," & CompMfr & "," & CompMdl & "," & strCHKDSKStarted & "," & strBadKB & "KB" & "," & ChkDskFail & "," & strCHKDSKFinished & "," & strDEFRAGStarted & "," & strFragAmount & "%" & "," & DefragFail & "," & strDEFRAGFinished & "," & strDrivePreCheckFinished)
End If
CSVLog.Close
If FSO.FileExists(strLogsDir & "_FDE.LOG") Then
Set InstallLog = FSO.OpenTextFile(strLogsDir & "_FDE.LOG", ForAppending, True)
InstallLog.WriteLine(b)
InstallLog.WriteLine(c)
InstallLog.WriteLine(d)
InstallLog.WriteLine(e)
InstallLog.WriteLine(f)
InstallLog.WriteLine(g)
InstallLog.WriteLine(h)
InstallLog.WriteLine(i)
InstallLog.WriteLine(j)
InstallLog.WriteLine(k)
InstallLog.WriteLine(l)
InstallLog.WriteLine(m)
Else
Set InstallLog = FSO.CreateTextFile(strLogsDir & "_FDE.LOG", True)
InstallLog.WriteLine(a)
InstallLog.WriteLine(b)
InstallLog.WriteLine(c)
InstallLog.WriteLine(d)
InstallLog.WriteLine(e)
InstallLog.WriteLine(f)
InstallLog.WriteLine(g)
InstallLog.WriteLine(h)
InstallLog.WriteLine(i)
InstallLog.WriteLine(j)
InstallLog.WriteLine(k)
InstallLog.WriteLine(l)
InstallLog.WriteLine(m)
End If
InstallLog.Close
FSO.DeleteFile(strLogsDir & CompNam & "_CHKDSK.LOG")
FSO.DeleteFile(strLogsDir & CompNam & "_DEFRAG.LOG")
End If
End If
End If
Function AEZiR(plngValue)
Dim pstrValue
Dim plngChars
Dim i
pstrValue = CStr(plngValue)
plngChars = Len(pstrValue)
If plngChars < 2 Then
For i = 1 to plngChars Step -1
pstrValue = "0" & pstrValue
Next
End If
AEZiR = pstrValue
End Function
What am I missing? Is this task even possible with VBScript? Thank you in advance.
As neither VBScript, nor the FileSystemObject provide locking, someone/thing else has to do it:
a [scripting] language with proper file locks
a data store (DBMS) that allows simultaneous access
a programmer who uses a semaphore (e.g. a renamed file) to control the file access
In my opinion, the third option is the worst, because
the programmer has to do all the work and to take all
the risks/responsibilities. Using a database would solve
the problem of access control out of the box; using a
suitable language would allow a standard/non-hacking
solution.
But if you like to live in interesting times - that's
the code structure I would try to get away with:
While it make sense to continue (# of tries, timeout, successfully written)
rename FileIsFree.log to FileIsLocked.log
If success
open FileIsLocked.log
write to FileIsLocked.log
close FileIsLocked.log
rename FileIsLocked.log to FileIsFree.log
break/exit
End If
End While
If Not successfully written
Panic
End If
ADDED:
Some food for thought:
discussion
code
I hope you come to the conclusion, that using a DBMS is the better idea.
'Declare long
Dim lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout,
lng_receiveTimeout As Long
'Declare integer
Dim int_serverCredentials As Integer
'Declare variants
Dim var_submitObject As Variant
'Set values
int_serverCredentials = 0
lng_resolveTimeout = 120000 'miliseconds = 2 minutes
lng_connectTimeout = 1200000
lng_sendTimeout = 1200000
lng_receiveTimeout = 1200000
'Create HTTP object
Set var_submitObject = CreateObject("WinHTTP.WinHTTPRequest.5.1")
Call var_submitObject.SetTimeouts(lng_resolveTimeout,
lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout)
'Standards for this post
%REM
Content-Type: multipart/form-data; boundary={boundary}
{boundary}
Content-Disposition: form-data; name="data"; filename="{filename}"
Content-Type: text/plain
{contents}
{boundary}--
%END REM
'Set post parameters
Call var_submitObject.open("POST", str_url, False)
Call var_submitObject.setRequestHeader("Accept", "application/xml")
Call var_submitObject.setRequestHeader("Authorization", "Basic " & str_auth)
Call var_submitObject.setRequestHeader("Content-Type", "multipart/form-data; boundary=b1")
str_boundary = |--b1| & Chr(13) &_
|Content-Disposition: form-data; name="data"; filename="name.txt"| & Chr(13) &_
|Content-Type: text/plain| & Chr(13) &_
str_fileContent & |b1--|
'Send the HTTP request
Call var_submitObject.Send(str_boundary)
'Wait for the answer and set object as returned value for further validation
Call var_submitObject.WaitForResponse
Set submitHTTP = var_submitObject
'Clear memory
Set var_submitObject = Nothing
Questions:
How to specify the "boundary" and send the file content correctly as a TXT file upload?
How to specify the line break for this boundary content?
Re the EOL question, you specify Chr(13) but that's not a complete line-feed in Windows (I assume you're using Windows based on the winhttp tag you also mention). An EOL entity in Windows is CR + LF where a carriage return is Chr(13) and a line-feed is Chr(10).
With regards text, you specify that in your content-type.