WebSocket using VB6.0 - vba

I'm using a project in VB6.0 and I need to implement WebSocket for VB6.0 but unfortunately, I could not find any resources over the internet, so please assist me on this, I've been searching Winsock to use TCP/IP socket servers, I need proper guidance on this.
I found the below code from somewhere but it seems not useful.
Private Sub Winsock1_ConnectionRequest(Index As Integer, ByVal requestID As Long)
Winsock1(Index).Close
Winsock1(Index).Accept requestID
Dim Packet As String
With Winsock1(Index)
Packet = "HTTP/1.1 101 Web Socket Protocol Handshake" & vbNewLine
Packet = Packet & "Upgrade: WebSocket" & vbNewLine
Packet = Packet & "Connection: Upgrade" & vbNewLine
Packet = Packet & "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" & vbNewLine
Data = Empty
.SendData Packet
End With
End Sub

I have developed websocket solution for vb6 but comments / varables are in Slovenian language so... fast answer:
you have to calculate key in 'Sec-WebSocket-Accept'. It changes on every connection so you cannot use fixed response...
"Sec-WebSocket-Accept: " + Key + vbCrLf + _

Related

Telnet (winsock) connection in VBA - class not registered

I have GSM gateway that use telnet for sending/recivieng SMS. I'am making a small app in my ms-access for sending sms notifications for my clients. For that I need winsock connection from my client computer -> gsm gateway. It supposed to be easy :)
I can't establish an object. I'm receiving run-time error -2147221164(80040154) - Class not registered. Error is indicated in "Set winsock = ..." line. I have added reference MS Winsock Control 6.0 (SP6) - MSWINSCK.OCX. I have a feeling this is a problem with reference, but I don't have any idea how to correct it (code below is simplified) :( .
Option Explicit
Private WithEvents Winsock1 As Winsock
Sub Start_Telnet_Session()
Dim Data As String
Dim Winsock1
Set Winsock1 = New MSWinsockLib.Winsock
Winsock1.RemoteHost = "192.168.1.1"
Winsock1.RemotePort = "23"
Winsock1.connect
Do Until Winsock1.State = 7
DoEvents
If Winsock1.State = sckError Then
Exit Sub
End If
Loop
Winsock1.SendData "user" & vbCrLf
Winsock1.SendData "pass" & vbCrLf
Dim I As Integer
I = 5
While TelnetCommands <> ""
Winsock1.SendData "TelnetCommands" & vbCrLf
Winsock1.GetData Data
Data = VBA.Replace(Data, vbLf, "")
Data = VBA.Replace(Data, vbCr, vbNewLine)
MsgBox Data
I = I + 1
Wend
Winsock1.Close
End Sub

Com Port doesn't work unless Hyperterminal Open and Closes Port First

So I am trying to connect to a piece of hardware. If I connect and disconnect with hyperterminal first. Then close the connection and the program. Everything works fine. If I don't I receive random characters back from the hardware. I use the same settings in hyperterminal as I do in the code.
baud=9600
parity=n
data=8
stop=1
Hardware flow controls "ON":
octs=on to=on dtr=on rts=hs
If I then disconnect the hardware and the serial port I will have the same problem again.
Is there anyway I can see how to comport is being configured after hyperterminal open and closes the port? I should note I am using a prolific serial to USB adapter.
Below is the code I use to open the com port.
Function OpenCom(PortNum As Integer, Baud As Long) As Long
Dim lpDCB As DCB
Dim ComTimeout As COMMTIMEOUTS
com$ = "COM" + Trim(Str(PortNum))
'open the communications port
hcomtemp& = CreateFile(com$, GENERIC_READ Or GENERIC_WRITE, 0, ByVal 0, OPEN_EXISTING, 0, ByVal 0)
'check for errors
If hcomtemp& < 0 Then
OpenCom = hcomtemp&
Exit Function
End If
r& = PurgeComm(hcomtemp&, 12) ' purge the comm RX and TX (RXCLEAR=0x08 and TXCLEAR=0x04)
' COMMAND LINE for "Hardware" flow control - mode com: baud=9600 parity=n data=8 stop=1 octs=on to=on dtr=on rts=hs
Build$ = "baud=" + Trim(str(Baud)) + " parity=N data=8 stop=1 octs=on to=on dtr=on rts=hs"
'build the data communications block
r& = BuildCommDCB(Build$, lpDCB)
'set the communications port's parameters with the DCB
r& = SetCommState(hcomtemp&, lpDCB)
ComTimeout.ReadIntervalTimeout = 100 'maximum time to wait between received bytes (milliseconds)
ComTimeout.ReadTotalTimeoutConstant = 1000 'maximum time to wait for receive data (milliseconds)
'set the timeouts
r& = SetCommTimeouts(hcomtemp&, ComTimeout)
'set the input buffer size to 4096 bytes and the output buffer size to 4096 bytes
r& = SetupComm(hcomtemp&, 4096, 4096)
'return the handle of the newly opened communications port
OpenCom = hcomtemp&
End Function
Please, try Advanced Serial Port Monitor -> Spy mode. http://www.aggsoft.com/serial-port-monitor.htm. It will show all actions that Hyperterminal does on the port. Then you can repeat these settings. It seems that the problem is related with the hardware flow control settings.
Below is the code I used to fix my problem. I only ever had to do it this way for one piece of equipment.
Function HandShakeBM5AS(ComPort As Integer) As Boolean
Dim Bm5ACom As Long
Dim x As Variant
Dim Path As String
comm$ = ComPort
Commands$ = "MODE COM" & comm$ & ": BAUD=9600 PARITY=N DATA=8 STOP=1 TO=ON XON=OFF ODSR=OFF OCTS=ON DTR=ON RTS=HS IDSR=OFF"
Call Shell("cmd.exe /S /C" & Commands$, vbNormalFocus)
'Shell (Commands$)
End Function
BuildCommDCB() fails if 'rts=hs' is included in the control string. This causes lpDCB to be not set correctly, and SetCommState is called with the wrong values.
You can set the RTS control flag in the lpDCB structure after calling BuildCommDCB. (I would include code but I'm not certain on the Basic syntax)

Uploading a file to Azure Blob Storage using VBA and MS XMLHTTP

I've been trying to upload file to Azure storage using VBA in Microsoft Access but so far without success.
I have had a good search around and have found some code which looks promising but I can't get it to work. Seems like many others have been looking for a similar solution or help with working with Azure from VBA.
This is the code;
Private Function pvPostFile(sUrl As String, sFileName As String, Optional ByVal bAsync As Boolean) As String
Const STR_BOUNDARY As String = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113"
Dim nFile As Integer
Dim baBuffer() As Byte
Dim sPostData As String
'--- read file
nFile = FreeFile
Open sFileName 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
'--- prepare body
sPostData = "--" & STR_BOUNDARY & vbCrLf & _
"Content-Disposition: form-data; name=""uploadfile""; filename=""" & Mid$(sFileName, InStrRev(sFileName, "\") + 1) & """" & vbCrLf & _
"Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _
sPostData & vbCrLf & _
"--" & STR_BOUNDARY & "--"
'--- post
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", sUrl, bAsync
.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
.Send pvToByteArray(sPostData)
If Not bAsync Then
pvPostFile = .ResponseText
End If
End With
End Sub
Private Function pvToByteArray(sText As String) As Byte()
pvToByteArray = StrConv(sText, vbFromUnicode)
End Function
(Thanks to - https://wqweto.wordpress.com/2011/07/12/vb6-using-wininet-to-post-binary-file/)
When I try this code using my azure storage URL in the form
https://XXXXX.blob.core.windows.net/
and a filename (C:\Temp\Test.txt) I get the following error;
<?xml version="1.0" encoding="utf-8"?><Error><Code>UnsupportedHttpVerb</Code><Message>The resource doesn't support specified Http Verb.
I suspect there's a problem in the header or post data rather than the VBA and this is not really my area.
Any help greatly appreciated.
I came across this post as I'm searching the same answer for uploading images to Azure Blob Storage. I took me 2 days to get the answer. And the code posted above did help me to partly solve the problem.
I would like to post my solution here in case anyone else is looking for the same answer.
Before you can use the code below, you need to get the Shared Access Signature (SAS) from your Azure portal (manage panel). You should be able to google the answers on this.
Public Sub UploadAfIle(sUrl As String, sFileName As String)
Dim adoStream As Object
Set adoStream = CreateObject("ADODB.Stream")
adoStream.Mode = 3 ' read write
adoStream.Type = 1 ' adTypeBinary
adoStream.Open
adoStream.LoadFromFile (sFileName)
With CreateObject("Microsoft.XMLHTTP")
adoStream.Position = 0
.Open "PUT", sUrl, False
.setRequestHeader "Content-Length", "0" 'this is not a must
.setRequestHeader "x-ms-blob-type", "BlockBlob"
.Send adoStream.Read(adoStream.Size)
End With
Set adoStream = Nothing
End Sub
sURL is a URL looks like (I'm in China so the Host is different): https://myaccount.blob.core.chinacloudapi.cn/products/newimagename.jpg?sv=2016-05-31&ss=bfpq&srt=dco&sp=rydlscup&se=2017-07-30T18:40:26Z&st=2017-07-28T10:40:26Z&spr=https&sig=mJgDyECayITp0ivVrD4Oug%2Bz%2chN7Wpo2nNtcn0pYRCU%4d
The one bolded is the SAS token you generated from Azure.
Worth noting the format of the sUrl in SiliconXu's answer is made up of 3 parts, I didn't realise at first so got a sore head for a while!!
1) Azure blob container URL (from the properties in the Storage Explorer)
2) the filename (this is the part I omitted by mistake)
3) Shared Access Signature
So is built like this
sURL = destination_folder & "/" & local_file_name & "?" & conn_SAS
I don't have the reputation require to comment directly below that answer
Great code though, as soon as I worked out the format of the sURL it worked like a dream
Azure Storage Service uses private key authentication. Since VBA runs on the end user's machine you are exposing yourself to a whole slew of risks associated with that key getting into the wild. I would recommend rethinking the whole premise of going directly from VBA to Azure Storage and utilize your own WebAPI to handle storing data to Blob.
This would have the dual benefit of:
1) making it easier to integrate with from VBA and
2) protecting your Azure Storage private key behind a component of your solution that doesn't get deployed to the end user's machine.

SEND SMS from samsung galaxy win celphone using vb.net

How to send sms from your cellphone to any number using vb.net? I have searched over the internet including youtube but it seems that i could not find or cant figure out where to start. My CP cant event detected in the "phone and modem" in windows...
I have a perfect way to send SMS in visual basic, using AT-commands.
AT-commands:are instructed through which you can send and receive SMS messages, make calls from cell phone, and this is an example to Send a message:
Firstly:
Write this code in the top:
Imports System.IO.Ports
Imports System.IO
Secondly:
Write this code in the public class of form:
Dim SerialPort As New System.IO.Ports.SerialPort()
Dim CR As String
Thirdly:
Create a textBox(TextmsgTextBox) to write the text message, and TextBox2(MobileNumberTextBox) to enter the mobile number, and Button(SendBUT) to Send message.
And write this code in the button click event.
If SerialPort.IsOpen Then
SerialPort.Close()
End If
SerialPort.PortName = COM4
SerialPort.BaudRate = 9600
SerialPort.Parity = Parity.None
SerialPort.StopBits = StopBits.One
SerialPort.DataBits = 8
SerialPort.Handshake = Handshake.RequestToSend
SerialPort.DtrEnable = True
SerialPort.RtsEnable = True
SerialPort.NewLine = vbCrLf
Dim message As String
message = MsgRichTextBox.Text
SerialPort.Open()
If SerialPort.IsOpen() Then
SerialPort.Write("AT" & vbCrLf)
SerialPort.Write("AT+CMGF=1" & vbCrLf)
SerialPort.Write("AT+CMGS=" & Chr(34) & phoneNumBox.Text & Chr(34) & vbCrLf)
SerialPort.Write(message & Chr(26))
SentPicture.Visible = True
SentLabel.Visible = True
SentTimer.Start()
Else
MsgBox("Port not available")
End If
I Hope My Answer Was Useful To You.
Important Note
Port value change from time to another and from computer to another.
I will show you how to know port value of your device by pictures.
1:Enter to Device Manager from Control Panel.
2:Right click on the device, and choose Properties.
3:Choose Modem tap, and look for port name, and use it in your application.

It's posible to define the UDP sourceport?

I have a WinForm application made it in VB.NET and I need to answer in the same port that I receive the UDP message but with the code that I have running the application source port is being chosen by the O.S., or it seems that.
Private Sub UdpSend(ByVal txtMessage As String)
Dim pRet As Integer
GLOIP = IPAddress.Parse(IpRemotaLbl.Text)
GLOINTPORT = RemotePortLbl.Text
MyUdpClient.Connect(GLOIP, GLOINTPORT)
bytCommand = Encoding.ASCII.GetBytes(txtMessage)
pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
'Console.WriteLine("No of bytes send " & pRet)
PrintLog("No of bytes send " & pRet)
End Sub
In example, if I receive the UDP message on port 8082 the answer, currently, is being sent from port 1515(local) to 8082(remote) and I need to send the message from port 8082(local) to 8082(remote).
Thanks.
You need to bind the UdpClient to a local port before you call Send(). The only way to specify the source port is in the UdpClient's constructor, so if you do not know which source port to use until you have received a message first then you will have to wait until then before creating the UdpClient.
Private Sub UdpSend(ByVal txtMessage As String)
Dim pRet As Integer
Dim MyUdpClient as UdpClient = new UdpClient(8082); ' <-- here
MyUdpClient.Connect(IPAddress.Parse(IpRemotaLbl.Text), RemotePortLbl.Text)
bytCommand = Encoding.ASCII.GetBytes(txtMessage)
pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
'Console.WriteLine("No of bytes send " & pRet)
PrintLog("No of bytes send " & pRet)
End Sub