How to display IPv4 address using VB.net - vb.net

I found this code on youtube and follow exactly like it. The MAC address and the nic name showed but the IPv4 wont show. Basically i want to show ipv4 address for all network interface inside my computer with the either its connected or not. Here the code
Private Sub getinterface()
'get all network interface available in system
Dim nics As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
If nics.Length < 0 Or nics Is Nothing Then
MsgBox("No network interfaces found")
Exit Sub
End If
'if interfaces are found let list them. first clear the listview items
ListView1.Items.Clear()
For Each netadapter As NetworkInterface In nics
'next lets set variable to get interface properties for later use
Dim intproperties As IPInterfaceProperties = netadapter.GetIPProperties()
'now add the network adaptername to the list
ListView1.Items.Add(netadapter.Name)
'now get the mac address of this interface
Dim paddress As PhysicalAddress = netadapter.GetPhysicalAddress()
Dim addbyte As Byte() = paddress.GetAddressBytes()
Dim macaddress As String = ""
'now loop through the bytes value and change it to hex
For i = 0 To addbyte.Length - 1
macaddress &= addbyte(i).ToString("X2") 'change string to hex
'now let separate hex value with -except last one
If i <> addbyte.Length - 1 Then
macaddress &= "-"
End If
Next
'ount item in listview
Dim icount As Integer = ListView1.Items.Count
'use try
Try
With ListView1.Items(icount - 1).SubItems
.Add(macaddress)
'.Add(intproperties.UnicastAddresses(2).Address.ToString)
.Add(intproperties.AnycastAddresses(2).Address.ToString)
.Add(intproperties.UnicastAddresses(2).IPv4Mask.ToString)
.Add(intproperties.UnicastAddresses(0).Address.ToString)
.Add(intproperties.UnicastAddresses(1).Address.ToString)
'.Add( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
End With
Catch ex As Exception
End Try
Next
'now lets make auto size columns
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
getinterface()
End Sub
Is there a solution for this code or there is another simpler way to do this for display all nic name with its ipv4 address? currently using visual basic express 2010 express

Use WMI queries for this - it will be a lot simpler.
There are some useful classes available - Win32_NetworkAdapterConfiguration & Win32_NetworkAdapter for getting these details. For easy WMI code creation, search for WMI Code Creator
Imports System
Imports System.Management
Imports System.Windows.Forms
Namespace WMISample
Public Class MyWMIQuery
Public Overloads Shared Function Main() As Integer
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_NetworkAdapterConfiguration")
For Each queryObj As ManagementObject in searcher.Get()
Console.WriteLine("-----------------------------------")
Console.WriteLine("Win32_NetworkAdapterConfiguration instance")
Console.WriteLine("-----------------------------------")
If queryObj("IPAddress") Is Nothing Then
Console.WriteLine("IPAddress: {0}", queryObj("IPAddress"))
Else
Dim arrIPAddress As String()
arrIPAddress = queryObj("IPAddress")
For Each arrValue As String In arrIPAddress
Console.WriteLine("IPAddress: {0}", arrValue)
Next
End If
Console.WriteLine("IPEnabled: {0}", queryObj("IPEnabled"))
Console.WriteLine("MACAddress: {0}", queryObj("MACAddress"))
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try
End Function
End Class
End Namespace

Related

Unable to decode serial port data

I tried to receive data from medical 'Mindray bs 200' device through serial port. data received but is unreadable. Unable to find the kind of data encryption.
Here is the code that receives the data
Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles comPort.DataReceived
Dim str As String = ""
If e.EventType = SerialData.Chars Then
Do
Dim bytecount As Integer = comPort.BytesToRead
If bytecount = 0 Then
Exit Do
End If
Dim byteBuffer(bytecount) As Byte
comPort.Encoding = Encoding.GetEncoding(28591)
' comPort.Encoding = Encoding.GetEncoding(1252)
'comPort.Encoding = Encoding.GetEncoding("Windows-1252")
comPort.Read(byteBuffer, 0, bytecount)
str = str & System.Text.Encoding.ASCII.GetString(byteBuffer, 0, 1)
' The str looks like
Loop
End If
RaiseEvent ScanDataRecieved(str)
End Sub
Here is the data received
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????X???????????????????
While not for this particular device, this document discusses a device that uses the same RS232 communication protocol and recommends the following SerialPort settings:
Baud rate: 115200
DataBits: 8
StopBits: 1
Parity: None
No flow control
Note: Minimum baud rate is 57600.
According to this document
2.1 Message Grammar:
Each HL7 message is composed of segments that end with <CR>
3 Communication Process and Message Example:
A message of HL7 protocol is the format of: <SB> ddddd <EB><CR>
ASCII value (HEX)
<SB> (start of message): 0B (VT - vertical tab)
<EB> (end of message): 1C (FS - file separator)
<CR> (carriage return) 0D (carriage return)
In the code below, I'll show how to use a buffer to collect data when "start of message" is received (HEX: 0B) and fill the buffer until "end of message" (HEX: 1C) followed by a carriage return (HEX: 0D) is received - at which point we'll raise an event and/or output the data.
For testing, we'll also write the data to a file in the Documents folder - this file is deleted each time the program starts so that only data from the current execution of the program is contained in the file. Each byte of data is output as a 2-digit hexadecimal value which allows us to see if a value is a control character.
The following may be helpful for interpreting the values:
ASCII Table
ASCII Code - The extended ASCII table
Create a class (name: HelperSerialPort.vb)
HelperSerialPort.vb
Note: The code in method Port_DataReceived (within the if-elseif statements) is untested - I don't have the particular device that you're using to be able to test it.
'(.NET Framework) - Add reference: Project => Add Reference => Assemblies => System.Management
'add using statement: Using System.Management;
'
'For >= .NET 5, install NuGet Package: System.IO.Ports and System.Management
'add Imports statements: Imports System.IO.Ports; Imports System.Management;
'
'
Imports System.Management
Imports System.IO.Ports
'specify valid baud rates
Public Enum PortBaudRate As Integer
Baud57600 = 57600
Baud76800 = 76800
Baud115200 = 115200
End Enum
Public Class HelperSerialPort
Implements IDisposable
Private Const BufferSize As Integer = 4096 'this value may need to be changed
Private Port As SerialPort = Nothing
Private BytesReadMessage As Integer = 0 'used to hold message bytes read
Private Buffer(BufferSize) As Byte 'used to hold data
Private Filename As String = Nothing
Private IsMessage As Boolean = False
'events that can be subscribed to
Public Event DataReceived(ByVal sender As Object, ByVal data As String)
Public Event ErrorReceived(ByVal sender As Object, ByVal errMsg As String)
Sub New()
'set value
'data will be written to this file for testing
Filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Mindray BS200.txt")
If Not String.IsNullOrEmpty(Filename) AndAlso System.IO.File.Exists(Filename) Then
'delete existing file
System.IO.File.Delete(Filename)
End If
System.Diagnostics.Debug.WriteLine("Filename: '" & Filename & "'")
End Sub
Public Function Connect(ByVal comPort As String, ByVal Optional baudRate As PortBaudRate = PortBaudRate.Baud115200) As String
Dim errMsg As String = String.Empty
Dim portName As String = String.Empty
Dim result As String = String.Empty
If String.IsNullOrEmpty(comPort) Then
errMsg = "COM port not selected"
Throw New Exception(errMsg)
End If
Try
If Port Is Nothing Then
'create new instance
Port = New SerialPort(comPort)
'subscribe to events (add event handlers)
AddHandler Port.DataReceived, AddressOf Port_DataReceived
AddHandler Port.ErrorReceived, AddressOf Port_ErrorReceived
End If
If Not Port.IsOpen Then
'set properties
Port.BaudRate = baudRate
Port.Handshake = Handshake.None
'if parity is even or odd, then set DataBits = 7
'if parity is none, set DataBits = 8
Port.Parity = Parity.None
Port.DataBits = 8
Port.StopBits = StopBits.One
'Port.ReadTimeout = 500 'this value may need to be adjusted
Port.WriteTimeout = 500 'this value may need to be adjusted
Port.DtrEnable = True 'enable Data Terminal Ready
'Port.RtsEnable = True 'enable Request to Send
'Port.DiscardNull = True
'Port.ReceivedBytesThreshold = 1 'number of bytes that causes 'DataReceived' event to be raised; default is 1
'open port
Port.Open()
result = "Status: Connected"
Else
result = "Status: Already Connected"
End If
Catch ex As System.IO.IOException
errMsg = "Error: " & ex.Message
result = errMsg 'set value
Debug.WriteLine(errMsg)
Dispose()
Catch ex As Exception
errMsg = "Error: " & ex.Message
result = errMsg 'set value
Debug.WriteLine(errMsg)
Throw ex
End Try
Debug.WriteLine(result)
Return result
End Function
Public Function Disconnect() As String
Dispose()
Return "Status: Disconnected"
End Function
Public Sub Dispose() Implements System.IDisposable.Dispose
If Port IsNot Nothing Then
'unsubscribe from events (remove event handlers)
RemoveHandler Port.DataReceived, AddressOf Port_DataReceived
RemoveHandler Port.ErrorReceived, AddressOf Port_ErrorReceived
Port.Dispose()
Port = Nothing
Else
Debug.WriteLine("Info: Port is null")
End If
End Sub
Public Function IsPortOpen() As Boolean
If Port IsNot Nothing Then
If Port.IsOpen Then
Return True
Else
Try
Port.Dispose()
Catch ex As Exception
'do nothing
Debug.WriteLine("Error (IsPortOpen): " & ex.Message)
End Try
End If
Port = Nothing
System.GC.Collect()
System.GC.Collect()
End If
Return False
End Function
Private Sub Port_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
'ToDo: add desired code
Dim bytesRead As Integer = 0
Dim bytesToRead As Integer = 1
Dim errMsg As String = String.Empty
'read SerialPort data
Do
'read 1 byte at a time
bytesRead = Port.Read(Buffer, BytesReadMessage, bytesToRead)
'when <SB> (HEX: 0B) is received, remove all existing data from buffer
'this will result in the buffer only containing our desired data.
'when <EB> (HEX: 1C) is received followed by <CR> (HEX: 0D),
'this is the end of the message, so we'll send the message and/or display it.
'Buffer(BytesReadMessage) contains the last byte of data that was read
'
If Buffer(BytesReadMessage) = &HB Then
'0x0B - VT (vertical tab); in the documentation this is '<SB>' - start of message
System.Diagnostics.Debug.WriteLine("<SB> (start of message)")
'remove existing data (get ready for new message)
Array.Clear(Buffer, 0, Buffer.Length)
're-initialize to -1. It's incremented below which will result in the value being 0
BytesReadMessage = -1
'set value - start saving data to the buffer
IsMessage = True
ElseIf IsMessage AndAlso Buffer(BytesReadMessage) = &HD AndAlso Buffer(BytesReadMessage - 1) = &H1C Then
'0x1C - FS (file separator); in the documentation this is '<EB>' - end of message
'0x0D - CR (carriage return); in the documentation this is '<CR>'
System.Diagnostics.Debug.WriteLine("<EB> (end of message)")
'raise event to send data
SendData(Buffer)
'set value - stop saving data to the buffer
IsMessage = False
ElseIf Not IsMessage Then
'for debugging/testing, display non-message data
System.Diagnostics.Debug.WriteLine("Non-message data: " & Buffer(BytesReadMessage).ToString("X2"))
End If
'set value
BytesReadMessage += bytesRead
Debug.WriteLine("Info: BytesReadMessage: " & BytesReadMessage.ToString() & " bytesRead: " & bytesRead.ToString() & " Port.BytesToRead: " & Port.BytesToRead.ToString())
Loop While (Port.BytesToRead > 0)
Debug.WriteLine(String.Format("{0}---------------------------{0}", System.Environment.NewLine))
End Sub
Private Sub Port_ErrorReceived(ByVal sender As Object, ByVal e As SerialErrorReceivedEventArgs)
'ToDo: add desired code
Dim errMsg As String = e.EventType.ToString()
Debug.WriteLine("Port_ErrorReceived: " & errMsg)
'raise event
RaiseEvent ErrorReceived(Me, errMsg)
End Sub
Public Sub SendData(buffer() As Byte)
'ToDo: modify the code below and/or add desired code
'convert to a string that's human-readable
Dim data As String = String.Empty
If buffer IsNot Nothing Then
For i As Integer = 0 To BytesReadMessage Step 1
If Not String.IsNullOrEmpty(data) Then
data += " " 'append space
End If
'for testing, convert to a 2-digit HEX value
data += buffer(i).ToString("X2")
Next
'add newline
data += System.Environment.NewLine
End If
System.Diagnostics.Debug.WriteLine("data: " & data)
'for testing save to file
If Not String.IsNullOrEmpty(Filename) Then
'append data to file
System.IO.File.AppendAllText(Filename, data)
End If
'raise event
RaiseEvent DataReceived(Me, data)
'Note: "When receiving the message, the LIS (Laboratory Information Management System) host first judges the legality and type of the message and then replies accordingly."
'ToDo: A response needs to be sent for each message received (see documentation for information on how to create the appropriate message - "3 Communication Process and Message Example")
End Sub
Public Sub WriteToSerialPort(ByVal data As String)
Dim errMsg As String = String.Empty
Try
If Port.IsOpen Then
'convert string to Byte array
Dim hexArr As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
For Each hexVal As Byte In hexArr
'convert byte to byte array
Dim tempArr As Byte() = New Byte() {hexVal}
'write
Port.Write(tempArr, 0, 1)
'add 1 ms delay before writing next byte
System.Threading.Thread.Sleep(1)
Next
Else
errMsg = "Error: Port is not open. Please open the connection and try again."
Debug.WriteLine(errMsg)
Throw New Exception(errMsg)
End If
Catch ex As Exception
errMsg = "Error: " & ex.Message
Debug.WriteLine(errMsg)
Throw ex
End Try
End Sub
End Class
Below is an alternative version of method Port_DataReceived that uses ReadExisting() instead - however, it may not work in your situation.
Port_DataReceived (version that uses ReadExisting):
Private Sub Port_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
'ToDo: add desired code
'read SerialPort data
Dim data As String = String.Empty
data = Port.ReadExisting()
'data = Port.ReadLine
Debug.WriteLine("Port_DataReceived: " & data)
'raise event
RaiseEvent DataReceived(Me, data)
End Sub
Form1:
Add a Button (name: btnConnectDisconnect)
Double-click the button to add the event handler
Add a RichTextBox (name: RichTextBox1)
Form1.vb
Note: In the code below, you'll need to update helper.Connect("COM1") with the correct COM port.
Public Class Form1
Private helper As HelperSerialPort = New HelperSerialPort()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Disconnect()
If helper IsNot Nothing Then
'unsubscribe from event(s)
RemoveHandler helper.DataReceived, AddressOf Helper_DataReceived
RemoveHandler helper.ErrorReceived, AddressOf Helper_ErrorReceived
helper.Dispose()
helper = Nothing
End If
End Sub
Private Sub btnConnectDisconnect_Click(sender As Object, e As EventArgs) Handles btnConnectDisconnect.Click
If helper Is Nothing Then
'create new instance
helper = New HelperSerialPort()
End If
If btnConnectDisconnect.Text = "Connect" Then
'clear existing data
RichTextBox1.Clear()
'ToDo: change to your desired COM port
helper.Connect("COM1")
'subscribe to event(s)
AddHandler helper.DataReceived, AddressOf Helper_DataReceived
AddHandler helper.ErrorReceived, AddressOf Helper_ErrorReceived
'set text
btnConnectDisconnect.Text = "Disconnect"
btnConnectDisconnect.Refresh()
Else
Disconnect()
'set text
btnConnectDisconnect.Text = "Connect"
btnConnectDisconnect.Refresh()
End If
End Sub
Private Sub Helper_DataReceived(ByVal sender As Object, ByVal data As String)
'ToDo: add desired code
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss") & " - Helper_DataReceived: " & data)
'append data to RichTextBox
RichTextBox1.Invoke(New MethodInvoker(Sub()
RichTextBox1.AppendText(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") & " - " & data)
End Sub))
End Sub
Private Sub Helper_ErrorReceived(ByVal sender As Object, ByVal errMsg As String)
'ToDo: add desired code
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss") & " - Helper_ErrorReceived: " & errMsg)
'append error message to RichTextBox
RichTextBox1.Invoke(New MethodInvoker(Sub()
RichTextBox1.AppendText(errMsg)
End Sub))
End Sub
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
Disconnect()
End Sub
End Class
Resources:
Host Interface Manual
HL7 Version 2.3.1
Modem control signals

Blocking more folders and applications

As you can see here I block the directory called "cleo". If I have it in my folder I can't click connect. How can I check if, for example, "Cleo", "Images", "Logs" exist in browsed file. I don't think making multiple If statements would be good, is there any other way?
Private Sub connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connect.Click
Dim cleoPath As String
Dim filePath As String
filePath = System.IO.Path.Combine(TextBox2.Text, "gta_sa.exe")
cleoPath = System.IO.Path.Combine(TextBox2.Text, "cleo")
If File.Exists(filePath) Then
If Directory.Exists(cleoPath) Then
MsgBox("Pronasli smo cleo fajl u vasem GTA root folderu. Da se konektujete na server morate ga obrisati.")
Else
Dim p() As Process
p = Process.GetProcessesByName("samp")
If p.Count > 0 Then
MsgBox("Vec imate pokrenut SAMP - ugasite ga.")
Else
Try
Dim prozess As Process = Process.GetProcessesByName("samp")(0)
prozess.Kill()
Catch ex As Exception
End Try
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SAMP", "PlayerName", TextBox1.Text)
Process.Start("samp://193.192.58.55:7782")
Dim client As New TcpClient
client.Connect("193.192.58.55", 10924)
Dim sendbytes() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text)
Dim stream As NetworkStream = client.GetStream()
stream.Write(sendbytes, 0, sendbytes.Length)
End If
End If
Else
MsgBox("Da se konektujete morate locirati GTA San Andreas folder.")
End If
End Sub
End Class
You could use extension methods combined with a directoryinfo to check if any of a list of directory exists. Depending of if you just want a true/false return or if you need to process each directories (for instance, by adding a custom message with the name of the folders that prevent your application from continuing.
Public Module DirectoryInfoExt
<System.Runtime.CompilerServices.Extension()>
Public Function AnyExists(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As Boolean
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Any(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function GetExistingDirectories(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As IEnumerable(Of String)
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Where(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
End Module
An example the boolean return.
Dim BaseDirectory As String = "C:\Games\GTA"
Dim GamePath As New DirectoryInfo(BaseDirectory)
' Will not give the specific path that exists, only a Boolean if any of theses folder are found
Dim ModsFound As Boolean = GamePath.AnyExists("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
If Not ModsFound Then
'Connect
Else
' Do something
End If
An example using the list return to generate a custome message prompt stating the name of the specific folders found.
'This version gives a list instead.
Dim ModsFoundList As IEnumerable(Of String) = GamePath.GetExistingDirectories("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
Dim HasMod As Boolean = ModsFoundList.Count > 0
If HasMod Then
EvilModdedUserPrompt(ModsFoundList)
Exit Sub
End If
' Here, since HasMod is false, we can proceed with connection.
' Do connection
As for the EvilModdedUserPrompt method
Public Sub EvilModdedUserPrompt(ModsFoundList As List(Of String))
Dim OutputMessage As New Text.StringBuilder
OutputMessage.AppendLine("The following mods have been detected on your system:")
For Each Moditem As String In ModsFoundList
OutputMessage.AppendFormat("- {0}", Moditem)
OutputMessage.AppendLine()
Next
MessageBox.Show(OutputMessage.ToString)
End Sub

Object reference not set to an instance of object - vb.net

First a little background information: The purpose of this application is to capture images and save them automatically to a network directory that will be either created or appended using the input of the text box. This code DOES work on my computer (windows 7 home 64 bit). I've created it using microsoft visual basic express 2010.
However..... when attempting to run the application on a windows 10 tablet, I get the follow errors:
On form load:
An error occurred while capturing the image. The video capture will now be terminated.
Object reference not set to an instance of an object.
On button2_Click Event:
Object reference not set to an instance of an object.
Below is the entirety of the code.
Form2.vb
Public Class Form2
Public scanIsSet As Boolean
Private webcam As WebCam
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
webcam = New WebCam()
webcam.InitializeWebCam(imgVideo)
webcam.Start()
scanIsSet = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim CFGfile As String
Dim SaveDir As String
Dim imgIndex As Integer
Dim existingImages() As String
SaveDir = "C:\somepath\"
'save image to directory with index number
Try
imgCapture.Image.Save(SaveDir & OrderNumber.Text & "\" & CStr(imgIndex) & ".jpg")
Catch ex As Exception
MsgBox("error while accessing object imgCapture" & ex.Message)
End Try
imgIndex = imgIndex + 1
Else
Beep()
MsgBox("Please scan or type in order number first")
End If
End Sub
End Class
WebCam.vb
Imports System
Imports System.IO
Imports System.Linq
Imports System.Text
Imports WebCam_Capture
Imports System.Collections.Generic
Imports ZXing
Imports ZXing.OneD
'Design by Pongsakorn Poosankam
Class WebCam
Public scanz As Boolean
Public Sub setScan(ByVal x As Boolean)
scanz = x
End Sub
Private webcam As WebCamCapture
Private _FrameImage As System.Windows.Forms.PictureBox
Private FrameNumber As Integer = 30
Public Sub InitializeWebCam(ByRef ImageControl As System.Windows.Forms.PictureBox)
webcam = New WebCamCapture()
webcam.FrameNumber = CULng((0))
webcam.TimeToCapture_milliseconds = FrameNumber
AddHandler webcam.ImageCaptured, AddressOf webcam_ImageCaptured
_FrameImage = ImageControl
End Sub
Private Sub webcam_ImageCaptured(ByVal source As Object, ByVal e As WebcamEventArgs)
_FrameImage.Image = e.WebCamImage
If scanz = True Then
Dim BCreader As New ZXing.BarcodeReader
'BCreader.Options.TryHarder = True
Try
Dim resu As Result = BCreader.Decode(e.WebCamImage)
Form2.OrderNumber.Text = resu.Text
setScan(False)
Form2.Label2.Text = ""
Beep()
Catch ex As Exception
'do nothing
End Try
End If
End Sub
Public Sub Start()
webcam.TimeToCapture_milliseconds = FrameNumber
webcam.Start(0)
End Sub
Public Sub [Stop]()
webcam.[Stop]()
End Sub
Public Sub [Continue]()
' change the capture time frame
webcam.TimeToCapture_milliseconds = FrameNumber
' resume the video capture from the stop
webcam.Start(Me.webcam.FrameNumber)
End Sub
Public Sub ResolutionSetting()
webcam.Config()
End Sub
Public Sub AdvanceSetting()
webcam.Config2()
End Sub
End Class
As you can see toward the end of Form2.vb, I've wrapped imgCapture.Image.Save(SaveDir & OrderNumber.Text & "\" & CStr(imgIndex) & ".jpg") in a Try-Catch block because I suspect it's some sort of problems with the pictureBox objects. The try catch block does indeed catch the exception, but I still have no idea what the problem is, why it happens on the tablet and not the PC, or how to fix it.
I've found similar questions, but none with a solution I can make use of.
Since you are using a library, EasyWebCam, that is outdated and not compatible with Win10, I would suggest switching libraries. Other options out there:
DirectX.Capture
Windows.Media.Capture
I FOUND THE SOLUTION BUT I DON'T KNOW IF YOU NEED IT NOW ANYWAY THE PROBLEM IS IF YOU HAVE CHANGED THE PICTUREBOX NAME THEN IN REFENCES USE THE EXACT NAME YOU HAVE CHANGED TO. EXAMPLE IF I CHANGE ALL MY PICTUREBOX NAMES AS -
PictureBox_A1 , PictureBox_A2 ,... and so on then my refence should be as -
Dim r As DataRow
For Each r In t1.Rows
CType(Controls("PictureBox_" & r(2)), PictureBox).Image = bookedicon
Next
MY REFERENCE IS - "PictureBox_"

How to share a resouce (a serial port) with several threads

I currently have a program with 4 threads.
4 Threads are "Worker Threads" that each have a dedicated serial port that monitors a dedicated device. So Worker Thread 1 monitors Com port 1, Thread 2 monitors Com Port 2 etc.
All this all working fine. No conflicts.
However, the 4 worker threads all have to send commands to a 5th Comm Port as well, which is a communication link to a device that can powercycle the other devices.
I.E. they all have to share a specific resource, the 5th com port.
When they do send a command to this 5th shared each thread has to wait until the command has finished before continuing.
I've followed the coding example from Dan (thanks!) and tried to form a prototype test code.
This SEEMS to work.
I would appreciate a critical review of the code to see if I'm going in the right direction.
Apologies if I'm not explaining this very well as whilst I've used threads before. Handling a shared resource is new to me. Also I'm just getting to grips with how Stackoverflow works!!
Many thanks
A simplified solution using a shared instance of a resource and a lock.
Public Class Resource
Public Function Read() As String
Return "result"
End Function
End Class
Public Class ResourceUser
Private Shared resourceLock As New Object
Private Shared r As New Resource()
Public Function Read()
Dim res As String
SyncLock resourceLock
res = r.Read()
End SyncLock
Return res
End Function
End Class
Example usage:
Sub Main()
Dim t1 As New Threading.Thread(AddressOf DoSomethingWithResourceUser)
Dim t2 As New Threading.Thread(AddressOf DoSomethingWithResourceUser)
t1.Start()
t2.Start()
End Sub
Private Sub DoSomethingWithResourceUser()
Dim ru As New ResourceUser()
ru.Read()
End Sub
Here's another example more specific to serial comms. It uses a dictionary to keep track of physical comm resources and their relevant locks, so that you can do asynchronous access to different comm ports, but synchronize access to each single comm port.
Sub Main()
Dim c1 As New CommPortThreadSafe("COM1")
Dim c2 As New CommPortThreadSafe("COM2")
Dim c3 As New CommPortThreadSafe("COM1")
Dim t1 As New Threading.Thread(Sub() c1.Read())
Dim t2 As New Threading.Thread(Sub() c2.Read())
Dim t3 As New Threading.Thread(Sub() c3.Read())
' t1 and t3 can't be in critical region at same time
' t2 will be able to run through critical region
t1.Start()
t2.Start()
t3.Start()
End Sub
Public Class CommPort
Public Property Name As String
Public Function Read() As String
Return "result"
End Function
End Class
Public Class CommPortThreadSafe
Private Shared resourceLocks As New Dictionary(Of String, Object)()
Private Shared comms As New Dictionary(Of String, CommPort)()
Private Shared collectionLock As New Object()
Private commPortName As String
' constructor takes the comm port name
' so the appropriate dictionaries can be set up
Public Sub New(commPortName As String)
SyncLock collectionLock
Me.commPortName = commPortName
If Not comms.ContainsKey(commPortName) Then
Dim c As New CommPort()
Dim o As New Object()
c.Name = commPortName
' configure comm port further etc.
comms.Add(commPortName, c)
resourceLocks.Add(commPortName, o)
End If
End SyncLock
End Sub
Public Function Read()
Dim res As String
SyncLock resourceLocks(Me.commPortName)
res = comms(Me.commPortName).Read()
End SyncLock
Return res
End Function
End Class
To address your recent edits:
Threads A would all declare the comm port in the same way. Actually this is a benefit of this pattern (similar to multiton pattern) which works like a singleton when only one comm port is used. This code could be used in all threads:
Dim myCommPort As New CommPortThreadSafe("COM1")
The lock inside the read is going to synchronize access to COM1 because "COM1" (the name of the comm port) is actually the key to the Dictionary<string, object> used for locking. So when any thread reaches this code, keying with the same key, that region will be accessible only to a single thread because they all use the same key.
SyncLock resourceLocks(Me.commPortName)
res = comms(Me.commPortName).Read()
End SyncLock
As you saw, that string is set up in the constructor so as long as all the threads create their object passing the same string to the constructor, they will all have underlying indirect references to the same CommPort. The constructor can only create the instance if the name doesn't already exist in its dictionary:
If Not comms.ContainsKey(commPortName) Then
Dim c As New CommPort()
Here's another example usage with just one comm port:
Sub Main()
Dim ts As New ThreadStart(
Sub()
Dim c As New CommPortThreadSafe("COM1")
For i As Integer = 0 To 99
c.Read()
Next
End Sub)
Dim t1 As New Threading.Thread(ts)
Dim t2 As New Threading.Thread(ts)
Dim t3 As New Threading.Thread(ts)
Dim t4 As New Threading.Thread(ts)
t1.Start()
t2.Start()
t3.Start()
t4.Start()
End Sub
In this example we start 4 threads which each perform the code in the threadstart. There is a loop reading the comm port. If you test this out, you will see that it is thread-safe as long as the entire read takes place inside Read(), which you will need to develop of course. You may have another layer in which you are sending custom commands and waiting for a response. These two actions should both be inside a single SyncLock in each custom function. Thread B should use the same class if it's doing a similar thing.
FORM CODE FOR TESTING
Imports System.Threading
Public Class Form1
Private Worker(4) As jWorker '4 Worker Object
Public myWorkerThread(4) As Threading.Thread '4 runtime threads
Private Checker As jChecker '1 Checking Object
Public myCheckerThread As Threading.Thread ' Thread to check status of Resource
Dim MainThreadResouce As jResourceUser
'Assume the actual serial port is opened here
'so its available for access by the jResource Object.
'Pressing button 1 will start up all the threads
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'setup a another ResourceUser object here so can see one of the shared values from the form.
MainThreadResouce = New jResourceUser
'Setup and start worker threads - basically these do work and regularly
'send commands to a shared resource
For I = 1 To 4
Worker(I) = New jWorker
Worker(I).id = I
myWorkerThread(I) = New Threading.Thread(AddressOf Worker(I).doWork)
myWorkerThread(I).Start()
Next I
'Start Checking thread - regularly checks something in the resource
'please ignore this for now!
Checker = New jChecker
myCheckerThread = New Threading.Thread(AddressOf Checker.dochecking)
myCheckerThread.Start()
End Sub
End Class
========================
WORKER THREAD, MODELLING THE MONITORING THREADS
Imports System.Threading
Public Class jWorker
Private _id As Integer = 0
Private _workCount As Integer = 0
Private resourceUser As jResourceUser
Public workerStatus As String = ""
Public Property id() As Integer
Get
Return _id
End Get
Set(ByVal Value As Integer)
Me._id = Value
End Set
End Property
Public ReadOnly Property count() As Integer
Get
Return _workCount
End Get
End Property
Public Sub New()
resourceUser = New jResourceUser
End Sub
Sub doWork()
workerStatus = "Started"
Do Until False
Thread.Sleep(1000)
_workCount += 1
If _workCount Mod 5 = 0 Then
'THe line below would cause a bottleneck
'As it prevents the system trying to powercycle any other
'modems whilst its doing just one.
'resourceUser.PowerCycle(_id)
Debug.Print("W" & _id & ", Worker - Requesting Power OFF +++++++++++++")
resourceUser.Poweroff(_id)
Debug.Print("W" & _id & ", Worker - Waiting 10 secs for modem to settle")
Thread.Sleep(10000)
Debug.Print("W" & _id & ", Worker - Requesting Power ON")
resourceUser.PowerOn(_id)
Debug.Print("W" & _id & ", Worker - Finished Power cycle ------------")
End If
Loop
End Sub
End Class
===================
RESOURCE USER - TO CONTROL ACCESS TO SHARED RESOURCE
Public Class jResourceUser
'Variables for handling resouce locking
Private Shared resourceLock As New Object
Private Shared _resource As New jResource("Com1", "ON")
'keeps a status of which workers have signalled an OFF or ON via the Resource
'in the form of a string 11213141 (device number (1-4) - 1 for on, 0 for off
Private Shared _powerStatus As String
Public ReadOnly Property PowerStatus As String
Get
Return _powerStatus
End Get
End Property
Public Sub New()
_powerStatus = _resource.PowerState
End Sub
Sub PowerOn(ByVal WorkerID As Integer)
Debug.Print("W" & WorkerID & ", ResouceUser - requesting Lock for Power ON [" & _powerStatus & "]")
SyncLock resourceLock
_resource.TurnOn(WorkerID)
_powerStatus = _resource.PowerState
Debug.Print("W" & WorkerID & ", ResouceUser - Turned On, Device statuses " & _powerStatus & "]")
End SyncLock
End Sub
Sub Poweroff(ByVal WorkerID As Integer)
Debug.Print("W" & WorkerID & ", ResouceUser requesting Lock for Power OFF [" & _powerStatus & "]")
SyncLock resourceLock
_resource.TurnOff(WorkerID)
_powerStatus = _resource.PowerState
Debug.Print("W" & WorkerID & ", ResouceUser - Turned Off, Device statuses [" & _powerStatus & "]")
End SyncLock
End Sub
'Not going to work as it blocks the whole system when it could be
'reseting other modems.
Sub PowerCycle(ByVal WorkerID As Integer)
SyncLock resourceLock
Debug.Print("W" & WorkerID & ", ResourceUser - Requesting Power CYcle LockPower")
_resource.PowerCycle(WorkerID)
_powerStatus = _resource.PowerState
Debug.Print("W" & WorkerID & ", ResourceUser - Power Cycled")
End SyncLock
End Sub
Function CheckState() As String
SyncLock resourceLock
Return _resource.CheckState
_powerStatus = _resource.PowerState
End SyncLock
End Function
End Class
============
RESOURCE - FOR ACTUAL WORK ON SHARED RESOURCE
'THis code would directly handle interactions
'with one specific com port that has already
'been configured and opened on the main thread.
Public Class jResource
Private _ComPort As String
Private _state As String
Private _PowerState As String
Private _CheckState As String
'Record the com port used for this resource
Public Property ComPort() As String
Get
Return _ComPort
End Get
Set(ByVal Value As String)
Me._ComPort = Value
End Set
End Property
'Returns the a particular status of the resouce
Public ReadOnly Property CheckState As String
Get
'here I'd send a few command to the comm port
'pick u the response and return it
Return _state
End Get
End Property
'The connected serial port is used to power cycle serveral devices
'this property returns the state of all those devices.
Public ReadOnly Property PowerState() As String
Get
Return _PowerState
End Get
End Property
Public Sub New(ByVal name, ByRef state)
Me._ComPort = name
Me._state = state
Me._PowerState = "11213141"
Me._CheckState = "ON"
End Sub
'Simulate a off command sent by a worker
'via its resourceUser object
Public Sub TurnOn(ByVal intWorker As Integer)
'simulate some work with the com port
Dim myTimeOut As DateTime
myTimeOut = Now.AddMilliseconds(500)
Do Until Now > myTimeOut
Loop
'Set the status to show that Device is on.
_PowerState = _PowerState.Replace(intWorker & "0", intWorker & "1")
Debug.Print("W" & intWorker & ", Resource - issued TurnON, Device Statuses [" & _PowerState & "]")
End Sub
Public Sub TurnOff(ByVal intWorker As Integer)
'simulate some work
Dim myTimeOut As DateTime
myTimeOut = Now.AddMilliseconds(500)
Do Until Now > myTimeOut
Loop
'Here would send command to Com port
'Set the status to show that Device is Off.
_PowerState = _PowerState.Replace(intWorker & "1", intWorker & "0")
Debug.Print("W" & intWorker & ", Resource - issued TurnOFF, Device Statuses [" & _PowerState & "]")
End Sub
Public Sub PowerCycle(ByVal intWorker As Integer)
Debug.Print("W" & intWorker & ", Resource - issued PowerCycle, Device Statuses [" & _PowerState & "]")
'Here would send command to Com port
'Set the status to show that Device is Off.
_PowerState = _PowerState.Replace(intWorker & "1", intWorker & "0")
Debug.Print("W" & intWorker & ", Resource - issued TurnOFF, Device Statuses [" & _PowerState & "]")
'simulate some work - takes a while for device to turn off
Dim myTimeOut As DateTime
myTimeOut = Now.AddMilliseconds(10000)
Do Until Now > myTimeOut
Loop
'Here would send command to Com port
'Set the status to show that Device is Off.
_PowerState = _PowerState.Replace(intWorker & "1", intWorker & "1")
Debug.Print("W" & intWorker & ", Resource - issued TurnON, Device Statuses [" & _PowerState & "]")
'simulate some work
myTimeOut = Now.AddMilliseconds(10000)
Do Until Now > myTimeOut
Loop
'Here would send command to Com port
End Sub
End Class

find gsm modem com port using vb.net

how to find gsm modem com port using vb.net? i writing this code :
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM5")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 19200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CMGS=""+628988397877""" & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("SUCCESS" & vbCrLf & Chr(26)) 'SMS sending
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not (SMSPort.IsOpen = True) Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen = True Then
SMSPort.Close()
End If
End Sub
End Class
but in this code :
Dim SMSEngine As New SMSCOMMS("COM5")
i need to know which com port that my modem gsm was connected, so i need code that can automatically find com port, can someone help me please?
thank you very much.
nb : i use visual basic 2012 (vb.net)
like others said, you will have to loop all ports and check whether you can connect use Rate/port to connect to the GSM modem. Here is a library, it is c#, but you can download the source code to see how it works.
http://www.scampers.org/steve/sms/libraries.htm
The only way to do this automatically without having to either select the COM port in your program interface or hard code the port number is to attempt to open all available COM ports, and send each one some kind of status command and listen (with a short timeout period) for a reply that only the GSM modem would return. Of course, this means you may send weird commands to other serial devices, if any, that are attached to the computer, but I'm guessing in your case it will be the only serial port with anything attached.
See here for the function to get the list of serial port names on the current computer.
Here's the Code to Find Attached modems and their Attributes in vb.net.
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_POTSModem")
ComboBox1.Items.Clear()
For Each queryObj As ManagementObject In searcher.Get()
If queryObj("Status") = "OK" Then
modems = queryObj("Description")
baud = queryObj("MaxBaudRateToSerialPort")
Port = queryObj("AttachedTo")
da.rows.add(1)
da.rows(incount).item(1)=Port
da.rows(incount).item(2)=baud
ComboBox1.Items.Add(modems)
ComboBox1.SelectedIndex = ComboBox1.FindString("Nokia")
If ComboBox1.SelectedItem = "" Then
ComboBox1.SelectedIndex = ComboBox1.FindString("Samsung")
If ComboBox1.SelectedItem = "" Then
ComboBox1.SelectedIndex = 0
End If
End If
End If
intcount+=1
Next
You need to add reference to the System.management assembly and also import the namespace system.management.