Send \r\n in vb6 for http response - html

I am attempting to write a websocket server in VB6 and have now figured out i am not sending \r\n in the response, how do i do that in VB6? vbNewLine and vbCr & vbLf does not work.
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim sData As String
Dim guid
guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
Winsock1.GetData sData
request.Text = sData
Dim aintCount()
Dim pos As Integer
Dim entry() As String
Dim entry2() As String
entry = Split(sData, vbCrLf, , vbTextCompare)
pos = 0
Do While pos < UBound(entry)
If Trim$(entry(pos)) <> "" Then
'Text3.Text = entry(pos)
entry2 = Split(entry(pos), ":", , vbTextCompare)
If entry2(0) = "Sec-WebSocket-Key" Then
Text3.Text = Trim(entry2(1) & guid)
End If
End If
pos = pos + 1
Loop
Dim Packet() As Byte
'Dim response As Byte() = System.Text.Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" & Environment.NewLine & "Connection: Upgrade" & Environment.NewLine & "Upgrade: websocket" & Environment.NewLine & "Sec-WebSocket-Accept: " & Convert.ToBase64String(System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(New Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups(1).Value.Trim() & "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))) & Environment.NewLine & Environment.NewLine)
crypt.EncodingMode = "base64"
crypt.HashAlgorithm = "sha1"
'Text1.Text = crypt.HashBytesENC(Bytes)
Bytes = StrConv(Trim(entry2(1) & "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"), vbFromUnicode)
Text1.Text = crypt.HashBytesENC(Bytes)
'"HTTP/1.1 101 Switching Protocols" & Environment.NewLine & "Connection: Upgrade" & Environment.NewLine & "Upgrade: websocket" & Environment.NewLine & "Sec-WebSocket-Accept: "
Packet = "HTTP/1.1 101 Switching Protocols" & Crlf & "Connection: Upgrade" & Crlf & "Upgrade: WebSocket" & Crlf & "Sec-WebSocket-Accept: " & crypt.HashBytesENC(StrConv(Trim(entry2(1) & "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"), vbFromUnicode)) & vbCr & vbLf
'Packet = Packet & "Upgrade: WebSocket" & vbCr & vbNewLine
'Packet = Packet & "Connection: Upgrade" & vbCr & vbNewLine
'Packet = Packet & "Sec-WebSocket-Accept: " & crypt.HashBytesENC(Bytes) & vbCr & vbNewLine
'Data = Empty
response.Text = Packet
Winsock1.SendData Packet
End Sub

I've tried to use the minimum code from the OP to provide an example. I don't know what the crypt function returns. It is very possible you'll want to include that inside the StrConv function as well. If so that will make it easier as you will not have to encrypt and concatenate the string in pieces. You will probably be able to look as response.Text to determine if you need to do the StrConv on the individual pieces or if you can do it on the whole string.
...
Dim Packet() As Byte
crypt.EncodingMode = "base64"
crypt.HashAlgorithm = "sha1"
Bytes = StrConv(Trim(entry2(1) & "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"), vbFromUnicode)
Text1.Text = crypt.HashBytesENC(Bytes)
'Either
Packet = StrConv("HTTP/1.1 101 Switching Protocols" & vbCrLf & "Connection: Upgrade" & vbCrLf & "Upgrade: WebSocket" & vbCrLf & "Sec-WebSocket-Accept: ", vbFromUnicode) & crypt.HashBytesENC(StrConv(Trim(entry2(1) & "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"), vbFromUnicode)) & StrConv(vbCrLf, vbFromUnicode)
'Or
Packet = StrConv("HTTP/1.1 101 Switching Protocols" & vbCrLf & "Connection: Upgrade" & vbCrLf & "Upgrade: WebSocket" & vbCrLf & "Sec-WebSocket-Accept: " & crypt.HashBytesENC(StrConv(Trim(entry2(1) & "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"), vbFromUnicode)) & vbCrLf, vbFromUnicode)
response.Text = StrConv(Packet, vbUnicode)
Winsock1.SendData Packet
...

Related

Deserialize a JSON String where there are no fixed KEY using vb

I have extracted some data from a JSON Stream with one element being an array. The result of this is
"{" & vbCrLf & " ""2019-08-22"": 128.75," & vbCrLf & " ""2019-08-23"": 151.47," & vbCrLf & " ""2019-08-24"": 151.47" & vbCrLf & "}"
I am then trying to separate the 3 values and place them into a database using VB.
Tried parse, deserialize but going round in circles.
Dim uObject = Newtonsoft.Json.Linq.JObject.Parse("{" & vbCrLf & " ""2019-08-22"": 128.75," & vbCrLf & " ""2019-08-23"": 151.47," & vbCrLf & " ""2019-08-24"": 151.47" & vbCrLf & "}")
DEBUG.PRINT(uObject(1, 1)) - This fails
Trying to get the following output
Key1: 2019-08-22 Value1: 128.75
Key2: 2019-08-23 Value1: 151.47
Key3: 2019-08-24 Value1: 151.47
I did a quick test:
Dim JSON_Obj As JObject = JObject.Parse("{" & vbCrLf & " ""2019-08-22"": 128.75," & vbCrLf & " ""2019-08-23"": 151.47," & vbCrLf & " ""2019-08-24"": 151.47" & vbCrLf & "}")
For Each item In JSON_Obj
Debug.Print(String.Format("Key: {0} Value: {1}", item.key, item.value))
Next
'>Key: 2019-08-22 Value: 128.75
'>Key: 2019-08-23 Value: 151.47
'>Key: 2019-08-24 Value: 151.47
If you can't get it by key name, simply get them with array index or something, like JSON_Obj1 = JSON_Obj.Children.ToArray()(0)
With great help from CruelD; my final working code is
Dim JSON_Obj As Newtonsoft.Json.Linq.JObject = Newtonsoft.Json.Linq.JObject.Parse("{" & vbCrLf & " ""2019-08-22"": 128.75," & vbCrLf & " ""2019-08-23"": 151.47," & vbCrLf & " ""2019-08-24"": 151.47" & vbCrLf & "}")
Dim JSON_Data As List(Of JToken) = JSON_Obj.Children().ToList
For Each uItem As JProperty In JSON_Data
Debug.Print(uItem.Name.ToString & " - " & uItem.Value.ToString)
Next
This works a treat.

fixing cell padding via html in a access database

I currently have a code in a database that sends an email with a table
The table currently is not formatted it correctly and Im unable to apply cell padding. Any ideas?
enter image description here
Here is the code accompanying it
Function exporthtml()
Dim strline, strHTML, strMsg
Dim Cnt As String
Dim strFilt As String
Dim ACname As String
Dim filt As String
Dim strCC As String
Cnt = DCount("[PATS Action ID]", "tblPAT", "Bureau='" & Form_frmMainPATS.cboBur.Value & "'")
ACname = DLookup("FIRSTNAME", "qryAC", "Bureau='" & Form_frmMainPATS.txtFull.Value & "'")
strFilt = DLookup("WORKEMAIL", "qryAC", "Bureau='" & Form_frmMainPATS.txtFull.Value & "'")
Dim OL As Outlook.Application
Set OL = New Outlook.Application
Set MyItem = Outlook.Application.CreateItem(olMailItem)
Report_rptCurrentPATS.Filter = "Bureau='" & Form_frmMainPATS.cboBur.Value & "'"
Report_rptCurrentPATS.FilterOn = True
DoCmd.OutputTo acOutputReport, "rptCurrentPATS", acFormatHTML, "R:\Epi- Admin\Administrative Collaboration\Admin Review Meetings\Weekly Administrative Reports\Working Documents\Bureau Status Report Updates\TEST.html"
Open "R:\Epi-Admin\Administrative Collaboration\Admin Review Meetings\Weekly Administrative Reports\Working Documents\Bureau Status Report Updates\TEST.html" For Input As 1
Do While Not EOF(1)
Input #1, strline
strHTML = strHTML & strline
Loop
Close 1
If Left(OL.Version, 2) = "10" Then
MyItem.BodyFormat = olFormatHTML
End If
MyItem.To = strFilt
MyItem.Subject = "Updated PATS Status Report as of " & Date - 1
MyItem.HTMLBody = "<BODY bgcolor='#E6E6FA'>" & "<img src='R:\Epi-Admin\Fiscal Management and Reporting Unit\Database\PS Database\logo.png' ALT='Banner'" & "<p>" & "<FONT color = '#000000'>" & "Dear " & ACname & "," & "<br/>" & "<br/>" & Form_frmMainPATS.cboBur.Value & " currently has " & Cnt & " pending personnel actions." & "</p>" & "<p>" & "Please see the report below:" & "<br/>" & "<BODY>" & "<table border= '1'>" & "<bgcolor=#ffffff; cellspacing=10; table-layout: fixed; >" & "<table header= '1' bgcolor='#fffff'>" & strHTML & "</table>" & "</br>" & "<br/>" & "</br>" & "</br>" & "<p> If you have any questions, please contact your desingated Personnel Coordinator"
MyItem.Display
End Function
Any help would be appreciated
Expanding on my comment from above, you can try to see if something like this works or gets you in the right direction (not tested):
Dim strCell() as string
Do While Not EOF(1)
Input #1, strline
strCell() = Split(strline, vbTab) 'Replace vbTab with deliminator if needed
dim i as integer
for i = 0 to UBound(strCell)
strline = "<td>" & strCell(i) & "</td>"
next
strHTML = strHTML & "<tr>" & strline & "</tr>"
Loop
Close 1

how to use Unordered HTML List in excel vba code?

I have been trying to send a email via excel and use html in the message body but it seems excel does not reconize de <\li>. I have the microsoft html Oject library added.
Sub send()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "dupma4"
'.CC = "Patrick.Blouin#mern.gouv.qc.ca;Veronic.Cinq-Mars#mern.gouv.qc.ca"
.BCC = ""
.Subject = "Ajouts d'adresse | [" & mun & " " & ville & "] | [" & Format(Now(), "yyyy-MM-dd") & "]"
.HTMLBody = "Bonjour," & "<br>" & "<br>" _
& "<ul>" & "<li> & message1 & "</li>" & "<li>" & message2 _
& "</li>" & "</ul>"
'.Send
End With
End Sub
You're missing an ending quotation mark (") for your first li. So it should be as follows...
.HTMLBody = "Bonjour," & "<br>" & "<br>" _
& "<ul>" & "<li>" & message1 & "</li>" & "<li>" & message2 _
& "</li>" & "</ul>"

run msgbox in background VBscript

Two part question:
I am trying to write a VBscript where a loop runs, but there is a message box that the user can use to abort the sequence at anytime. I know that if you have a sequence with msgbox in it, the script will stop executing until an answer has been received, but can I run it as a subscript, so it doesn't interfere with the main script?
when I use the following script, I never see the msgbox
function test()
msgbox ("test")
end function
wscript.sleep 1000
msgbox "done
i was under the impression that function let you get inputs. Can this even be done with pure vbscript?
Not what I was going for but this is a work around I found. It makes a temporary msgbox that closes itself after a time. Gives the user a 5 second window to abort the sequence each loop.
set infobox = createobject("Wscript.shell")
do while E<N+1
E=E+1
if InfoBox.Popup ("Click cancel to stop sequence", _
5, "Abort Sequence?", 1) = 2 then
E=N+1
end if
loop
The Trick here is to have the first script create and start a second script. This second script will just run in the background and can then wait and kill the initial script Process... This can easily be done with a Function and can be called at the start of your script. When your main script ends, it simply kills the previously created second script. Note: the second script which is created will automatically delete itself upon being run. See the below Script for a good working example:
Dim iKillPID
'Start Kill Script At Start Of Script
iKillPID = KillPID()
For X = 10 To 0 Step -1
WScript.Echo "Closing in " & X & " Seconds"
WScript.Sleep 1000
Next
'Kill The Kill Script At End Of Script
GetObject("winmgmts:root\cimv2:Win32_Process.Handle='" & iKillPID & "'").Terminate
MsgBox "This Script is Complete"
'$$$$$$$$$$
Function KillPID()
Dim strKillScriptPath, strKillCommand, KillFile, StrFileKill, iScriptPID
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
'Generates a Unique Temp File Name In The Same Directory As The Current Script
strKillScriptPath = objFSO.GetParentFolderName(WScript.ScriptFullName) & Chr(92) & Replace(objFSO.GetTempName, ".tmp", ".vbs")
'Command Line To New Kill Script
strKillCommand = "WScript.exe " & Chr(34) & strKillScriptPath & Chr(34)
'This part gets the Process ID of the Current Running Script
iScriptPID = GetObject("winmgmts:root\cimv2:Win32_Process.Handle='" & _
CreateObject("WScript.Shell").Exec("CMD /C ping 127.0.0.1 -n 2 > nul").ProcessID & "'").ParentProcessID
'String With Kill File Code (Script Process ID Included)
StrFileKill = _
"Const iKillProc = " & iScriptPID & vbCrLf & _
"Dim objFSO: Set objFSO = CreateObject(" & Chr(34) & "Scripting.FileSystemObject" & Chr(34) & ")" & vbCrLf & _
"objFSO.DeleteFile WScript.ScriptFullName, True" & vbCrLf & _ '<-- Deletes itself immediately upon running
"On Error Resume Next" & vbCrLf & _
"Set objKillProc = Nothing" & vbCrLf & _
"Set objKillProc = GetObject(" & Chr(34) & "winmgmts:root\cimv2:Win32_Process.Handle='" & Chr(34) & " & iKillProc & " & Chr(34) & "'" & Chr(34) & ")" & vbCrLf & _
"If objKillProc Is Nothing Then" & vbCrLf & _
" MsgBox " & Chr(34) & "The Process Is Not Running" & Chr(34) & vbCrLf & _
" WScript.Quit" & vbCrLf & _
"End If" & vbCrLf & _
"MsgBox " & Chr(34) & "Click OK To Kill The Script Process" & Chr(34) & vbCrLf & _
"Call KillProcess(iKillProc)" & vbCrLf & _
"WScript.Quit" & vbCrLf & _
"Sub KillProcess(iProcID)" & vbCrLf & _
"Dim objKillProc, strParentProc" & vbCrLf & _
"On Error Resume Next" & vbCrLf & _
"Set objKillProc = Nothing" & vbCrLf & _
"Set objKillProc = GetObject(" & Chr(34) & "winmgmts:root\cimv2:Win32_Process.Handle='" & Chr(34) & " & iProcID & " & Chr(34) & "'" & Chr(34) & ")" & vbCrLf & _
"If Err = 0 And Not objKillProc Is Nothing Then" & vbCrLf & _
" If StrComp(objKillProc.Name, " & Chr(34) & "cmd.exe" & Chr(34) & ", 1) = 0 Or _" & vbCrLf & _
" StrComp(objKillProc.Name, " & Chr(34) & "cscript.exe" & Chr(34) & ", 1) = 0 Or _" & vbCrLf & _
" StrComp(objKillProc.Name, " & Chr(34) & "wscript.exe" & Chr(34) & ", 1) = 0 Then" & vbCrLf & _
" strParentProc = objKillProc.ParentProcessID" & vbCrLf & _
" objKillProc.Terminate()" & vbCrLf & _
" Call KillProcess(strParentProc)" & vbCrLf & _
" End If" & vbCrLf & _
"End If" & vbCrLf & _
"Set strParentProc = Nothing" & vbCrLf & _
"Err.Clear" & vbCrLf & _
"End Sub"
'Write the Code To File
Set KillFile = objFSO.CreateTextFile(strKillScriptPath, True)
KillFile.WriteLine StrFileKill
KillFile.Close
Set KillFile = Nothing
WScript.Sleep 250
'Execute The Script and Return the Script Process ID So You Can Kill It When The Script Ends
KillPID = CreateObject("WScript.Shell").Exec(strKillCommand).ProcessID
End Function
'$$$$$$$$$$
Also, If you're using CScript as the Scripting Engine for your VBS, I believe you can stop the script by pressing CTRL + C in the Command Prompt Window.
Now if your super motivated you can create an HTA that does about the same thing, but present a UserForm or Custom Internet Explorer Window to click and it can also loop through and check if the process is still running and close itself when the script is finished and the process is no longer running. You can add pretty colors and everything too!

What's causing my UPDATE statement not to work?

Good evening all,
I'm using the following as an attempt to update records in my MySQL database, but the records aren't being updated and I'm not catching any exceptions either. Your help would be kindly appreciated:
dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=trojan;Password=horse;Database=accounting")
Try
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
Else
Try
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("UPDATE customer " & _
"SET accountNumber= '" & TextBoxAccount.Text & "', nameLAST='" & TextBoxLastName.Text & "', nameFIRST='" & TextBoxFirstName.Text & "'" & _
"nameSALUTATION='" & ComboBoxSalutation.SelectedItem & "', nameCOMPANY='" & TextBoxCompanyName.Text & "', addressSTREET='" & TextBoxAddress1.Text & "'" & _
"addressSTREET1='" & TextBoxAddress2.Text & "', addressCITY='" & TextBoxCity.Text & "', addressSTATE='" & ComboBoxState.SelectedItem & "'" & _
"addressZIPCODE='" & MaskedTextBoxZip.Text & "', phone='" & MaskedTextBoxPhone.Text & "', fax='" & MaskedTextBoxFax.Text & "', email='" & TextBoxEmail.Text & "'" & _
"WHERE accountNumber='" & TextBoxAccount.Text & "';", dbConn)
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
MessageBox.Show("Customer account SUCCESSFULLY updated!")
Call lockForm()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Call lockForm()
dbConn.Close()
Use MySQLCommand instead of MySQLDataAdapter. You are defeating the purpose of using ADONet because still your code is vulnerable with sql injection. Make it parameterized. Below is a modified code from your code. It uses Using-End Using for proper handling of object disposal.
Dim ConnectionString As String ="Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=trojan;Password=horse;Database=accounting"
Dim iQuery As String = "UPDATE customer " & _
"SET accountNumber = #accountNumber, nameLAST = #nameLAST, nameFIRST = #nameFIRST, " & _
" nameSALUTATION = #nameSALUTATION, nameCOMPANY = #nameCOMPANY, addressSTREET = #addressSTREET, " & _
" addressSTREET1 = #addressSTREET1, addressCITY = #addressCITY, addressSTATE = #addressSTATE, " & _
" addressZIPCODE = #addressZIPCODE, phone = #phone, fax = #fax, email = #email " & _
"WHERE accountNumber = #accountNumber"
Using dbConn As New MySqlConnection(ConnectionString)
Using dbComm As New MySQLCommand()
With dbComm
.Connection = dbConn
.CommandType = CommandType.Text
.CommandText = iQuery
.Parameters.AddWithValue("#accountNumber", TextBoxAccount.Text )
.Parameters.AddWithValue("#nameLAST", TextBoxLastName.Text)
.Parameters.AddWithValue("#nameFIRST", TextBoxFirstName.Text)
.Parameters.AddWithValue("#nameSALUTATION", ComboBoxSalutation.SelectedItem)
.Parameters.AddWithValue("#nameCOMPANY", TextBoxCompanyName.Text)
.Parameters.AddWithValue("#addressSTREET", TextBoxAddress1.Text)
.Parameters.AddWithValue("#addressSTREET1", TextBoxAddress2.Text)
.Parameters.AddWithValue("#addressCITY", TextBoxCity.Text)
.Parameters.AddWithValue("#addressSTATE", ComboBoxState.SelectedItem)
.Parameters.AddWithValue("#addressZIPCODE", MaskedTextBoxZip.Text)
.Parameters.AddWithValue("#phone", MaskedTextBoxPhone.Text)
.Parameters.AddWithValue("#fax", MaskedTextBoxFax.Text)
.Parameters.AddWithValue("#email", TextBoxEmail.Text)
End With
Try
dbConn.Open
dbComm.ExecuteNonQuery()
MessageBox.Show("Customer account SUCCESSFULLY updated!")
Call lockForm()
Catch( ex as MySQLException)
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
Finally
dbConn.Close()
End Try
End Using
End Using
In this case, I would use ExecuteNonQuery as you can't use a MySQLDataAdapter the way you are trying to use it. Also please use paramters as what you are doing opens you up to SQL injection attacks. And finally you don't need to update accountNumber because you are using that to find the row which you want to update!