Counting ping attempts - vb.net

Imports System.Net.NetworkInformation
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim pingtarget As String = "88.250.204.138"
Dim pingre As PingReply = Ping.Send(pingtarget)
If My.Computer.Network.Ping("pingtarget", 9002) Then
address.ForeColor = Color.Green
Do While My.Computer.Network.Ping("pingtarget", 9002)
Me.ListBox1.Items.Add("Response from " & pingtarget & " in " & pingre.RoundtripTime.ToString() & " ms")
My.Computer.Network.Ping("pingtarget", 9002)
Loop
Else
Timer2.Enabled = True
address.ForeColor = Color.Red
MsgBox("Connection Failed")
End If
End Sub
End Class
Hey guys, I just began trying to develop a program that will keep pinging the server and if connection is lost, the client will reboot itself. I have some questions :
1- How to count the reboots? Otherwise it will keep rebooting as long as there is no connection. Reboots will retry connecting internet again but it fails too much, there must be a way to stop it. For example after 3 reboots , the client will run even without connection.
2- In these codes, when there is no connection, I get aa error message saying "An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.VisualBasic.dll".

One obvious problem:
change this part of your code:
My.Computer.Network.Ping("pingtarget", 9002)
to this:
My.Computer.Network.Ping(pingtarget, 9002)
you are passing pingtarget as a string not a variable.

Related

How to fix "The I/O operation has been aborted because of either a thread exit or an application request" with SerialPort in VB.NET?

I'm pretty new at programming, and .net is the what I use to do the easy stuff I need. I created a program to read from a weight indicator that comes through the serial port and it was working just fine like this for an EL05 device:
Private Sub sppuerto_DataReceived( sender As Object, e As IO.Ports.SerialDataReceivedEventArgs ) Handles sppuerto.DataReceived
Dim buffer As String
'------- WORKS FOR EL05 -----------------
buffer = sppuerto.ReadLine
txtrecibe.Text = buffer.Substring(4, 5)
End Sub
But now I'm connecting a new device from another manufacturer and I get an exception with ReadLine:
An unhandled exception of type 'System.IO.IOException' occurred in System.dll
Additional information: La operación de E/S se anuló por una salida de subproceso o por una solicitud de aplicación"
The English version of the exception message is
The I/O operation has been aborted because of either a thread exit or an application request
I got it to work with ReadExisting but it keeps reading and never stops like it did with ReadLine
Private Sub sppuerto_DataReceived( sender As Object, e As IO.Ports.SerialDataReceivedEventArgs ) Handles sppuerto.DataReceived
Dim buffer As String
'------------- WORKS WITH NEW INDICATOR BUT UNREADABLE----------------
buffer = sppuerto.ReadExisting
txtrecibe.Text = buffer
End Sub
I looked around but all the posts refer to C# implementations and I really don't want to get into that since is completely different for what I read. Also in Java.
Has anyone tried this in VB.NET? I can paste more of the code if needed.
Edit:
Adding the complete code by request (not really that long)
Imports System.IO.Ports
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
buscarpuerto()
End Sub
Private Sub buscarpuerto()
Try
cmbPort.Items.Clear()
For Each puerto As String In My.Computer.Ports.SerialPortNames
cmbPort.Items.Add(puerto)
Next
If cmbPort.Items.Count > 0 Then
cmbPort.SelectedIndex = 0
Else
MsgBox(" NO HAY PUERTO DISPONIBLES ")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub btnconectar_Click(sender As Object, e As EventArgs) Handles btnconectar.Click
Try
With sppuerto
.BaudRate = Int32.Parse(CboBaudRate.Text)
.DataBits = 8
.Parity = IO.Ports.Parity.None
.StopBits = 1
.PortName = cmbPort.Text
.Open()
If .IsOpen Then
lblestado.Text = "CONECTADO"
Else
MsgBox("NO SE PUDO CONECTAR", MsgBoxStyle.Critical)
End If
End With
Catch ex As Exception
End Try
End Sub
Private Sub btndesconectar_Click(sender As Object, e As EventArgs) Handles btndesconectar.Click
sppuerto.Close()
lblestado.Text = "DESCONECTADO"
End Sub
Private Sub sppuerto_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles sppuerto.DataReceived
Dim buffer As String
Dim x As String
buffer = ""
'------- WORKS FOR EL05 -----------------
'buffer = sppuerto.ReadLine
'txtrecibe.Text = buffer.Substring(4, 5)
'------------- WORKS WITH NEW INDICATOR BUT UNREADABLE----------------
x = sppuerto.ReadExisting
buffer = buffer + x
txtrecibe.Text = buffer
End Sub
Private Sub btnenviar_Click(sender As Object, e As EventArgs) Handles btnenviar.Click
If sppuerto.IsOpen Then
sppuerto.WriteLine(txtenvia.Text)
Else
MsgBox("NO ESTAS CONECTADO", MsgBoxStyle.Exclamation)
End If
End Sub
Private Sub btnsalida_Click(sender As Object, e As EventArgs) Handles btnsalida.Click
If lblestado.Text = ("CONECTADO") Then
MsgBox("DESCONECTARSE DEL SISTEMA", MsgBoxStyle.Exclamation, "AYUDA")
Else
Close()
End If
End Sub
End Class
I suspect that with your new device, the data is NOT completely received. You may need to test the incoming data buffer to see if its length is still increasing. Only do you ReadExisting if the device is done sending data into the buffer.
Dim x = SerialPort1.BytesToRead
Application.DoEvents()
Do While SerialPort1.BytesToRead <> x
x = SerialPort1.BytesToRead
Application.DoEvents()
Loop
Beware that this will block your code from running until the device is done writing. Also, if your computer is slow, and the COM device is continuously sending data, you may get a new string in the buffer before the BytesToRead numbers can be compared and NEVER break out.
You may also want to change your ReceivedBytesThreshold for the serial port to only fire the DataReceived event if several bytes have been received instead of the default one byte.

the connection property has not been initialized

I'm trying to run this code for my user interfaces, I connected the interface with my database and I did everything correctly. But the problem is this error keeps showing and I have no clue in how to fix it.
The error says "the connection property has not been initialized"
And this is my code,
Public Class ManageBus
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
txtbus.Text = Nothing
txtdriver = Nothing
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
End
End Sub
Private Sub btnadd_Click(sender As Object, e As EventArgs) Handles btnadd.Click
Try
OracleConnection1.Open()
Dim command As String
command = "insert into BUS(Bus_ID, Driver_ID)" _
& " values('" & txtbus.Text & "', '" _
& txtdriver.Text & ")"
OracleDataAdapter1.InsertCommand.CommandText = command
lblsql.Text = command
OracleDataAdapter1.InsertCommand.ExecuteNonQuery()
MsgBox("Insert Successful", MsgBoxStyle.Information, "Insert Status")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
OracleConnection1.Close()
End Try
End Sub
You need to initialize the connectionstring for the connection to setup the connection. For example:
Dim OracleConnection1 As New OracleConnection("Data Source=ORCL;User Id=test;Password=test;");
OracleConnection1.Open();

Debugging error: "Object reference not set to an instance of an object"

Introduction (Warning: Bad English)
Hello everybody. I need some help with my program.
So, basically my program is made for downloading one file and extracting it to known path, for example C:\Users\ProfileName\Documents\Windward. This path is suitable for most part of people. But for some people it's wrong path (Because file need's to be installed in Documents\Windward folder). So i decided to make changeable path. I thought I making everything right, but something gone wrong. And i thing something is frong with this: Dim path As String = TextBox1.Text & "\Localization.zip", but i don't know how to fix it.
Please help me!
Error:
An unhandled exception of type System.InvalidOperationException occurred in AutoDownloadV2.exe
Additional information: Error in form creating. Exception.InnerException. Error: Object reference not set to an instance of an object.
After Debug I recieve this:
in AutoDownloadV2.My.MyProject.MyForms.Create__Instance__[T](T Instance) in :string 190
in AutoDownloadV2.My.MyApplication.OnCreateMainForm() в B:\Projects\Progs\AutoDownloadV2\AutoDownloadV2\AutoDownloadV2\My Project\Application.Designer.vb:string 35
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
in AutoDownloadV2.My.MyApplication.Main(String[] Args) in :string 81 The program '[5452] AutoDownloadV2.exe' has exited with code 0 (0x0).
Here is my code (I have removed the useless part of code.)
Public Class Form1
Public WithEvents download As WebClient
Dim path As String = TextBox1.Text & "\Localization.zip"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Try
My.Computer.FileSystem.DeleteFile(path)
Catch ex As Exception
End Try
download = New WebClient
download.DownloadFileAsync(New Uri("http://http://exsite.example"), path)
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
End Sub
Private Sub download_DownloadProgressChanged(ByVal sender As System.Object, ByVal e As System.Net.DownloadProgressChangedEventArgs) Handles download.DownloadProgressChanged
Try
Label3.Text = "Downloaded : " & e.BytesReceived / 1024 & " kb / " & e.TotalBytesToReceive / 1024 & " kb "
Label4.Text = ProgressBar1.Value & "%"
ProgressBar1.Value = e.ProgressPercentage
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
If e.BytesReceived = e.TotalBytesToReceive Then
Unzip()
End If
End Sub
Public Sub Unzip()
Dim startPath As String = path
Dim zipPath As String = path
Dim extractPath As String = ("C:\Users\" + SystemInformation.UserName + "\Documents\Windward\")
If My.Computer.FileSystem.FileExists(extractPath + "mods\translateMod\Localization.txt") Then
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Localization.txt")
Try
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Version.txt")
Catch e As Exception
End Try
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
Else
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
End If
End Sub
End Class
Move the initialization of path inside the Form1_Load after setting the initial value in TextBox1
Dim path As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
path = TextBox1.Text & "\Localization.zip"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
The problem is caused by the reference to TextBox1 in the global area of your form class. At that point the TextBox1 is still Nothing (not initialized) thus you get the NRE message (Null Reference Exception)

Tcp Client/Server - Client messages issue

I have client and server application.
I have the client disconnect from the server with client.close via a disconnect button.
I send a message, shows on server. ok works great.
I disconnect and then reconnect. I send a message. It shows the message two times.
I disconnect another time then reconnect. I send a message. It then shows the message three times.
It is incrementing the message and sending it multiple times after the disconnect and then reconnect.
Help? Been trying to figure this out for a while
[SERVER]
Public Class Server
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ListenerThread As System.Threading.Thread
Dim ClientID As String
Dim ClientIP As String
Dim ClientIPandID As String
Dim ClientIPandPort As String
Dim TotalItemCount As String
Dim clientcount As Integer = 0
Private Sub Server_Load(sender As Object, e As EventArgs) Handles Me.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub ButtonStart_Click(sender As System.Object, e As System.EventArgs) Handles ButtonStart.Click
If TextBoxPort.Text = "" Then
MsgBox("Please Enter Port To Run On.")
Else
ListenerThread = New System.Threading.Thread(AddressOf Listening)
ListenerThread.IsBackground = True
ListenerThread.Start(TextBoxPort.Text)
ButtonStart.Enabled = False
ButtonStop.Enabled = True
ListBox1.Items.Add("[SERVER] Running on Port " + TextBoxPort.Text)
ListBox1.Items.Add("[SERVER] Waiting For A Connection...")
End If
End Sub
Private Sub Listening(ByVal Port As Integer)
Try
Listener = New TcpListener(IPAddress.Any, Port)
Listener.Start()
Do
Client = Listener.AcceptTcpClient 'Accepts Client Trying To Connect
If Client.Connected Then
MsgBox("Client Connected")
End If
clientcount += 1
GetClientInfo() 'Retrieves The Clients Info
AddHandler ReceivedMessage, AddressOf ReceivedMessage1
Loop Until False
Catch ex As Exception
End Try
End Sub
'Events
Public Event ReceivedMessage(ByVal Command As String)
Private Sub GenerateClientSessionNumber()
Dim r As New Random
Dim x As String = String.Empty
For i = 0 To 7
x &= Chr(r.Next(65, 89))
Next
ClientID = x
End Sub
Private Sub GetClientInfo()
GenerateClientSessionNumber()
ClientIPandID = Client.Client.RemoteEndPoint.ToString().Remove(Client.Client.RemoteEndPoint.ToString().LastIndexOf(":")) & " - " & ClientID
ClientIP = Client.Client.RemoteEndPoint.ToString().Remove(Client.Client.RemoteEndPoint.ToString().LastIndexOf(":"))
ClientIPandPort = Client.Client.RemoteEndPoint.ToString()
MsgBox(ClientIPandPort)
ListBox2.Items.Add(ClientIPandID)
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
End Sub
Private Sub ButtonStop_Click(sender As System.Object, e As System.EventArgs) Handles ButtonStop.Click
Listener.Stop()
Client.Close()
ButtonStop.Enabled = False
ButtonStart.Enabled = True
ListBox1.Items.Add("[SERVER] Server Stopped")
End Sub
Private Sub Reading()
Try
Dim Reader As New StreamReader(Client.GetStream)
Dim Command As String = Reader.ReadLine
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
RaiseEvent ReceivedMessage(command)
Catch ex As Exception
End Try
End Sub
Private Sub ReceivedMessage1(ByVal Command As String)
Dim Message() As String = Command.Split("|")
If Message(0) = "MESSAGE" Then
MsgBox("Message Received From Client " + ">" + Message(1))
End If
end sub
[CLIENT]
Public Class Client
Dim Client As New TcpClient
Sub Connect(ByVal ServerIP As String, ByVal Port As Integer)
'Try To Make Connection With Server
If Client.Connected = True Then
MsgBox("Already Connected")
MsgBox("Connected To " + Client.Client.RemoteEndPoint.ToString)
Else
MsgBox("Currently Not Connected. Trying To Connect...")
Try
Client.Connect(ServerIP, Port)
MsgBox("Connected")
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
Catch ex As Exception
MsgBox("Could Not Connect To Server. Check Server." + ex.Message.ToString)
End Try
End If
End Sub
Private Sub SendData(ByVal Message As String) 'Sends Data to Server
TextBox1.Text = Message
Try
If Client.Connected = True Then
Dim Writer As New StreamWriter(Client.GetStream)
Writer.WriteLine(Message)
Writer.Flush()
Else
MsgBox("Cannot Send Message. Connection To Server Is Not Active.")
End If
Catch ex As Exception
MsgBox("You Are Not Connected To The Server." + vbCrLf + ex.Message.ToString)
End Try
End Sub
Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click
Connect(TextBoxIPAddress.Text, TextBoxPort.Text)
End Sub
Private Sub ButtonSendMessage_Click(sender As Object, e As EventArgs) Handles ButtonSendMessage.Click
SendData("MESSAGE|" & TextBoxMessage.Text)
End Sub
Private Sub Client_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
SendData("DISCONNECT|")
Client.Close()
Client = New TcpClient
End Sub
End Class
i am not sure about the problem but i can give you some hypothesizes, firstly you add handler on every client you connect on server side and that means multiple pointer to the same place, secondly when you connect to server and reconnect you actually don't tell the server that the two clients are the same so he make two channels between the client and the server, the first is the old one that didn't close and he still have handler on it, the server don't recognize that the first is disconnected because he is connected! even if its another object at client. so when client disconnects , disconnect him from server too, or at every loop test if clients are connected before accepting do this test .
Since I have a class Called "ConnectedClient". I was able to make a call to that specific client or all clients and Close/Destroy the connection.

VB.NET Warning , CPU Application

The warning is : An error occurred creating the form. See Exception.InnerException for details. The error is: Cannot load Counter Name data because an invalid index '' was read from the registry.
My Code is :
Imports System
Imports System.Management
Imports System.Diagnostics
Public Class Form1
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Dim cpuLoad As Integer = CDec(PerformanceCounter1.NextValue.ToString())
cpuLoad = 100 - cpuLoad
Label1.Text = cpuLoad.ToString() & "%"
On Error Resume Next
ProgressBar1.Value = cpuLoad.ToString
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Timer1.Start()
Label2.Text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "ProcessorNameString", Nothing)
label3.text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "~MHz", Nothing) & " Mhz"
End Sub
End Class
Have a look at this question. I found this, and many more examples suggesting that your problem results from one or more corrupted registry entries. Pablissimo's answer provides an explanation of the problem, and the relevant steps to rebuild these entries.
Click Start, type cmd right click cmd.exe, and select Run as
administrator. At the prompt, type lodctr /r and press ENTER.
First of all your cpu counter gives a strange value on my pc."2 times higher than it is"
what i use is also a performance counter but the value is almost the same as in windows task manager.
Dim CpuCounter As New PerformanceCounter()
Dim CpuResult As New Integer
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
With CpuCounter
.CategoryName = "Processor"
.CounterName = "% Processor Time"
.InstanceName = "_Total"
End With
CpuResult = CpuCounter.NextValue
CpuLabel.Text = CpuResult & "%"
CpuBar.Value = CpuResult
End Sub
the other thing is ...
Your code to get the ProcessorNameString and the Mhz is working on my computer..
But you can also use it like this.
you need to Imports Microsoft.Win32 "but of course you already have that"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cpuName As String
Dim cpuFreq As String
Dim regKey As RegistryKey
regKey = Registry.LocalMachine
regKey = regKey.OpenSubKey("HARDWARE\DESCRIPTION\System\CentralProcessor\0", False)
cpuName = regKey.GetValue("ProcessorNameString")
cpuFreq = regKey.GetValue("~MHz")
Label2.Text = cpuName
Label3.Text = cpuFreq & " MHz"
End Sub
And if this does not work you can also use WMI "ManagementObjectSearcher" for it.
you need to Imports System.Management
and Add reference System.Management to your project.
then you can use this code in the form load event to get the same info
Dim cpuName As String
Dim cpuFreq As String
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_Processor")
For Each queryObj As ManagementObject In searcher.Get()
cpuName = queryObj("Name")
cpuFreq = queryObj("CurrentClockSpeed")
Label2.Text = cpuName
Label3.Text = cpuFreq & "MHz"
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try