communicating with a scale using USB vb.net - vb.net

I have been given a project at work to write VB.net code that will communicate with a shipping scale using USB. Unfortunately I have never written anything to communicate with USB before so I have no idea how to go about this. I have searched the net and found plenty of ways to do it with C#. But everything I find with VB.net I cannot get to work. I came across this code which looked promising unfortunately I'm getting the error "System.Managermant.ManagementObject is not defined". I imported System.management and I still have the error. I need an example of how to communicate with a USB device
Imports System.Management
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim strDeviceName As String
Dim strQuotes As String
Dim arrDeviceNames As Array
Dim USBDevice As System.Management.ManagementObject
Dim objReturnCollection As System.Management.ManagementObjectCollection
'Dim ObjScope As New System.Management.ManagementScope("\\FullNameOfYourComputer\root\cimv2") 'This is optional. Can be used for remote connections.
Dim SearcherUSBDevicesCollection As New System.Management.ManagementObjectSearcher("Select * from Win32_USBControllerDevice")
Dim ReturnUSBDevicesCollection As System.Management.ManagementObjectCollection
ReturnUSBDevicesCollection = SearcherUSBDevicesCollection.Get
'Or
'Dim USBDevicesClass As New System.Management.ManagementClass("Win32_USBControllerDevice")
'Dim ReturnUSBDevicesCollection As System.Management.ManagementObjectCollection = USBDevicesClass.GetInstances()
For Each USBDevice In ReturnUSBDevicesCollection
strDeviceName = USBDevice.Properties("Dependent").Value.ToString()
strQuotes = Chr(34)
strDeviceName = Replace(strDeviceName, strQuotes, "")
arrDeviceNames = Split(strDeviceName, "=")
strDeviceName = arrDeviceNames(1)
Dim objSearcher As New System.Management.ManagementObjectSearcher("Select * From Win32_PnPEntity Where DeviceID = '" & strDeviceName & "'")
objReturnCollection = objSearcher.Get()
Dim objReturn As System.Management.ManagementObject
For Each objReturn In objReturnCollection
Me.ListBox4.Items.Add("Description: " & objReturn("Name").ToString())
Me.ListBox4.Items.Add("DeviceID: " & objReturn("DeviceID").ToString())
Next
Next
End Sub
End Class

Go to your project settings and add a reference to System.Management.

Related

Getting variables form text file, then setting a new variable

I'm creating a code for the computers at work. I had to make an "Install" program. I didn't know how to do it properly but I found a way to do it.
When I "Install" the program on a other computer I have my USB-stick and copy it to the local disk at the computer.
Now I start the program for the first time at their computer and this code run's
and then I got an error here because Program is not yet divined:
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim Pathproj As String = AppDomain.CurrentDomain.BaseDirectory
Dim Pathfile As String = Pathproj.Replace("bin\Debug\", "Bestanden\Locatie.txt")
Dim Program As String = System.IO.File.ReadAllText(Pathfile)
'Deze bestanden worden aangemaakt en er wordt automatisch een route ingezet.
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim lBibliotheek As String = System.IO.File.ReadAllText(Program & "Bibliotheek.txt")
Dim lExcel_autonummering As String = System.IO.File.ReadAllText(Program & "Excelbestand autonummering.txt")
Dim lLocatie_telbestanden As String = System.IO.File.ReadAllText(Program & "Locatie telbestanden.txt")
Dim lMapnamen As String = System.IO.File.ReadAllText(Program & "Mapnamen.txt")
Dim lOrderschijf As String = System.IO.File.ReadAllText(Program & "Zoek schijf.txt")
Because when the form2_load I do this and then I wan't to divine that string.
Public Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Locatie_05Kuipers As String
If System.IO.File.ReadAllText(Pathfile) = "" Then
'If System.IO.File.ReadAllText("C:\testing1\testing2\testing7\testing1\testing1\text.txt") = "" Then
Locatie_05Kuipers = InputBox("Vul hier de Locatie waar je start bestanden moeten staan. Bijvoorbeeld: K:\Inventor\Instalprogram\ ")
If System.IO.File.Exists(Pathfile) Then
System.IO.File.Delete(Pathfile)
End If
Dim objStreamWriter As StreamWriter
objStreamWriter = New StreamWriter(Pathfile)
objStreamWriter.WriteLine(Locatie_05Kuipers & "\03 - Locaties")
objStreamWriter.Close()
ButtonInstal.Visible = True
Exit Sub
Else
End If
So how or where do I need to put my strings?
You can save a path in your settings, and every time you need it, you can create the file and put your data in it.
For example:
Dim pathString As String = My.Settings.filePath
Dim fullPath = Path.Combine(pathString, "Locatie.txt")
If Not Directory.Exists(pathString) Then
Directory.CreateDirectory(pathString)
File.Create(fullPath)
Else
If Not File.Exists(pathString) Then
File.Create(fullPath)
Else
Console.WriteLine($"File {fullPath}already exists.")
End If
End If

sqldatareader which must be closed error but it has not been used?

All,
This is my code:
Public Class frmFindRoute
Private Sub frmFindRoute_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cmdroad As SqlCommand
Dim sdrroad As SqlDataReader
cmdroad = conRouteMapping.CreateCommand
cmdroad.CommandText = "Select title, uniqueref from road order by title"
sdrroad = cmdroad.ExecuteReader
PopulateListviewHeaders(lvwFromRoad, 1, sdrroad)
PopulateListview(lvwFromRoad, sdrroad)
sdrroad = cmdroad.ExecuteReader
PopulateListviewHeaders(lvwToRoad, 1, sdrroad)
PopulateListview(lvwToRoad, sdrroad)
sdrroad.Close()
End Sub
Private Sub cmbFind_Click(sender As Object, e As EventArgs) Handles cmbFind.Click
Dim cmdLanes As SqlCommand
Dim sdrLanes As SqlDataReader
cmdLanes = conRouteMapping.CreateCommand
cmdLanes.CommandText = "Select direction, number,uniqueref from lane where roadref='" & lvwFromRoad.SelectedItems(0).SubItems(1).Text & "'"
sdrLanes = cmdLanes.ExecuteReader
sdrLanes.Read()
FindRoute(sdrLanes.GetValue(2))
End Sub
Private Sub FindRoute(ByVal LaneRef As Guid)
Dim cmdDestRoad As SqlCommand
Dim sdrDestRoad As SqlDataReader
Dim cmdNextJunction As SqlCommand
Dim sdrNextJunction As SqlDataReader
cmdDestRoad = conRouteMapping.CreateCommand
cmdDestRoad.CommandText = "Select roadref from lane where uniqueref='" & LaneRef.ToString & "'"
sdrDestRoad = cmdDestRoad.ExecuteReader ' << error here
If sdrDestRoad.GetValue(0) <> lvwToRoad.SelectedItems(1).SubItems(0).Text Then
cmdNextJunction = conRouteMapping.CreateCommand
cmdNextJunction.CommandText = "Select tolane from junction where fromlane='" & LaneRef.ToString & "'"
sdrNextJunction = cmdNextJunction.ExecuteReader
Do While sdrNextJunction.Read
'FindRoute(sdrNextJunction.GetValue(0))
Loop
sdrNextJunction.Close()
End If
sdrDestRoad.Close()
End Sub
End Class
Where I've marked "error here" I get the error:
There is already an open DataReader associated with this Command which
must be closed.
I don't know why? I've already verified that cmdDestRoad and sdrNextJunction aren't used anywhere else in the solution. The data readers in form_load and find_click work fine.
I've also used breakpoints to confirm that it fails the first time it runs this section of code.
Mary's answer was correct. You can not have two open readers on a connection. I can't accept it as answer as it's a comment.
The line
sdrDestRoad = cmdDestRoad.ExecuteReader
Fails because a reader is already opened with the following line in cmbFind_Click:
sdrLanes = cmdLanes.ExecuteReader
The lines:
cmdDestRoad = conRouteMapping.CreateCommand
cmdDestRoad.CommandText = "Select roadref from lane where uniqueref='" & LaneRef.ToString & "'"
are not part of the problem. Opening a second command on the connection didn't cause the error. Trying to open a second reader did.

How can we make this code run with option strict on?

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lblSystemSerialNumbers.Text = SystemSerialNumber()
lblCpuIds.Text = CpuId()
End Sub
Private Function SystemSerialNumber() As String
' Get the Windows Management Instrumentation object.
Dim wmi As Object = GetObject("WinMgmts:")
' Get the "base boards" (mother boards).
Dim serial_numbers As String = ""
Dim mother_boards As Object = wmi.InstancesOf("Win32_BaseBoard")
For Each board As Object In mother_boards
serial_numbers &= ", " & board.SerialNumber
Next board
If serial_numbers.Length > 0 Then serial_numbers = serial_numbers.Substring(2)
Return serial_numbers
End Function
Private Function CpuId() As String
Dim computer As String = "."
Dim wmi As Object = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & _
computer & "\root\cimv2")
Dim processors As Object = wmi.ExecQuery("Select * from Win32_Processor")
Dim cpu_ids As String = ""
For Each cpu As Object In processors
cpu_ids = cpu_ids & ", " & cpu.ProcessorId
Next cpu
If cpu_ids.Length > 0 Then cpu_ids = cpu_ids.Substring(2)
Return cpu_ids
End Function
End Class
This code will retrieve the CPU id and the motherboard id. How do I ensure that this will work even when option strict is on.
Why this could be a problem?
Well, let's see. The type of wmi is Object. That wmi do not necessarily support methods like InstancesOf, and SerialNumber
So how can we pull this out?
I think object that we got from GetObject is not just pure object. I think we should ctype or direct cast it to a more appropriate type. That more appropriate type will support methods like InstancesOf, SerialNumber, etc.
However what are the appropriate types?
You could use the ManagementObjectSearcher from the WMI classes hosted inside the System.Management.dll assembly.
(And you need to add the appropriate reference).
In this way you could write the SystemSerialNumber as
Private Function SystemSerialNumber(computer As String) As String
Dim wmi = New ManagementObjectSearcher(computer & "\root\cimv2", "select * from Win32_BaseBoard")
Dim boards = New List(Of String)()
For Each board In wmi.Get()
Dim temp = board.Properties("SerialNumber").Value?.ToString()
If Not String.IsNullOrEmpty(temp) Then
boards.Add(temp)
End If
Next board
Return String.Join(", ", boards)
End Function
The CpuId function is a bit more complex because you want to set the Impersonate flags but it is still possible to write a method around the NET wrapper classes for WMI interfaces
Private Function CpuId(computer As String) As String
Dim cpu = New List(Of String)()
Dim options = New ConnectionOptions()
options.Impersonation = System.Management.ImpersonationLevel.Impersonate
Dim scope = New ManagementScope(computer & "\root\cimv2", options)
scope.Connect()
Dim query = New ObjectQuery("Select * from Win32_Processor")
Dim wmi = New ManagementObjectSearcher(scope, query)
For Each m As ManagementObject In wmi.Get()
Dim temp = m.Properties("ProcessorId").Value?.ToString()
If Not String.IsNullOrEmpty(temp) Then
cpu.Add(temp)
End If
Next
Return String.Join(", ", cpu)
End Function

Notes error: Could not open the ID file in lotus notes

Please somebody help me. I use Lotus Notes to send email with using vb.net but I got this error when I try to run. I already add references about interop.lotus.dll and interop.Domino.dll but it's still the same error. Please advice..
Line 115: If dsEmail.Tables(0).Rows.Count > 0 Then
Line 116: **s.Initialize("abcde!")** 'ERROR in THIS LINE
Protected Sub btnSend_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.ServerClick
Dim s As New Domino.NotesSession
Dim db As Domino.NotesDatabase
Dim doc As Domino.NotesDocument
Dim mimeEntity As Domino.NotesMIMEEntity
Dim mimeChild As Domino.NotesMIMEEntity
Dim header As Domino.NotesMIMEHeader
Dim stream As Domino.NotesStream
Dim sendTo As String
Dim connectionString As String = "Data Source=[hide];User ID=[hide];initial Catalog=[hide];Password=[hide]"
Dim objConn As New SqlConnection(connectionString)
objConn.Open()
Dim dsEmail = New DataSet
Dim CommTaskA As SqlCommand
Dim AdapTaskA As SqlDataAdapter
CommTaskA = New SqlCommand("select EMAILBLASTCCID, rtrim(ltrim(EMAILADDR)) EMAILADDR, SUBJECTEMAIL, EMAILTEMPLATE from [hide] where [MESSAGE_TIME] is NULL", objConn)
CommTaskA.CommandTimeout = 180
AdapTaskA = New SqlDataAdapter
AdapTaskA.SelectCommand = CommTaskA
AdapTaskA.Fill(dsEmail)
AdapTaskA.Dispose()
CommTaskA.Dispose()
objConn.Close()
If dsEmail.Tables(0).Rows.Count > 0 Then
s.Initialize("abcde!")
db = s.GetDatabase("[hide]", "[hide].nsf", False)
subjectEmail = dsEmail.Tables(0).Rows(0)(2).ToString
For x As Integer = 0 To dsEmail.Tables(0).Rows.Count - 1
doc = db.CreateDocument()
sendTo = dsEmail.Tables(0).Rows(x)(1).ToString
doc.ReplaceItemValue("SendTo", dsEmail.Tables(0).Rows(x)(1))
doc.ReplaceItemValue("Subject", dsEmail.Tables(0).Rows(x)(2))
mimeEntity = doc.CreateMIMEEntity
mimeChild = mimeEntity.CreateChildEntity
header = mimeEntity.GetNthHeader("Content-Type")
header.SetHeaderVal("multipart/related")
stream = s.CreateStream
stream.WriteText("<img src='" & dsEmail.Tables(0).Rows(x)(3) & "'>")
mimeChild.SetContentFromText(stream, "text/html", Domino.MIME_ENCODING.ENC_NONE)
stream.Close()
doc.Send(False)
objConn.Open()
CommTaskA = New SqlCommand("update [ZITA].[DEV].[EMAILBLASTCC_test] set [MESSAGE_TIME] ='" & DateTime.Now.ToString & "' where rtrim(ltrim(EMAILADDR)) = '" & sendTo & "'", objConn)
CommTaskA.CommandTimeout = 180
CommTaskA.ExecuteNonQuery()
CommTaskA.Dispose()
objConn.Close()
Next
End If
End Sub
Thank you for all your respond.. I found the answer
the problem because the user account Lotus Notes and my IIS Manager are different.
You must make your Lotus Notes IBM and Application Pool Identity in IIS Manager run with the same account.
It works for me. Thank You
Make sure the Windows environment variable PATH points to C:\Users\adventina.nababan\AppData\Local\IBM\Notes\Data\ too.
For further instructions on how to do this, please take a look at the question "Adding directory to PATH Environment Variable in Windows".

Visual Basic - system.nullReferenceException

So I'm still a bit of a newbie when it comes to programming, hence why I'm using visual basic. I'm getting this exception raised repeatedly, but the variables that vb is saying have unassigned values have been given values in my code. Can anyone point out where I'm going wrong with this?
EDIT: just a few more details: the file exists, I can read from it using just the ReadLine method, but I need to split the fields so I can compare the scores and get the highest 2 scores
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim srdFile As System.IO.StreamReader
Dim strLine As String
Dim strField(1) As String
Dim strName() As String
Dim strScore() As String
Dim i = 0
srdFile = New System.IO.StreamReader("HighScores.dat")
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(",")
strName(i) = strField(0)
strScore(i) = strField(1)
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i = i + 1
Loop
End Sub
Following two arrays are never initialized: strName and strScore
I don't know the logic, but one way would be to use a List(Of String) instead which does not need to get the correct size in the first place and can be resized. I would also use the Using-statement to dispose the stream properly:
Using srdFile As New System.IO.StreamReader("HighScores.dat")
Dim strLine As String
Dim strField(1) As String
Dim strName As New List(Of String)
Dim strScore As New List(Of String)
Dim i = 0
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(","c)
strName.Add(strField(0))
strScore.Add(strField(1))
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i += 1
Loop
End Using
Side-note: i recommend to set Option Strict to On by default.
By the way, here is a completely different approach doing the same but with LINQ:
Dim lines = From line In IO.File.ReadLines("HighScores.dat")
Where Not String.IsNullOrWhiteSpace(line)
Let fields = line.Split(","c)
Let name = fields.First()
Let score = fields.Last()
Select String.Format("{0}, {1}", name, score)
rtbOut.Text = String.Join(Environment.NewLine, lines)
I find this more readable.
Before you use an array, you need to assign a fixed array size in the computer memory locations. You can do this by initialising an array with the number of array elements. In your code, you have not allocated any memory to strName() and strScore() before using them, hence the code will throw an exception.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim srdFile As System.IO.StreamReader
Dim strLine As String
Dim strField(1) As String
Dim strName(10) As String ''fixed size array (Using List(Of T) is a better option)
Dim strScore(10) As String ''fixed size array (Using List(Of T) is a better option)
Dim i = 0
srdFile = New System.IO.StreamReader("HighScores.dat")
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(",")
strName(i) = strField(0)
strScore(i) = strField(1)
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i = i + 1
Loop
End Sub
You can also create a dynamic array. Please follow Resizing an array at runtime in VB.NET on Stackoverflow about dynamic array.