How to i get the SerialPort information of Desktop? - vb.net

There are two serialports in my computer.
How do I get the serialport information?
(I know about coding of Serialport, but I really want to know about Serialport of my Computer information)
is it possible to get the information about Serialport of my computer?
I'm coding in vb.net
is is possible in vb.net?
if it possible, please tell me how to do it.

which information do you want to have about the serial port?
using the MSComm control you can use the following function to determine if the port exists and if it's already in use or not:
Public Enum PortAttr
PortFree = 0
PortInUse = 1
PortUnknown = 2
End Enum
Public Function CheckPort(intPort As Integer) As PortAttr
On Error GoTo ErrorFound
With MSComm1
If .PortOpen Then .PortOpen = False
.CommPort = intPort
.PortOpen = True
CheckPort = PortFree
If .PortOpen = False Then .PortOpen = True
End With 'MSComm1
Exit Function
ErrorFound:
Select Case Err.Number
Case 8002 'port doesnt exist
CheckPort = PortUnknown
Case 8005 'port already in use
CheckPort = PortInUse
Case Else
MsgBox Err.Description, vbCritical, "Error " & CStr(Err.Number) & " on Port " & CStr(intPort)
End Select
On Error GoTo 0
End Function
You can then loop from 1 to 16 to see if any of these ports exist (usb converters could add extra ports)
For intIndex = 1 To 16
Select Case CheckPort(intIndex)
Case PortFree
intFree = intFree + 1
cboPort.AddItem "Com" & CStr(intIndex), intFree 'add the port to the "free" list
cboPort.ItemData(intFree) = intIndex
Case PortInUse
cboPort.AddItem "Com" & CStr(intIndex) 'add the port to the "in use" ist
End Select
Next intIndex

Use the MSComm control in Visual Basic .NET to access serial ports
Because no Microsoft .NET Framework classes exist to access the communications resources that connected to your computer, you can use the MSComm control in Microsoft Visual Basic 6.0. The MSComm control provides serial communications for your application by enabling the transmission and reception of data through a serial port. To implement basic serial communications by using a modem, follow these steps:
Start Microsoft Visual Studio .NET.
On the File menu, point to New, and then click Project.
Under Project Types, click Visual Basic Projects.
Under Templates, click Console Application.
In the Name box, type MyConsoleApplication, and then click OK.
By default, Module1.vb is created.
Right-click the MyConsoleApplication project, and then click Add Reference.
Click the COM tab, click Microsoft Comm Control 6.0 under Component Name, click Select, and then click OK.
Note To use the MSComm control, you must install the related COM components of Microsoft Visual Basic 6.0 on the same computer that has Microsoft Visual Studio .NET installed.
For more information about license issues when you use Visual Basic 6.0 controls in Visual Studio .NET, click the following article number to view the article in the Microsoft Knowledge Base:
318597 Errors when you use Visual Basic 6.0 controls in Visual Studio .NET
Replace the code in Module1.vb with the following code example.
Imports MSCommLib
Module Module1
Sub Main()
'New a MSComm control
Dim MSComm1 As MSComm
MSComm1 = New MSComm
' Buffer to hold input string.
Dim Buffer As String
' Use the COM1 serial port.
MSComm1.CommPort = 1
' 9600 baud, no parity, 8 data, and 1 stop bit.
MSComm1.Settings = "9600,N,8,1"
' Tell the control to read the whole buffer when Input is used.
MSComm1.InputLen = 0
' Open the serial port.
MSComm1.PortOpen = True
Console.WriteLine("Open the serial port.")
' Tell the control to make the Input property return text data.
MSComm1.InputMode() = InputModeConstants.comInputModeText
'Clear the receive buffer.
MSComm1.InBufferCount() = 0
' Send the attention command to the modem.
MSComm1.Output = "ATV1Q0" & Chr(13)
Console.WriteLine("Send the attention command to the modem.")
Console.WriteLine("Wait for the data to come back to the serial port...")
' Make sure that the modem responds with "OK".
' Wait for the data to come back to the serial port.
Do
Buffer = Buffer & MSComm1.Input
Loop Until InStr(Buffer, "OK" & vbCrLf)
' Read the "OK" response data in the serial port.
' Close the serial port.
Console.WriteLine("Read the OK response data in the serial port.")
MSComm1.PortOpen = False
Console.WriteLine("Close the serial port.")
End Sub
End Module
Press CRTL+F5 to build and run this project. You will receive the following output messages:
Open the serial port.
Send the attention command to the modem.
Wait for data to come back to the serial port...
Read the OK response data in the serial port.
Close the serial port.
To read the rest of this you can go here How to access serial and parallel ports by using Visual Basic .NET

Related

Weird Issue With Windows Service - Service Timing Out

Hi there I have piece of legacy (VS2010) Windows Service code that I have imported into VS2017 and is causing me severe frustration. This code has worked well for about the last 6 years, however when I carry out the install and attempt to start the service the SCM comes back with a timeout error. The OnStart code is as follows:
Protected Overrides Sub OnStart(ByVal args() As String)
'Instaniate the timer for the service
_serviceTimer = New Threading.Timer(New Threading.TimerCallback(AddressOf Tick), Nothing, 60000, 60000)
End Sub
The call back is:
Private Sub Tick(ByVal state As Object)
'Switch off the timer event whilst the code executes
_serviceTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
If Not _started Then
Startup()
_started = True
End If
Call ServerProcess()
'Re-enable the timer now that application code has completed
_serviceTimer.Change(_longInterval, _longInterval)
End Sub
I originally had the Startup process in the OnStart method, however removed it as an attempt at resolving this issue, however it has not made any difference. Method Startup is as follows:
Public Sub Startup()
Try
'Source these settings from the local config file
_appDataFolder = Utilities.GetSetting("AppDataRoot")
_configPathMapped = _appDataFolder & Utilities.GetSetting("ConfigPathMapped")
_logPath = _appDataFolder & "\" & utl.GetSetting("LogPath")
'Instaniate the timer for the service - Commented out after moving startup code from OnStart method
' _serviceTimer = New Threading.Timer(New Threading.TimerCallback(AddressOf Tick), Nothing, Timeout.Infinite, Timeout.Infinite)
'Initialise logging architecture
_logger = New aslLog.Logger(_configPathMapped & "nlog.config", _logPath, My.Application.Info.ProductName, My.Application.Info.Version.ToString)
_logger.SendLog("Started PSALERTS Schedule Server Service", NLog.LogLevel.Info, _serviceTimer, _checkInterval, Nothing)
'Determine if the cloned config files exists in the mapped config file folder
'We clone these files to a writable destination to allow us to overcome write restrictions ot the C: drive on the SPEN PTI Desktop model
If Not System.IO.File.Exists(_configPathMapped & "psaservermachine.config") Then
'Clone the app.config file in the config folder as psaservermachine.config
Utilities.CloneFile(_programFileLocation & "PSALERTSScheduleServer.exe.config", _configPathMapped & "psaservermachine.config")
End If
If Not System.IO.File.Exists(_configPathMapped & "nlog.config") Then
'Clone the nlog.config file
Utilities.CloneFile(_programFileLocation & "PSALERTSScheduleServer.exe.config", _configPathMapped & "nlog.config")
End If
'Determine the Oracle TNS Environment
'Check for the existence of the environment variable 'TNS_ADMIN'
If Environment.GetEnvironmentVariable("TNS_ADMIN") IsNot Nothing Then
'If TNS_ADMIN exists then we can continue with the application session
Else
Dim oraTnsPath As String = ""
'If it doesn't exist then we need to determine the Oracle information from the PATH environment variable
oraTnsPath = GetOraTnsPath()
If oraTnsPath <> "" Then
'Then create the TNS_ADMIN environment variable
Environment.SetEnvironmentVariable("TNS_ADMIN", oraTnsPath)
Else
'If no oracle client information exists then raise an error to this effect and exit the app
'informing the user that they need to install the Oracle client in order to use PSALERTS
Beep()
Throw New PSALERTSOracleConfigException(
"PSALERTS Oracle Configuration Error. PSALERTS Did not find a valid Oracle Client." & vbCrLf & vbCrLf &
"Please install a valid Oracle Client and try again." & vbCrLf & vbCrLf &
"If a valid Oracle Client is installed then ensure that the PATH environment variable contains an entry for the Oracle Client." & vbCrLf & vbCrLf &
"For example - TNS_ADMIN=C:\oracle\12.1.0\Client_lite\NETWORK\ADMIN"
)
End If
End If
'Register the application
If Not Registered() Then
'Register the application
Register()
End If
If Registered() Then
'Clean/close any stray Excel processes from previous debug session
If _debugModeOn Then
CleanUpRedundantProcesses("EXCEL", "PSALERTS")
End If
'instantiate fresh excel session
_myXLApp = New Excel.Application
'Get the timer interval settings
_longInterval = CType(utl.GetSettingServerMachine(_configPath, "appSettings", "LongIntervalMillis"), Integer)
_initInterval = CType(utl.GetSettingServerMachine(_configPath, "appSettings", "InitialIntervalMillis"), Integer)
_refreshInterval = CType(utl.GetSettingServerMachine(_configPath, "appSettings", "InitialIntervalMillis"), Integer)
'Re-start the timer with periodic signalling as per the specified check interval
_serviceTimer.Change(_initInterval, _initInterval)
Else
_started = False
End If
Catch ex As Exception
_logger.SendLog("PSALERTS Schedule Server startup failure.", NLog.LogLevel.Error, ex)
Finally
End Try
End Sub
I use a similar technique for a number of similar services and they are running fine. Would appreciate some insight from any Windows Service gurus out there. Oh, I use WiX to carry out the install, again this is a well worn template for a number of similar such applications.
Kind Regards
Paul J.
Core: The very most typical errors:
Config problems: connection strings, faulty paths, etc...
Boot startup problem (good list - from FAQ)
Wrong password / login account when running as a real user with password.
Files missing or runtimes missing.
Permission problems (ACL / NT Privilege missing).
Maybe check this answer before the below.
UPDATE: Maybe have a look at this previous answer. Service startup timing issue. Also check my ad-hoc answer there in the same page.
Debugger: Other than that - nothing like stepping through the code with a debugger. I haven't done that in a long time. Deploy debug binaries and try? Windows 10 now hides messages from services - not sure how that affects debuggers: No more switching to Session 0.
I am not a service guru, but a deployment specialist. I'll just provide some links and see if that helps. Maybe I have not fully understood the whole problem. I tend to focus on the deployment side and not so much development side.
Ideas List / Debugging Check List: These are "ideas lists" for what could be wrong for applications in general - not just services (two first lists are similar - created some time apart):
Crash on launch
Desktop application won't launch
General purpose WiX / MSI links
Yes, these lists are very generic - too large to digest. Just skim the first two I think.
Debugging Tools: Also a reminder of the most useful service debugging tools: Event Viewer, Task Manager, Services.msc, Process Explorer (system internals), The NET command and SC.exe.
Good Service FAQ: https://www.coretechnologies.com/WindowsServices/FAQ.html
Your startup method should fire up a background worker and quickly return to the SCM that it has started. There is a system wide default setting of 30 seconds but honestly a proper service should respond in a few seconds.
Looking though your code, your connection to the database is probably the long pole causing the problem.

MS Access app shows "Enter parameter value" only on some machines

In an MS Access app I have a main form that has some buttons, one of which is a "Calendar" button.
When this button is clicked, a form that implements some kind of calendar should open.
The problem is that on some clean machines where I deployed this, instead of the calendar opening, an Enter parameter value dialog opens. On 3 other older instances it works without this problem.
On that form there is an unbound control that has default value =Now()
Office version 2013.
Where and how can I look for differences between these machines?
I can add code snippets or print screens to this question if you let me know what part exactly.
UPDATE:
The code in the open form altough before this get's executed the "Enter parameter value" dialog shows.
Private Sub Form_Open(Cancel As Integer)
Dim PrstAnz As Integer
On Error GoTo Form_Open_EH
If DCount("[prst]", "FLMT_AKTPRST") > 1 Then
'Es stehen mehrere Prüfstände zur Auswahl
Me.prst.Visible = True
Me.prst.RowSource = "FLMT_AKTPRST"
End If
Me![prst] = DLookup("[prst]", "FLMT_AKTPRST")
Me![ABeginn] = Date
InitPrst Me![ABeginn]
Exit Sub
All machines are Windows 7 x64 with Office 2013.
It's was about OS culture settings.

Read a Serial port in Excel 2013 using VBA [duplicate]

What is the best way to access a serial port from VBA?
I have a need for some of our sales reps to be able to send a simple string over the serial port from an action button in PowerPoint. I don't commonly use VBA, especially for anything like this. Normally I would turn it into an application of some sort, but I actually don't think the idea is that bad. It will be a handy tool for them to demo this device with while on a projector and talking to other sales guys and non technical people. Also, this sales guy will have no problem making small modifications to the VBA or PowerPoint presentation, but would not do as well with recompiling a .NET application.
I know we could do it through a batch file run from the presentation on the action, but that doesn't make me very happy. I figure we could probably access a COM object and run from there, but again I am not real up on the latest and greatest libraries to use in VBA, and it would also be nice to get a quick little primer in how to easily open, send and close the connection.
Since this will need to be run on multiple people's computers, it would be nice if it would be easily transportable to other machines. I should be able to say it has to run on Office 2007 and Windows XP. Compatibility with anything else would be a nice bonus though.
How should I go about handling this? Any good tips or tricks? Library recommendations?
The Win32 API handles the serial port as a file. You can access the serial ports directly by calling these API functions from within VBA. I had to do this for an old .NET application but VBA is no different.
Rather than hash it out for you on this site, here's a reference I've hung onto over the years. How to perform serial port communications in VBA
Sub Stinky()
Dim COM_Byte As Byte
Dim Received_Lines As Long
Dim Input_Buffer As String
Dim Output_Buffer As String
Dim Chars2Send As Long
Dim CharsRemaining As Long
Dim lfsr As Long
Open "COM7:9600,N,8,1" For Random As #1 Len = 1
Input_Buffer = ""
CharsRemaining = 0
Do
Get #1, , COM_Byte
If COM_Byte Then
If COM_Byte = 13 Then ' look for CR line termination
Debug.Print Input_Buffer, Now ' print it
Input_Buffer = "" ' and clear input buffer
' generate some output (9 characters)
lfsr = &H3FFFFFFF - 2 ^ (Received_Lines And 15)
Output_Buffer = "?########"
Chars2Send = 9
CharsRemaining = 9
For j = 0 To 2
Mid(Output_Buffer, 2 + j, 1) = Chr(Asc(Mid(Output_Buffer, 2 + j, 1)) + (31 And Int(lfsr / 32 ^ (2 - j))))
Next j
Debug.Print Output_Buffer
' show what I generated
Received_Lines = Received_Lines + 1 ' keep track of received line count
Else
Input_Buffer = Input_Buffer & Chr(COM_Byte) ' assemble output buffer
' process any characters to send
If CharsRemaining Then
CharsRemaining = CharsRemaining - 1
COM_Byte = Asc(Mid(Output_Buffer, Chars2Send - CharsRemaining, 1))
Put #1, , COM_Byte
End If
End If
End If
DoEvents
Loop
Close
End Sub
This works for me. I'm not sure if the OPEN actually sets up the Baud rate, as I first used TeraTerm.
My COM port is a USB connection to a BASYS3 prototyping kit. It is spewing characters at 9600, records of 36 characters ending with CR. I can randomly send commands of 9 characters. In the above code, I generate these command strings every time I have received a new line.
The way I chose which character to send is a little clunky: perhaps a better way is to have a character pointer and a number of characters, and when those go equal to set them both to zero.
Here is a brief module of VBA code that can send and receive messages on a PC serial port. This is not very elegant, but it is simple and should work on modern versions of Excel and Windows.
You are left on your own to expand the functionality and store or parse the messages. This just shows the low-level stuff to deal with the serial port.
The first 5 lines declare the millisecond "Sleep" library function (based on Excel version).
The SerialPort() subroutine outlines the steps to open the port, transmit some data, receive some data, try again to receive some data (to show that it really does not run afoul of the "end of file" error), and close the port.
#If VBA7 Then ' Excel 2010 or later
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)
#Else ' Excel 2007 or earlier
Public Declare Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)
#End If
Public Sub SerialPort()
' open a COM port, transmit a message, gather results, close the port.
' open the COM port as file #1
Debug.Print "Open COM port 4"
Open "COM4:115200,N,8,1" For Binary Access Read Write As #1
transmit$ = Chr(2) + "Hello, World." + Chr(13)
receiveDummy$ = "~~~"
' transmit a message
Put #1, , transmit$
Debug.Print "Message sent."
' wait a bit for a response
Sleep 100
' check for received message
Debug.Print "Look for incoming message."
On Error Resume Next
Do While True
receive$ = receiveDummy$ 'dummy value
Input #1, receive$
If receive$ = receiveDummy$ Then Exit Do 'the string didn't change, so move on
Debug.Print receive$
Loop
On Error GoTo 0
' do it again to show that the empty input queue doesn't stop the flow
Debug.Print "Look again for incoming message (should not stop on error)."
On Error Resume Next
Do While True
receive$ = receiveDummy$ 'dummy value
Input #1, receive$
If receive$ = receiveDummy$ Then Exit Do 'the string didn't change, so move on
Debug.Print receive$
Loop
On Error GoTo 0
' close the serial port
Debug.Print "Close COM port."
Close #1
Debug.Print "Done."
End Sub

Connect to an available wireless network using VB.NET

Using VB.NET how do I connect to an available wireless network. I have been able to list all the available networks.
Assuming you are wanting to control the Windows biult-in wifi stack, you should be able to do it with the WlanConnect Function. A signature is availeble at pinvoke.net.
MSDN has a list of the articles pertaining to wifi here.
The MSDN page does not say whether this is the case, but an application might need elevated permissions to use this API...
If you have the WLAN profile saved in your PC, this approach is simple.
Sub connectTo(ByVal name As String)
Dim p = "netsh.exe"
Dim sInfo As New ProcessStartInfo(p, "wlan connect " & name)
sInfo.CreateNoWindow = True
sInfo.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(sInfo)
End Sub
'use the sub to connect to your AP. connectTo("myAP")
Otherwise, it is easier to use ManagedWifi or SimpleWifi dll libraries. Here is my code where I used SimpleWifi.dll to connect to a network with a passkey.

Ensure connection to a POSPrinter connected via COM

I need to make sure that the connection to a POS printer is successful before writing data to the database and then printing a receipt. The POSprinter is normally of type BTP 2002NP but may differ. The common thing is that they are all connected via COM-port and NOT usb, so no drivers installed at all on the client.
Can I send some kind of "ping" on a COM-port and check if a device is connected and turned on? Any help or suggestions are very much appreciated.
Additional information, the application is developed in VB.net and Visual Studio 2008
About all you can do is write out a character string to the com port and wait and see if your printer responds with a reply. However the string you write and the string you expect will depend on the printer itself.
Refer to the BTP 2002NP printers programming manual for examples (the first link in google that I looked at)
From looking at the manual an appropriate string to send to the printer is the "DLE EOT n" command which requests that the printer send back its current status.
As for other printers in the range, check out this list of drivers and manuals
btw, this is what i came up with in the end.
Public Function ComTest() As Byte()
Dim TXT As String
TXT = Chr(&H10S) & Chr(&H4S) & Chr(1) 'DLE EOT 1
If OpenCom() Then 'Connect to com
moRS232.PurgeBuffer(Rs232.PurgeBuffers.TxClear Or Rs232.PurgeBuffers.RXClear)
moRS232.Write(TXT)
moRS232.Read(1)
Return moRS232.InputStream
Else
Return Nothing
End If
End Function
the function returns 1 byte. i can then from the manual translate this byte into what state the printer is currently in. this probably works for all ESC/P printers.