Here is the code I am using:
Dim httpReq As New WinHttp.WinHttpRequest
Dim strLineOut As String
Dim strReturn As String
Dim strStatus As String
lblResponse1.Caption = ""
DoEvents
strLineOut = "<form name=""form1"" method=""post"" enctype=""multipart/form-data"">" & vbCrLf
strLineOut = strLineOut & " <input name=""hdntype"" type=""hidden"" id=""hnd1"" value=""1"">" & vbCrLf
strLineOut = strLineOut & " <input name=""hnd1"" type=""hidden"" id=""hnd1"" value=""Value1"">" & vbCrLf
strLineOut = strLineOut & " <input name=""hdn2"" type=""hidden"" id=""hdn2"" value=""Value2"">" & vbCrLf
strLineOut = strLineOut & " <input type=""submit"" name=""Submit"" value=""Submit"">" & vbCrLf
strLineOut = strLineOut & "</form>" & vbCrLf
httpReq.Open "POST", "http://www.XXXX.com/XMLProjects/vb6test/form_post.asp", False
httpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'text/xml
'application/x-www-form-urlencoded
'httpReq.StatusText
'httpReq.Status
'httpReq.SetRequestHeader "Content-Length", Len(strLineOut)
httpReq.Send (strLineOut)
strStatus = httpReq.StatusText
strReturn = httpReq.ResponseText
Debug.Print strReturn & vbCrLf & strStatus
lblResponse1.Caption = strReturn & vbCrLf & strStatus
Set httpReq = Nothing
The asp that catches the form cannot seem to recognize the form. It sees a form with one item.
The catch code in the asp is:
Response.Write Request.Form("hdntype")
Response.Write "the form object is " & Request.Form.Item(1) & vbCrLf
The response from the asp is:
the form object is "form1"method="post"enctype="multipart/form-data">
<inputname="hdntype"type="hidden"id="hnd1"value="1">
<inputname="hnd1"type="hidden"id="hnd1"value="Nick">
<inputname="hdn2"type="hidden"id="hdn2"value="Arnone">
<inputtype="submit"name="Submit"value="Submit"></form>
It does not see the item hdntype, or any other item within the form. It sees 1 item, the entire form.
If I do a Request.TotalBytes, I can see everythinhg in the asp.
If I add a querystring objects, I can see each object.
I cannot see form objects.
In VB6, if you send the data like this:
strIDJob = "34"
strAuthString = "supertest"
DataToPost = ""
DataToPost = DataToPost & "IDJob=" & strIDJob & "&"
DataToPost = DataToPost & "AUTH=" & strAuthString & "&"
(im sending it to an ASP page, using the CreateObject("Msxml2.XMLHTTP.6.0") component)
(sending with POST with only this header included: "application/x-www-form-urlencoded")
Then, you can retrieve each item using the code bellow (in ASP), one by one:
IDJob = Request.Form.Item(1) 'here is the core point of this post. This is the line that matters
AUTH = Request.Form.Item(2) 'here is the core point of this post. This is the line that matters
response.write "IDJob = " & IDJob & "<BR>"
response.write "AUTH = " & AUTH & "<BR>"
Response.End
this code in asp produces the following return/output:
IDJob = 34AUTH = supertest
Related
I want to send Image or pdf document in post request, the URL is working fine, but in visual basic I used the below code to send the document using url but It gives me failure response server error .
I have checked URL, it has no issue, but when I tried to implement in vb, in response I get the 500 server error
Dim strFile As String
Dim uploadDocUrl As String
Dim baBuffer() As Byte
Dim sPostData As String
Dim strFile As String
Dim strFileName As String
strFile = "C://Users/Avinashi/Desktop/1.pdf"
uploadDocUrl = "http://api.tally.messaging.bizbrain.in/api/v1/uploadFile"
strFileName = "1.pdf"
nFile = FreeFile
Open strFile For Binary Access Read As nFile
If LOF(nFile) > 0 Then
ReDim baBuffer(0 To LOF(nFile) - 1) As Byte
Get nFile, , baBuffer
sPostData = StrConv(baBuffer, vbUnicode)
End If
Close nFile
sPostData = "--" & STR_BOUNDARY & vbCrLf & _
"Content-Disposition: form-data;name=""1.pdf""; filename=""" & Mid$(strFile, InStrRev(strFile, "\") + 1) & """" & vbCrLf & _
"Content-Type:multipart/form-data" & vbCrLf & vbCrLf & _
sPostData & vbCrLf & _
"--" & STR_BOUNDARY & "--"
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", uploadDocUrl, bAsync
.SetRequestHeader "Content-Type", "multipart/form-data"
.SetRequestHeader "token", "78bea912b4a5c497b85926bb471fab04"
.Send pvToByteArray(sPostData)
MsgBox (.responseText)
End With
Private Function pvToByteArray(sText As String) As Byte()
pvToByteArray = StrConv(sText, vbUnicode)
End Function
The text file exists, the web hook exists, etc. I am using a discord web hook. The response is
{"code": 50006, "message": "Cannot send an empty message"}
I have concluded that the way I formatted the request is incorrect. Probably the Set oHTTP = CreateObject("Microsoft.XMLHTTP") part.
How do I reformat the request correctly? Is it even possible to send a web hook using a .vbs file?
Dim time
user = CreateObject("WScript.Network").UserName
time = (FormatDateTime(Now, 2)& " "& FormatDateTime(Now, 4))
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Users\"& user& "\Desktop\state.txt",1)
state = objFileToRead.ReadAll()
objFileToRead.Close
Set objFileToRead = Nothing
url = "" 'my discord webhook
avatar = "https://discordapp.com/assets/dd4dbc0016779df1378e7812eabaa04d.png"
req1 = ("{ \" & Chr(34) & "username\" & Chr(34) & ":\" & Chr(34) & _
"Manage bot\" & Chr(34) & ", \" & Chr(34) & "avatar_url\" & Chr(34) & _
":\" & Chr(34) & avatar)
req2 = Chr(34) & ", \" & Chr(34) & "content\" & Chr(34) & ":\" & Chr(34) & _
time & " " & user & Chr(13) + Chr(10) & state & Chr(34) & " }"
Set oHTTP = CreateObject("Microsoft.XMLHTTP")
oHTTP.Open "POST", url, False
oHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oHTTP.SetRequestHeader "Content-Length", Len(req1+req2)
oHTTP.Send req1+req2
HTTPPost = oHTTP.ResponseText
MsgBox oHTTP.ResponseText
I have some code that copies cells from Excel, pastes them as a picture, saves the picture, and then sends an email with that picture in it's body. The problem is that because the image gets saved on my hard drive, when it gets sent out to the recipients cannot see the image. Is there a way of getting around this?
The code is as follows:
Sub Email()
Dim objOutlook As Object
Dim objMail As Object
Dim TempFilePath As String
Dim Location As String
Dim RecipientNumber As String
Dim rng As Range
Dim PrimaryRecipients As String
Dim SecondaryRecipients As String
Dim To_Name As String
Worksheets("Contacts").Activate
Range("A2").Select
While ActiveCell <> "" And ActiveCell <> "0"
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
ActiveCell.Offset(1, 0).Select
RecipientNumber = ActiveCell.Value
To_Name = ActiveCell.Offset(0, 4).Value
If To_Name = "" Or To_Name = "0" Then
To_Name = ActiveCell.Offset(0, 7).Value
Worksheets("Output 2").Activate
Range("C2").Value = RecipientNumber
Dim objChart As Chart
Call ActiveSheet.Range("A1:M28").CopyPicture(xlScreen, xlPicture)
Sheets.Add.Name = "Without Formatting"
Worksheets("Without Formatting").Shapes.AddChart
Worksheets("Without Formatting").Activate
ActiveSheet.Shapes.Item(1).Select
Set objChart = ActiveChart
objChart.Paste
With ActiveChart.Parent
.Height = 300 ' resize
.Width = 750 ' resize
.Top = 100 ' reposition
.Left = 100 ' reposition
End With
Dim DayForLocation As String
Dim MonthForLocation As String
Dim YearForLocation As String
Dim DateForLocation As String
DayForLocation = Day(Now)
MonthForLocation = Month(Now)
YearForLocation = Year(Now)
DateForLocation = YearForLocation & MonthForLocation & DayForLocation
Dim FileLocation As String
FileLocation = "C:\Users\asfadsf\Documents\" & DateForLocation
If Dir("C:\Users\asfadsf\Documents\" & DateForLocation) <> "" Then
MkDir ("C:\Users\asfadsf\Documents\" & DateForLocation)
End If
FileLocation = FileLocation & RecipientNumber & ".jpeg"
objChart.Export (FileLocation)
Set rng = ActiveSheet.Range("A1:M28").Rows.SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
'Keep_Format
With objMail
.To = PrimaryRecipients
.Cc = SecondaryRecipients
.Subject = "Information: " & RecipientNumber & " Updated Profiler"
Dim Greeting As String
If Time >= #12:00:00 PM# Then
Greeting = "Afternoon"
Else
Greeting = "Morning"
End If
Dim LastMonth As String
LastMonth = MonthName((Month(Date)) - 1)
Dim InsertImage As String
InsertImage = "<img src='" & FileLocation & "'>"
.HTMLBODY = "<font face=Arial><p>" & "Good " & Greeting & " " & To_Name & "," & "</p>"
.HTMLBODY = .HTMLBODY + "<p>" & "Email text." & "</p>"
.HTMLBODY = .HTMLBODY + "<p>" & "Email text." & "</p>"
.HTMLBODY = .HTMLBODY + "<p>" & "Email text." & "</p>"
' .HTMLBODY = .HTMLBODY + RangetoHTML(rng)
.HTMLBODY = .HTMLBODY + InsertImage
.HTMLBODY = .HTMLBODY + "<p>" & "Kind Regards" & "<br>"
.HTMLBODY = .HTMLBODY + "<img src='C:\Users\asfadsf\Documents\test.jpg'>"
.Send
End With
Worksheets("Contacts").Activate
Application.DisplayAlerts = False
Sheets("Without Formatting").Delete
Application.DisplayAlerts = True
Wend
Set objOutlook = Nothing
Set objMail = Nothing
Set objOutlook = Nothing
Set objMail = Nothing
End Sub
This is quite an issue, can someone please help?
Maybe these two lines I changed / added are better than the two lines of comment above to illustrate what I mean:
With objMail
.To = PrimaryRecipients
.Cc = SecondaryRecipients
.Subject = "Information: " & RecipientNumber & " Updated Profiler"
Dim Greeting As String
If Time >= #12:00:00 PM# Then
Greeting = "Afternoon"
Else
Greeting = "Morning"
End If
Dim LastMonth As String
LastMonth = MonthName((Month(Date)) - 1)
Dim InsertImage As String
InsertImage = "<img src='" & FileLocation & "'>"
.HTMLBODY = "<font face=Arial><p>" & "Good " & Greeting & " " & To_Name & "," & "</p>"
.HTMLBODY = .HTMLBODY + "<p>" & "Email text." & "</p>"
.HTMLBODY = .HTMLBODY + "<p>" & "Email text." & "</p>"
.HTMLBODY = .HTMLBODY + "<p>" & "Email text." & "</p>"
' .HTMLBODY = .HTMLBODY + RangetoHTML(rng)
.HTMLBODY = .HTMLBODY + InsertImage
.HTMLBODY = .HTMLBODY + "<p>" & "Kind Regards" & "<br>"
.Attachments.Add "C:\Users\asfadsf\Documents\test.jpg"
.HTMLBODY = .HTMLBODY + "<img src='test.jpg'>"
.Send
End With
The only thing I actually changed is this:
.Attachments.Add "C:\Users\asfadsf\Documents\test.jpg"
.HTMLBODY = .HTMLBODY + "<img src='test.jpg'>"
You'll note that you don't see test.jpg as an attachment anymore but rather directly displayed in the body of the email.
i am creating a .vbs file that should open access, and inside access a form call "Issue Details", but passing a parameter, meaning that if i have 10 issues in my "Issues" table a vbs file is created for each one and when clicked should open the right form id(would be one ID for each in the table). It is so far opening access and it is opening the form(Issue Details) but it is blank. What am i missing? Help, getting crazy here ... Check code below
Public Sub sendMRBmail(mrbid)
Dim tmprs As DAO.Recordset
Dim db As DAO.Database
Set db = CurrentDb
Set tmprs = db.OpenRecordset("select * from Issues where [ID] = " & mrbid)
If IsNull(tmprs) Then
MsgBox "Record is not yet available"
Else
DoCmd.OpenForm "Issue Details", , , "[ID] = " & mrbid
End If
Set tmprs = Nothing
End Sub
Private Sub Create_Click()
On Error GoTo Err_Command48_Click
Dim snid As Integer
snid = Me.ID
Dim filename As String
filename = "S:\Quality Control\vbs\QC" & snid & ".vbs"
Dim proc As String
proc = Chr(34) & "sendMRBmail" & Chr(34)
Dim strList As String
strList = "On Error Resume Next" & vbNewLine
strList = strList & "dim accessApp" & vbNewLine
strList = strList & "set accessApp = createObject(" & Chr(34) & "Access.Application" & Chr(34)")" & vbNewLine
strList = strList & "accessApp.OpenCurrentDataBase(" & Chr(34) & "S:\Quality Control\Quality DB\Quality Database.accdb" & Chr(34) & ")" & vbNewLine
strList = strList & "accessApp.Run " & proc & "," & Chr(34) & snid & Chr(34) & vbNewLine
strList = strList & "set accessApp = nothing" & vbNewLine
Open filename For Output As #1
Print #1, strList
Close #1
Err_Command48_Click:
If Err.Number <> 0 Then
MsgBox "Email Error #: " & Err.Number & ", " & "Description: " & Err.Description
Exit Sub
End If
End Sub
I already found the answer. I added acFormEdit at the end of my DoCmd and it worked, check below:
DoCmd.OpenForm "Issue Details", , , "[ID] = " & mrbid, acFormEdit
I'm trying to create an HTA To Do List saving locally to a text file. Every time you press submit button generates a new entry that display inside hta body and it's being saved inside the text file. I want to develop this furthermore :
delete an entry and update body/text file
modify an entry and update body/text file
put new entry on top
Any suggestions?
<html>
<head>
<HTA:APPLICATION SINGLEINSTANCE="yes" APPLICATIONNAME="To Do List">
</head>
<SCRIPT Language="VBScript">
Sub Window_OnLoad
ReadBlog
End Sub
Sub SaveData
strDel1="<"
strDel2=">"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists("C:\Test.txt") Then
Set objFile = objFSO.OpenTextFile("C:\Test.txt", 8)
strLine = strDel1 & Time & vbTab & Date & vbTab & Title.Value & vbTab & Message.Value & strDel2
objFile.WriteLine strLine
objFile.Close
Else
Set objFile = objFSO.CreateTextFile("C:\Test.txt")
strLine = strDel1 & Time & vbTab & Date & vbTab & Title.Value & vbTab & Message.Value & strDel2
objFile.WriteLine strLine
objFile.Close
End If
ReadBlog
ClearText
End Sub
Sub ReadBlog
Const ForReading = 1, ForWriting = 2
dim sampletext, objRegExp, SearchPattern, ReplacePattern, matches
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Test.txt", ForReading)
Do Until objFile.AtEndOfStream
sampletext = objFile.ReadAll
SearchPattern = "<"
SearchPattern = SearchPattern & "(.*?)([\s\S]*?)"
SearchPattern = SearchPattern & ">"
Set objRegExp = New RegExp
objRegExp.Pattern = searchpattern ' apply the search pattern
objRegExp.Global = True ' match all instances if the serach pattern
objRegExp.IgnoreCase = True ' ignore case
Set matches = objRegExp.execute(sampletext)
If matches.Count > 0 Then ' there was at least one match to the search pattern
i=0
For Each match in matches
arrEntry = Split(Split(match.Value, "<")(1), ">")(0)
arrFields = Split(arrEntry, vbTab)
strTime = arrFields(0)
strDate = arrFields(1)
strTitle = arrFields(2)
strMessage = arrFields(3)
strHTML = strHTML & "<p>" & strTime & "</p>"
strHTML = strHTML & "<p>" & strDate & "</p>"
strHTML = strHTML & "<p>" & strTitle & "</p>"
strHTML = strHTML & "<p>" & strMessage & "</p>"
strHTML = strHTML & "<input type='button' name='Delete' value='Delete' >"& i &"<p>"
i=i+1
Next
Else ' there were no matches found
MsgBox objRegExp.Pattern & "was not found in the string"
End If
Loop
DataArea.InnerHTML = strHTML
Set objRegExp = Nothing
Set objFSO = Nothing
End Sub
Sub ClearText
Title.Value = ""
Message.Value = ""
End Sub
</SCRIPT>
<body>
<input type="text" name="Title" size="101"><p>
<textarea rows="10" cols="76" type="text" name="Message" size="25"></textarea><p>
<input type="button" value="Submit" onClick="SaveData">
<p><div id="DataArea"></div></p>
</body>
</html>
Are you particularly tied to using text files? If you used a database (such as access) you could do this quite easily (you don't have to have access installed to use an access database with an HTA either). And it would open up some other possibilities.
Incidentally, I also notice you're doing this:
strHTML = strHTML & "<p>" & strTime & "</p>"
strHTML = strHTML & "<p>" & strDate & "</p>"
strHTML = strHTML & "<p>" & strTitle & "</p>"
strHTML = strHTML & "<p>" & strMessage & "</p>"
Not a big thing, but concatenating the strings like that isn't great for performance. You'd be better off writing it all to the variable at the same time, otherwise it has to keep writing the variable to memory over and over again.
If you want to read a file with HTA you can easily do it in javaScript. Since the context changes IE allws you to directly read file on the computer or the network to wich the computer is linked to. In order to do so, you need to access the File System Object (FSO)
Full Documentation on FSO
If you are still looking to access a database you need to use the ADODB.Connection. That will allow you to connect to database localy or remotely. Altought there is not much documentation on the subject we did it at my work place. With a little imagination you can figure out how to fix it.
Documentation on the ADODB.Connnect
In this documentation the example are in VB but you can write them in JS as well.