Call Page_Load from a Protected Sub VB.NET - vb.net

I've got a front facing ASPX page that displays several buttons and preforms the code requested. The issue is that I'm reading a relay and so my current state of the web relay is always behind due to my page refresh so I'm thinking I just need to start at the Page_Load event to make this happen correctly and regenerate the status of the relay.
My question is, how do I call the Page_Load() from within the button Click sub?
'Global Gate Interface
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim tcpClient As New TcpClient()
'Connect to webrelay
tcpClient.Connect("xx.xx.xx.xx", 80)
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'Create the XML command to send to Webrelay
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("GET /state.xml HTTP/1.1" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==" & vbCrLf & vbCrLf)
'Send the command to webrelay
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Convert the bytes received from Webrelay into a string
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Convert the string into and array
Dim array1 As Char() = returndata.ToCharArray()
'Relay State found at index 66 of array
If array1(66) = "1" Then
relayState.Text = "ON"
Else
relayState.Text = "OFF"
End If
'Input State found at index 94 of array
If array1(94) = "1" Then
inputState.Text = "ON"
Else
inputState.Text = "OFF"
End If
'Close the connection
tcpClient.Close()
End Sub
'Turn East relay On
Protected Sub relayOnEast_Click(sender As Object, e As EventArgs) Handles eastOpen.Click
Dim tcpClient As New TcpClient()
'Connect to webrelay
tcpClient.Connect("xx.xx.xx.xx", 80)
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'Create the XML command to send to Webrelay
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("GET /state.xml?relayState=1 HTTP/1.1<CR><LF>" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==<CR><LF><CR><LF>" & vbCrLf & vbCrLf)
'Send the command to webrelay
netStream.Write(sendBytes, 0, sendBytes.Length)
'Close the connection
tcpClient.Close()
'RERUN PAGE LOAD HERE?
End Sub

Just move the code from Page_Load() to a separate private method and call that method in Page_Load() and relayOnEast_Click().
Side note: this might not work as you have to pay attention to the life cycle of a ASPX page.

Put the code that is inside the protected sub into a separate sub maybe like this
and then call the new sub from the form load event. And then you can call the same code from your other sub.
Protected sub PageReload
Dim tcpClient As New TcpClient()
'Connect to webrelay
tcpClient.Connect("xx.xx.xx.xx", 80)
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'Create the XML command to send to Webrelay
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("GET /state.xml HTTP/1.1" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==" & vbCrLf & vbCrLf)
'Send the command to webrelay
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Convert the bytes received from Webrelay into a string
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Convert the string into and array
Dim array1 As Char() = returndata.ToCharArray()
'Relay State found at index 66 of array
If array1(66) = "1" Then
relayState.Text = "ON"
Else
relayState.Text = "OFF"
End If
'Input State found at index 94 of array
If array1(94) = "1" Then
inputState.Text = "ON"
Else
inputState.Text = "OFF"
End If
'Close the connection
tcpClient.Close()
End Sub

Related

How GetResponseCode in live.com and hotmail

I want to send a message to the hotmail mail and test the mail whether it exists or not. If it does not exist, a message appears for me. A code was made and tested on the gmail mail and it works great, but when converting it to hotmail it did not work. Please help
Private Function GetResponseCode(ByVal ResponseString As String) As Integer
Try
Return Integer.Parse(ResponseString.Substring(0, 3))
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 0 To ListBox1.Items.Count - 1
Dim tClient As TcpClient = New TcpClient("smtp-mail.outlook.com", 587)
Dim CRLF As String = vbCrLf
Dim dataBuffer As Byte()
Dim ResponseString As String
Dim netStream As NetworkStream = tClient.GetStream()
Dim reader As StreamReader = New StreamReader(netStream)
ResponseString = reader.ReadLine()
dataBuffer = BytesFromString("HELO" & CRLF)
netStream.Write(dataBuffer, 0, dataBuffer.Length)
ResponseString = reader.ReadLine()
dataBuffer = BytesFromString("MAIL FROM:<fx121#gmail.com>" & CRLF)
netStream.Write(dataBuffer, 0, dataBuffer.Length)
ResponseString = reader.ReadLine()
dataBuffer = BytesFromString("RCPT TO:<" & Itm(i) + "#hotmail.com" & ">" & CRLF)
netStream.Write(dataBuffer, 0, dataBuffer.Length)
ResponseString = reader.ReadLine()
If GetResponseCode(ResponseString) = 550 Then
MsgBox("Not exist")
Else
MsgBox("exist")
End If
dataBuffer = BytesFromString("QUITE" & CRLF)
netStream.Write(dataBuffer, 0, dataBuffer.Length)
tClient.Close()
Next
End Sub

tcpclient webrelay and control analog outputs

This is the first time that I have ever worked with networking in a program control webrelay. I was able to write my program with success... or so I thought. A couple of days ago I had a device drop off the network and my program "locked up". I know it did not truly lock up. I did some debugging and found out that what is happening is that when the tcpclient throws an exception, it just stops running any code after it. This causes my program to stop updating because of a timer that is never restarted and I con't control analog Outputs.
Public Class ControlPanelX317
Private SQL As New SQLControl
Private Sub ControlPanelX317_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadControlsX317()
End Sub
'Dislay Conrol
'__________________________________________________________________________________________________________________________________________________________________________
Private Sub LoadControlsX317()
Dim loadqry As String = "SELECT * FROM controlsX317 WHERE controlsX317.ValueVoltageID = '" & 1 & "' "
Dim SQLCmd As New SqlCommand(loadqry, Sql.SQLCon)
If Sql.SQLCon.State = ConnectionState.Closed Then Sql.SQLCon.Open()
Dim reader As SqlDataReader = SQLCmd.ExecuteReader
While reader.Read = True
txt_S1_VolueVoltage.Text = reader("S1VolueVoltage")
txt_S2_VolueVoltage.Text = reader("S2VolueVoltage")
txt_S3_VolueVoltage.Text = reader("S3VolueVoltage")
txt_S4_VolueVoltage.Text = reader("S4VolueVoltage")
End While
SQLCmd.Dispose()
reader.Close()
Sql.SQLCon.Close()
End Sub
Private Sub btn_Save_ValueVoltage_Click(sender As Object, e As EventArgs) Handles btn_Save_ValueVoltage.Click
If txt_S1_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S1_VolueVoltage.Clear()
Exit Sub
End If
If txt_S2_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S2_VolueVoltage.Clear()
Exit Sub
End If
If txt_S3_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S3_VolueVoltage.Clear()
Exit Sub
End If
If txt_S4_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S4_VolueVoltage.Clear()
Exit Sub
End If
If txt_S1_VolueVoltage.Text <> "" Then
Dim UpdateValueVoltage As String = "UPDATE controlsX317 SET S1VolueVoltage='" & txt_S1_VolueVoltage.Text & "', S2VolueVoltage='" & txt_S2_VolueVoltage.Text & "',
S3VolueVoltage='" & txt_S3_VolueVoltage.Text & "', S4VolueVoltage='" & txt_S4_VolueVoltage.Text & "'
WHERE ValueVoltageID ='" & 1 & "' "
If SQL.DataUpdate(UpdateValueVoltage) = 0 Then
MsgBox("The Sysytem could not be found!!! ")
Else
MsgBox("VolueVoltage successfully changed")
End If
Else
MsgBox("You must restart a Sysytem")
End If
End Sub
Private Sub btn_S1_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S1_SetVoltage.Click
lbl_S1_AnalogOutput.Text = Val(txt_S1_VolueVoltage.Text) * Val(txt_S1_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S2_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S2_SetVoltage.Click
lbl_S2_AnalogOutput.Text = Val(txt_S2_VolueVoltage.Text) * Val(txt_S2_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S3_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S3_SetVoltage.Click
lbl_S3_AnalogOutput.Text = Val(txt_S3_VolueVoltage.Text) * Val(txt_S3_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S4_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S4_SetVoltage.Click
lbl_S4_AnalogOutput.Text = Val(txt_S4_VolueVoltage.Text) * Val(txt_S4_ControlViltage.Text / 100) & "V"
End Sub
'End Display Control
'_________________________________________________________________________________________________________________________________________________________________________
'Conection to WebRelay X317
'_________________________________________________________________________________________________________________________________________________________________________
Public Sub getWebRelayState()
Dim tcpClient As New TcpClient()
Dim port As Integer
Try
port = Convert.ToInt32(txtPort.Text)
tcpClient.Connect(txt_IPAddress.Text, port)
If tcpClient.Connected Then
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'If we can read and write to the stream then do so
If netStream.CanWrite And netStream.CanRead Then
'Send the on command to webrelay
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes("GET /state.xml?noReply=0 HTTP/1.1" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==" & vbCrLf & vbCrLf)
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Parse the response and update the webrelay state and input text boxes
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Parse out the relay state and input state
Dim array1 As Char() = returndata.ToCharArray()
Dim ana(4) As Integer
'Relay State found at index 66
If array1(66) = "1" Then
RelayState.Text = "ON"
Else
RelayState.Text = "OFF"
End If
'Input State found at index 94
If array1(94) = "1" Then
inputState.Text = "ON"
Else
inputState.Text = "OFF"
End If
End If
'Close the connection
tcpClient.Close()
End If
Catch ex As Exception
inputState.Text = "Error"
RelayState.Text = "Error"
'Disable the timer
TimerRelayRefresh.Enabled = False
End Try
End Sub
Private Sub sendRequest(ByVal val As String)
Dim tcpClient As New TcpClient()
Dim port As Integer
Try
'Disable the timer
TimerRelayRefresh.Enabled = False
port = Convert.ToInt32(txtPort.Text)
tcpClient.Connect(txt_IPAddress.Text, port)
If tcpClient.Connected Then
MsgBox("connection successful")
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'If we can read and write to the stream then do so
If netStream.CanWrite And netStream.CanRead Then
'Send the on command to webrelay
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes("GET /state.xml?relayState=1 HTTP/1.1<CR><LF>" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==<CR><LF><CR><LF>" & vbCrLf & vbCrLf)
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Parse the response and update the webrelay state and input text boxes
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Parse out the relay state and input state
Dim array1 As Char() = returndata.ToCharArray()
'Relay State found at index 66
If array1(66) = "1" Then
RelayState.Text = "ON"
Else
RelayState.Text = "OFF"
End If
'Input State found at index 94
If array1(94) = "1" Then
inputState.Text = "ON"
End If
Else
inputState.Text = "OFF"
End If
End If
'Enable the timer
TimerRelayRefresh.Enabled = True
Catch ex As Exception
inputState.Text = "Error"
RelayState.Text = "Error"
'Disable the timer
TimerRelayRefresh.Enabled = False
End Try
End Sub
Private Sub btn_ControlsX317_On_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_On.Click
sendRequest("1")
End Sub
Private Sub btn_ControlsX317_Off_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_Off.Click
sendRequest("0")
End Sub
Private Sub btn_ControlsX317_PULSE_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_PULSE.Click
sendRequest("2")
End Sub
'End Conetion
'_________________________________________________________________________________________________________________________________________________________________________
End Class

Issue with socket chat not being able to send full messages

I am having a little issue with this socket chat, if I send little messages like "hello world" it works perfectly fine but if I try to send huge messages with about 10,000 characters it just crashes, i've been trying to fix this for the past 3 days with no luck, what should I be doing?
Server source:
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Enum Command
Login
'Log into the server
Logout
'Logout of the server
Message
'Send a text message to all the chat clients
List
'Get a list of users in the chat room from the server
Null
'No command
End Enum
Public Class Form1
'The ClientInfo structure holds the required information about every
'client connected to the server
Private Structure ClientInfo
Public socket As Socket
'Socket of the client
Public strName As String
'Name by which the user logged into the chat room
End Structure
'The collection of all clients logged into the room (an array of type ClientInfo)
Private clientList As ArrayList
'The main socket on which the server listens to the clients
Private serverSocket As Socket
Private byteData As Byte() = New Byte(1023) {}
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
clientList = New ArrayList()
'We are using TCP sockets
serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
'Assign the any IP of the machine and listen on port number 1000
Dim ipEndPoint As New IPEndPoint(IPAddress.Any, 2277)
'Bind and listen on the given address
serverSocket.Bind(ipEndPoint)
serverSocket.Listen(4)
'Accept the incoming clients
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
Catch ex As Exception
MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub
Private Sub OnAccept(ar As IAsyncResult)
Try
Dim clientSocket As Socket = serverSocket.EndAccept(ar)
'Start listening for more clients
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
'Once the client connects then start receiving the commands from her
clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), clientSocket)
Catch ex As Exception
MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub
Private Sub OnReceive(ar As IAsyncResult)
Try
Dim clientSocket As Socket = DirectCast(ar.AsyncState, Socket)
clientSocket.EndReceive(ar)
'Transform the array of bytes received from the user into an
'intelligent form of object Data
Dim msgReceived As New Data(byteData)
'We will send this object in response the users request
Dim msgToSend As New Data()
Dim message As Byte()
'If the message is to login, logout, or simple text message
'then when send to others the type of the message remains the same
msgToSend.cmdCommand = msgReceived.cmdCommand
msgToSend.strName = msgReceived.strName
Select Case msgReceived.cmdCommand
Case Command.Login
'When a user logs in to the server then we add her to our
'list of clients
Dim clientInfo As New ClientInfo()
clientInfo.socket = clientSocket
clientInfo.strName = msgReceived.strName
clientList.Add(clientInfo)
'Set the text of the message that we will broadcast to all users
msgToSend.strMessage = "<<<" & msgReceived.strName & " has joined the room>>>"
Exit Select
Case Command.Logout
'When a user wants to log out of the server then we search for her
'in the list of clients and close the corresponding connection
Dim nIndex As Integer = 0
For Each client As ClientInfo In clientList
If client.socket Is clientSocket Then
clientList.RemoveAt(nIndex)
Exit For
End If
nIndex += 1
Next
clientSocket.Close()
msgToSend.strMessage = "<<<" & msgReceived.strName & " has left the room>>>"
Exit Select
Case Command.Message
'Set the text of the message that we will broadcast to all users
msgToSend.strMessage = msgReceived.strName & ": " & msgReceived.strMessage
Exit Select
Case Command.List
'Send the names of all users in the chat room to the new user
msgToSend.cmdCommand = Command.List
msgToSend.strName = Nothing
msgToSend.strMessage = Nothing
'Collect the names of the user in the chat room
For Each client As ClientInfo In clientList
'To keep things simple we use asterisk as the marker to separate the user names
msgToSend.strMessage += client.strName & "*"
Next
message = msgToSend.ToByte()
'Send the name of the users in the chat room
clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSend), clientSocket)
Exit Select
End Select
If msgToSend.cmdCommand <> Command.List Then
'List messages are not broadcasted
message = msgToSend.ToByte()
For Each clientInfo As ClientInfo In clientList
If clientInfo.socket IsNot clientSocket OrElse msgToSend.cmdCommand <> Command.Login Then
'Send the message to all users
clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSend), clientInfo.socket)
End If
Next
Debug.Print(msgToSend.strMessage)
End If
'If the user is logging out then we need not listen from her
If msgReceived.cmdCommand <> Command.Logout Then
'Start listening to the message send by the user
clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), clientSocket)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub
Public Sub OnSend(ar As IAsyncResult)
Try
Dim client As Socket = DirectCast(ar.AsyncState, Socket)
client.EndSend(ar)
Catch ex As Exception
MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub
End Class
'The data structure by which the server and the client interact with
'each other
Class Data
Public strName As String
'Name by which the client logs into the room
Public strMessage As String
'Message text
Public cmdCommand As Command
'Command type (login, logout, send message, etcetera)
'Default constructor
Public Sub New()
cmdCommand = Command.Null
strMessage = Nothing
strName = Nothing
End Sub
'Converts the bytes into an object of type Data
Public Sub New(data__1 As Byte())
'The first four bytes are for the Command
cmdCommand = CType(BitConverter.ToInt32(data__1, 0), Command)
'The next four store the length of the name
Dim nameLen As Integer = BitConverter.ToInt32(data__1, 4)
'The next four store the length of the message
Dim msgLen As Integer = BitConverter.ToInt32(data__1, 8)
'This check makes sure that strName has been passed in the array of bytes
If nameLen > 0 Then
Me.strName = Encoding.UTF8.GetString(data__1, 12, nameLen)
Else
Me.strName = Nothing
End If
'This checks for a null message field
If msgLen > 0 Then
Me.strMessage = Encoding.UTF8.GetString(data__1, 12 + nameLen, msgLen)
Else
Me.strMessage = Nothing
End If
End Sub
'Converts the Data structure into an array of bytes
Public Function ToByte() As Byte()
Dim result As New List(Of Byte)()
'First four are for the Command
result.AddRange(BitConverter.GetBytes(CInt(cmdCommand)))
'Add the length of the name
If strName IsNot Nothing Then
result.AddRange(BitConverter.GetBytes(strName.Length))
Else
result.AddRange(BitConverter.GetBytes(0))
End If
'Length of the message
If strMessage IsNot Nothing Then
result.AddRange(BitConverter.GetBytes(strMessage.Length))
Else
result.AddRange(BitConverter.GetBytes(0))
End If
'Add the name
If strName IsNot Nothing Then
result.AddRange(Encoding.UTF8.GetBytes(strName))
End If
'And, lastly we add the message text to our array of bytes
If strMessage IsNot Nothing Then
result.AddRange(Encoding.UTF8.GetBytes(strMessage))
End If
Return result.ToArray()
End Function
End Class
Client source:
Enum Command
Login '0 Log into the server
Logout '1 Logout of the server
Message '2 Send a text message to all the chat clients
List '3 Get a list of users in the chat room from the server
Null '4 No command
End Enum
Public Class frmMain
Public clientSocket As System.Net.Sockets.Socket
'The main client socket
Public strName As String
'Name by which the user logs into the room
Private byteData As Byte() = New Byte(1023) {}
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call StartChat()
End Sub
Private Sub StartChat()
clientSocket = New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp)
Dim ipAddress As System.Net.IPAddress = System.Net.IPAddress.Parse("127.0.0.1")
Dim ipEndPoint As New System.Net.IPEndPoint(ipAddress, 2277)
clientSocket.BeginConnect(ipEndPoint, New AsyncCallback(AddressOf OnLoginConnect), Nothing)
End Sub
Private Sub OnLoginConnect(ar As IAsyncResult)
clientSocket.EndConnect(ar)
'We are connected so we login into the server
Dim msgToSend As New Data()
msgToSend.cmdCommand = Command.Login
msgToSend.strName = txtUser.Text
msgToSend.strMessage = Nothing
Dim b As Byte() = msgToSend.ToByte()
'Send the message to the server
clientSocket.BeginSend(b, 0, b.Length, System.Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf OnLoginSend), Nothing)
End Sub
Private Sub OnLoginSend(ar As IAsyncResult)
clientSocket.EndSend(ar)
strName = txtUser.Text
Call LoggedIn()
End Sub
'***************
Private Sub LoggedIn()
'The user has logged into the system so we now request the server to send
'the names of all users who are in the chat room
Dim msgToSend As New Data()
msgToSend.cmdCommand = Command.List
msgToSend.strName = strName
msgToSend.strMessage = Nothing
byteData = msgToSend.ToByte()
clientSocket.BeginSend(byteData, 0, byteData.Length, System.Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf OnSend), Nothing)
byteData = New Byte(1023) {}
'Start listening to the data asynchronously
clientSocket.BeginReceive(byteData, 0, byteData.Length, System.Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
End Sub
'Broadcast the message typed by the user to everyone
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
'Fill the info for the message to be send
Dim msgToSend As New Data()
'.ToString("M/d/yyyy h:mm:ss tt")
msgToSend.strName = "[" & Date.Now.ToString("h:mm:ss tt") & "] <" & strName & ">"
msgToSend.strMessage = txtMessage.Text
msgToSend.cmdCommand = Command.Message
Dim byteData As Byte() = msgToSend.ToByte()
'Send it to the server
clientSocket.BeginSend(byteData, 0, byteData.Length, System.Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf OnSend), Nothing)
txtMessage.Text = Nothing
End Sub
Private Sub OnSend(ar As IAsyncResult)
clientSocket.EndSend(ar)
End Sub
Private Sub OnReceive(ar As IAsyncResult)
'clientSocket.EndReceive(ar)
Dim bytesReceived As Long = clientSocket.EndReceive(ar)
If (bytesReceived > 0) Then
Me.Invoke(New iThreadSafe(AddressOf iThreadSafeFinish), New Object() {byteData})
End If
byteData = New Byte(1023) {}
clientSocket.BeginReceive(byteData, 0, byteData.Length, System.Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
End Sub
Private Delegate Sub iThreadSafe(ByVal ibyteData As Byte())
Private Sub iThreadSafeFinish(ByVal ibyteData As Byte())
Dim msgReceived As New Data(ibyteData)
'Accordingly process the message received
Debug.Print(msgReceived.cmdCommand)
Select Case msgReceived.cmdCommand
Case 0 'login
lstChatters.Items.Add(msgReceived.strName)
Exit Select
Case 1 'log out
lstChatters.Items.Remove(msgReceived.strName)
Exit Select
Case 2 'msg
Exit Select
Case 3 'List
lstChatters.Items.AddRange(msgReceived.strMessage.Split("*"c))
lstChatters.Items.RemoveAt(lstChatters.Items.Count - 1)
txtChatBox.Text += "<<<" & strName & " has joined the room>>>" & vbCr & vbLf
Exit Select
End Select
If msgReceived.strMessage IsNot Nothing AndAlso msgReceived.cmdCommand <> Command.List Then
txtChatBox.Text += msgReceived.strMessage & vbCr & vbLf
End If
End Sub
Private Sub txtMessage_TextChanged(sender As Object, e As KeyEventArgs) Handles txtMessage.KeyDown
If e.KeyCode = Keys.Enter Then
btnSend_Click(sender, Nothing)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
strName = txtUser.Text
End Sub
End Class
'The data structure by which the server and the client interact with
'each other
Class Data
Public strName As String
'Name by which the client logs into the room
Public strMessage As String
'Message text
Public cmdCommand As Command
'Command type (login, logout, send message, etcetera)
'Default constructor
Public Sub New()
cmdCommand = Command.Null
strMessage = Nothing
strName = Nothing
End Sub
'Converts the bytes into an object of type Data
Public Sub New(data__1 As Byte())
'The first four bytes are for the Command
cmdCommand = CType(BitConverter.ToInt32(data__1, 0), Command)
'The next four store the length of the name
Dim nameLen As Integer = BitConverter.ToInt32(data__1, 4)
'The next four store the length of the message
Dim msgLen As Integer = BitConverter.ToInt32(data__1, 8)
'This check makes sure that strName has been passed in the array of bytes
If nameLen > 0 Then
strName = System.Text.Encoding.UTF8.GetString(data__1, 12, nameLen)
Else
strName = Nothing
End If
'This checks for a null message field
If msgLen > 0 Then
strMessage = System.Text.Encoding.UTF8.GetString(data__1, 12 + nameLen, msgLen)
Else
strMessage = Nothing
End If
End Sub
'Converts the Data structure into an array of bytes
Public Function ToByte() As Byte()
Dim result As New List(Of Byte)()
'First four are for the Command
result.AddRange(BitConverter.GetBytes(CInt(cmdCommand)))
'Add the length of the name
If strName IsNot Nothing Then
result.AddRange(BitConverter.GetBytes(strName.Length))
Else
result.AddRange(BitConverter.GetBytes(0))
End If
'Length of the message
If strMessage IsNot Nothing Then
result.AddRange(BitConverter.GetBytes(strMessage.Length))
Else
result.AddRange(BitConverter.GetBytes(0))
End If
'Add the name
If strName IsNot Nothing Then
result.AddRange(System.Text.Encoding.UTF8.GetBytes(strName))
End If
'And, lastly we add the message text to our array of bytes
If strMessage IsNot Nothing Then
result.AddRange(System.Text.Encoding.UTF8.GetBytes(strMessage))
End If
Return result.ToArray()
End Function
End Class
You are assuming that you will receive an entire message at a time. TCP does not guarantee to preserve the chunks that you wrote. Use the return value bytesReceived to determine how many bytes are actually in the buffer.
Your code must be able to deal with the possibility of receiving all outstanding data one byte at a time.

Backgroundworker Progressbar freezes

So I've finally got this to almost work but now every few times I test the process the form and the progressbar freeze. I'm also sure there are much more efficient ways of doing this so any constructive criticism would be greatly appreciated.
This is the coding for one page of a program that allows the user to click one button to download and install one application and then press the next button to download and install a different application:
Imports System.Net.WebRequestMethods
Public Class Software
'Open link in external browser
Public Sub HandleRequestNavigate(ByVal sender As Object, ByVal e As RequestNavigateEventArgs)
Process.Start(New ProcessStartInfo(e.Uri.AbsoluteUri))
e.Handled = True
End Sub
'Declarations
Shared progressamc As New Progress
Shared progresscti As New ProgressCTI
WithEvents startcti As New Process
WithEvents startamc As New Process
WithEvents startsfstb As New Process
WithEvents amcworker As New ComponentModel.BackgroundWorker
WithEvents ctiworker As New ComponentModel.BackgroundWorker
Dim ProgressBarAMC As Object = Progress.ProgressBar1
Dim blprgrsAMC As Object = Progress.blprgrs
Dim ProgressBarCTI As Object = progresscti.ProgressBar1
Dim blprgrsCTI As Object = progresscti.blprgrs
'FTP Values
Const host As String = "ftp://10.167.16.80/"
Const username As String = "anonymous"
Const password As String = ""
'AMC File Put/Get
Const localfileamc As String = "C:\AMC.exe"
Const Remotefileamc As String = "Bin/AMC.exe"
'CTI File Put/Get
Const localfilecti As String = "C:\CTI.exe"
Const Remotefilecti As String = "Bin/CTI.exe"
'On Init
Public Sub New()
InitializeComponent()
amcworker.WorkerReportsProgress = True
amcworker.WorkerSupportsCancellation = True
ctiworker.WorkerReportsProgress = True
ctiworker.WorkerSupportsCancellation = True
End Sub
'Install AMC Button
Private Sub ButtonAMC(sender As Object, e As RoutedEventArgs)
Dim butt1 As Button = DirectCast(sender, Button)
butt1.IsEnabled = False
Dispatcher.BeginInvoke(New Action(AddressOf progressamc_Show))
AddHandler Progress.Cancel_Click, AddressOf myProcessamc_Exited
amcworker.RunWorkerAsync()
End Sub
'Open Dialog
Private Sub progressamc_Show()
Try
progressamc.ShowDialog()
Catch ex As Exception
MessageBox.Show("An error has occurred during the process:" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Please close the application and try again." _
& vbCrLf & "If you continue to encounter this error please Email")
End Try
End Sub
'FTP - Download
Private Sub ftpseshamc_DoWork(ByVal sender As System.Object, ByVal e As ComponentModel.DoWorkEventArgs) Handles amcworker.DoWork
Dim URI As String = host & Remotefileamc
Dim FTP As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(URI), System.Net.FtpWebRequest)
'Set the credentials
FTP.Credentials = New System.Net.NetworkCredential(username, password)
'FTP Options
FTP.KeepAlive = False
FTP.UseBinary = True
'Define the action as Download
FTP.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
'Get the response to the Ftp request and the associated stream
Try
Dim response As System.Net.FtpWebResponse = CType(FTP.GetResponse, System.Net.FtpWebResponse)
Dim Length As Long = response.ContentLength
Dim StopWatch As New Stopwatch
Dim CurrentSpeed As Double = Nothing
Using responseStream As IO.Stream = response.GetResponseStream
'loop to read & write to file
Using fs As New IO.FileStream(localfileamc, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Dim count As Integer
Do
If amcworker.CancellationPending = True Then
e.Cancel = True
Return
End If
StopWatch.Start()
amcworker.ReportProgress(CShort(count / Length * 100 + 0.5))
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
count += read
Loop Until read = 0
StopWatch.Stop()
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
Catch ex As Exception
MessageBox.Show("An error has occurred during the process:" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Please close the application and try again." _
& vbCrLf & "If you continue to encounter this error please Email")
myProcessamc_Exited()
End Try
Installamc()
End Sub
'Starts the installation
Sub Installamc()
startamc.StartInfo.FileName = "C:\AMC.exe"
startamc.EnableRaisingEvents = True
Try
startamc.Start()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dispatcher.Invoke(New Action(AddressOf Progressamc_Hide))
End Sub
'Hide Dialog during install
Private Sub Progressamc_Hide()
progressamc.Hide()
End Sub
'Report progress
Private Sub amcworker_ProgressChanged(ByVal sender As System.Object, ByVal e As ComponentModel.ProgressChangedEventArgs) Handles amcworker.ProgressChanged
ProgressBarAMC.value = e.ProgressPercentage
blprgrsAMC.Content = "Downloading: " & e.ProgressPercentage & "%"
End Sub
End Class
Again, any help would be greatly appreciated.
Edit: I've made the following edit to the code but I'm not entirely sure it's doing what I think it's doing. Basically what I intended is for the ReportProgress to only run once every 2047 bytes read.
'Get the response to the Ftp request and the associated stream
Try
Dim response As System.Net.FtpWebResponse = CType(FTP.GetResponse, System.Net.FtpWebResponse)
Dim Length As Long = response.ContentLength
Dim StopWatch As New Stopwatch
Dim CurrentSpeed As Double = Nothing
Using responseStream As IO.Stream = response.GetResponseStream
'loop to read & write to file
Using fs As New IO.FileStream(localfileamc, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Dim count As Integer
Dim chunk As Integer = Int(2047 / Length)
Dim cycle As Integer = chunk = count
Do
If amcworker.CancellationPending = True Then
e.Cancel = True
Return
End If
StopWatch.Start()
If cycle = True Then
amcworker.ReportProgress(CShort(count / Length * 100 + 0.5))
Else
End
End If
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
count += read
Loop Until read = 0
StopWatch.Stop()
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
Catch ex As Exception
MessageBox.Show("An error has occurred during the process:" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Please close the application and try again." _
& vbCrLf & "If you continue to encounter this error please Email")
myProcessamc_Exited()
End Try
I didn't scrutinize the code carefully, but I don't see why you're using stopwatch, so I took out the references. I'm not sure what starting it multiple times inside the loop and ending it outside would do anyway.
The use of the word END in the second example will comletely end your app! Pretty sure that's what you want there.
Try this modification of your first code. The key is only updating if change is >= 5%:
Using fs As New IO.FileStream(localfileamc, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Dim count As Integer
dim LastPct as Short = -5
dim Pct as Short = 0
Do
If amcworker.CancellationPending = True Then
e.Cancel = True
Return
End If
Pct = CShort(count / Length * 100 + 0.5)
if Pct>= (LastPct + 5)
amcworker.ReportProgress(Pct)
LastPCT= Pct
EndIf
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
count += read
Loop Until read = 0
amcworker.ReportProgress(100)
responseStream.Close()
fs.Flush()
fs.Close()
End Using

Save binary file from SQL Server

I'm trying to save a binary file stored in a SQL database with a SaveDialog, the function RetrieveFile retrieves the specified file from the database as a Byte array, here's what I have so far:
Private Shared Function RetrieveFile(ByVal filename As String) As Byte()
Dim connection As New SqlConnection("Data Source=SERVER\SQL2008;Initial Catalog=NorthPole;Integrated Security=True")
Dim command As New SqlCommand("SELECT pcfFile FROM Items WHERE pcfFileName=#Filename", connection)
command.Parameters.AddWithValue("#Filename", filename)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)
reader.Read()
Dim memory As New MemoryStream()
Dim startIndex As Long = 0
Const ChunkSize As Integer = 256
While True
Dim buffer As Byte() = New Byte(ChunkSize - 1) {}
Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)
memory.Write(buffer, 0, CInt(retrievedBytes))
startIndex += retrievedBytes
If retrievedBytes <> ChunkSize Then
Exit While
End If
End While
connection.Close()
Dim data As Byte() = memory.ToArray()
memory.Dispose()
Return data
End Function
Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "PCF File|*.pcf|"
saveFileDialog1.Title = "Save an pcf File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
Dim fs As System.IO.FileStream = CType(RetrieveFile("FakePCF.pcf"), System.IO.FileStream)
fs.Close()
End If
End Sub
Files are saved as "SqlDbType.VarBinary" within the database.
I get: "Index was outside the bounds of the array." on:
Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)
The MemoryStream appears to not be retrieving the data yet the SQL sytax is correct.
What am I doing wrong?
Well, first of all, your method returns byte[] and you're trying to cast it to FileStream. You should change your handler to following:
Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "PCF File|*.pcf|"
saveFileDialog1.Title = "Save an pcf File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
Dim fs As New System.IO.FileStream (saveFileDialog1.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim data As Byte() = RetrieveFile("FakePCF.pcf")
fs.Write(data, 0, data.Length)
fs.Flush()
fs.Close()
End If
End Sub