Error to validate the length of a barcode read - vb.net

I have a project in Visual Studio 2005 with EMDK 2.6 with a MC1000 data collector over XP SP3 implemented on Windows CE.
I have this function within the project that gives me an error that I can't solve :
'Handle data from the reader
Private Sub HandleData(ByVal TheReaderData As Symbol.Barcode.ReaderData)
'MsgBox("Hello I'm reading ....")
If Me.DataTextBox.Text = "" Then
Me.DataTextBox.Text = TheReaderData.Text
' Here begins the verification of the length
If Len(Me.DataTextBox.Text) = Me.TextBox6.Text Then
' The length is ok
objStreamWriter.WriteLine(Me.DataTextBox.Text)
'Update the last read
Me.Label5.Text = Me.DataTextBox.Text
'Clean the field of the current read
Me.DataTextBox.Text = ""
'The counter of the code bars reads increases +1
Me.TextBox3.Text = Me.TextBox3.Text + 1
Else
Me.DataTextBox.Text = ""
MessageBox.Show("The length of the string read is not as expected", "Error !")
End If
End If
End Sub
The problem begins when I read a barcode with a length different to Me.TextBox6.Text (24 for example), the messagebox is shows ok, but inmediatelly another message box appear with the next error:
"StartRead Invalid Request Read already pending"
and the program continues fine, I need to eliminate this error because looks very bad.
Any help ?
Thanks in advance.

MessageBox does not stop your application from processing other events and it may be that a new barcode is read (or the same barcode is notified again) while you are still in the function processing the previous one.
Did you try to remove the call to MessageBox and check if this is still happening?
You may need to disable the reader before you call MessageBox.

Related

Retrieving weights from scales to excel

I have connected a weighing scale to my PC via an RS-232 to USB converter cable. My goal was to create a command button in excel 2007 that would place the weight from the scale into the selected cell. I got it to work using the following code in a userform.
Private Sub XMCommCRC1_OnComm()
Static sInput As String
Dim sTerminator As String
Dim Buffer As Variant
' Branch according to the CommEvent property
Select Case XMCommCRC1.CommEvent
Case XMCOMM_EV_RECEIVE
Buffer = XMCommCRC1.InputData ' Use Input property for MSComm
sInput = sInput & Buffer
If Worksheets("Settings").Range("Terminator") = "CR/LF" Then
sTerminator = vbCrLf
Else
sTerminator = vbCr
End If
If Right$(sInput, Len(sTerminator)) = sTerminator Then
XMCommCRC1.PortOpen = False
sInput = Left$(sInput, Len(sInput) - Len(sTerminator))
Select Case Left$(sInput, 2)
Case "ST", "S "
ActiveCell.Value = CDbl(Mid$(sInput, 7, 8))
ActiveCell.Activate
Case "US", "SD"
MsgBox "The balance is unstable."
Case "OL", "SI"
MsgBox "The balance is showing an eror value."
End Select
sInput = ""
End If
End Select
End Sub
Public Sub RequestBalanceData()
With Worksheets("Settings")
' Configure and open the COM port
If Not XMCommCRC1.PortOpen Then
XMCommCRC1.RThreshold = 1
XMCommCRC1.RTSEnable = True
XMCommCRC1.CommPort = .Range("COM_Port")
XMCommCRC1.Settings = .Range("Baud_Rate") & "," & _
.Range("Parity") & "," & _
.Range("Data_Bits") & "," & _
.Range("Stop_Bits")
XMCommCRC1.PortOpen = True
End If
' Send balance's "SI" (Send Immediate) command
' to request weighing data immediately
If .Range("Terminator") = "CR/LF" Then
XMCommCRC1.Output = "R" & vbCrLf
Else
XMCommCRC1.Output = "R" & vbCr
End If
End With
End Sub
I then created a command button with the following code.
Private Sub CommandButton1_Click()
UserForm1.RequestBalanceData
End Sub
When I click on the command button the weight is placed in the selected cell. However, this does not consistently happen. Sometimes when I click the button nothing will be placed in the cell, and I will have to click it multiple times until the weight is placed in the cell. I would like to fix this, but I'm not sure where to start. Is it a problem with the code itself, or is it more likely a problem with the converter or the scale itself?
Any help is appreciated.
Here is the scale: https://www.optimascale.com/product-page/op-915-bench-scale
Here is the converter cable: https://www.amazon.com/gp/product/B06XJZHCV8/ref=ox_sc_act_title_3?smid=A33N7O64F8FSDL&psc=1
Here is the tutorial I used for the code: http://www.msc-lims.com/lims/diybalance.html
Here is the ActiveX control from the tutorial that I used: http://www.hardandsoftware.net/xmcomm.htm
EDIT: I have done what Wedge has suggested and placed a Mgsbox sInput after my first End If. I have been getting inconsistent results. I am wondering if I need to change my scales sending format. The scale is currently set to sending format 4.
Here is the scale manual (sending formats are on page 21-23: https://docs.wixstatic.com/ugd/78eff6_e629ae5fe7004c7189060cca4bc7c3de.pdf
2ND EDIT:
I have connected my serial port to putty. My scale is in continuos sending mode. In putty the scale is consistently sending the following: ST,GS+ 0.00lb. However, when i try to enter the weight value in a cell, the message box sometimes displays that part of the data sent (ST,GS+ 0.00lb) has got cut off, or has been sent multiple times with one button press. Does anyone know how I would fix this?
3RD EDIT: It seems to me that the continuous sending mode (mode 4) my scale is set to is sending data too fast and is causing my code to mess up. I would like to try to make this work with the command request mode (mode 3), but I can't figure out how to properly parse the data string and place it into a cell. The sending format for command request mode is :
If anybody could help me figure out how to get this working I would greatly appreciate it.

OutOfMemory Exception when Control.invoke

I use a working thread to pump up messages , and use a event handler on UI thread to call Control.Invoke to show them on the RichTextBox.
Now found it would generate exception after 12 hours continuous running on target machine.
Log showed that:
System.OutOfMemoryException when System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
And here's part of my codes in Main Form:
Dim __lastMessage As String = ""
Private Sub historyMessageHandler(ByVal sender As messageHandler, ByVal e As String) Handles messengerReference.MessagePoped
'prevent invoking after form closed
If (Me.IsDisposed) Then
Exit Sub
End If
Dim __thisMessage As String = e
If (__lastMessage <> __thisMessage) Then
'---------------------------
' Once this message is not equal to last mesage , post on the history panel
'---------------------------
Me.Invoke(Sub()
RichTextBoxHistory.Text += (e & vbCrLf)
'-------------------------------------------
' Discard oldest message if count reached to prevent buffer overload
'-------------------------------------------
If (RichTextBoxHistory.Lines.Length > 64) Then
RichTextBoxHistory.Text = String.Join(vbCrLf,RichTextBoxHistory.Lines, 1, RichTextBoxHistory.Lines.Count - 1)
End If
'----------------------
' keep scoll on bottom
'---------------------
textBox.SelectionStart = textBox.Text.Length
textBox.ScrollToCaret()
End Sub)
Else
'-----------------------
'redundant message found , no need to show
'-----------------------
End If
__lastMessage = __thisMessage 'memorize last message
End Sub
Until now i considered two possible issues and did some tests:
The way to remove first line on TextBox is not appropriate.
There's some side-effect about Control.Invoke i don't know before.
For the first one , i tried to raise message event once a line per 1ms in my laptop, after 24 hours testing , it still works , no exception.
For the second reason , i read How to avoid leaking handles when invoking in UI from System.Threading.Timer? , and use perfmon.exe to monitor if handle leaks , it seems works fine so far, unused handles was collected by GC for sure.
Out of ideas now , is there other issue i missed?
Found a defect on this command:
RichTextBoxHistory.Text =
String.Join(vbCrLf,RichTextBoxHistory.Lines, 1,
RichTextBoxHistory.Lines.Count - 1)
If there's multi line message coming via argument e, it would delete only the very beginning single line per event raised , so that the heap usage of RichTextBox may keep growing on this situation , of course there's possible to occurs OutOfMemory in the end.
In this post, found the useful alternative calling to keeps fixed lines on RichTextBox, it can solve this problem.
RichTextBoxHistory.Lines = RichTextBoxHistory.Lines.Skip(RichTextBoxHistory.Lines.Length - 64).ToArray()

" A Sharing Violation occured" error when editing images in Paint using VB.NET

I have written a program in VB.NET to monitor file changes to recent saved screenshots taken from the tool.
I have a custom FileSystemWatcher class written (shared by someone on the internet,just customized) and have an instance invoked in my program.
The basic issue or objective is that when i capture a screen area using my program, I want it to immediately copy it over to clipboard. There are times when I would want to edit the captured image, in which case any editing made and saved, after saving the edited image must automatically be copied over to clipboard.
I use the below code to copy the image over to clipboard
'Subroutine to Copy the captured screenshot
'Added 15/09/2014
Sub CopyImageCapture(ByVal ImgPath)
Dim ThreadA As Thread
ThreadA = New Thread(AddressOf Me.MyAsyncTask)
'Setting ApartmentState.STA as this is needed for Clipboard related functionalities
ThreadA.SetApartmentState(ApartmentState.STA)
ThreadA.Start(ImgPath)
End Sub
'Threading to handle the Clipboard copy function
'Copy the screenshot to Clipboard
'Added 15/09/2014
Private Sub MyAsyncTask(ByVal ImgPath)
Clipboard.Clear()
Clipboard.SetImage(ImgPath)
End Sub
And when i choose to edit the image, the below code takes care to monitor the file changes
Sub MonitorFileChange(ByVal FolderPath, ByVal ItemName)
Try
Dim sFolder As String
Dim sFile As String
sFolder = FolderPath
sFile = ItemName
If IO.Directory.Exists(sFolder) Then
objWatcher.FolderToMonitor = sFolder
objWatcher.FileToMonitor = sFile
'objWatcher.NotifyFilter = (NotifyFilters.FileName Or NotifyFilters.Size)
objWatcher.StartWatch()
Else
MessageBox.Show("Folder does not exist!")
End If
Catch ex As Exception
MsgBox("Encountered an exception in MonitorFileChange subroutine. Details - " + ex.Message)
End Try
End Sub
'Subrountine to capture FileChanged events (esp. when captured image is edited in Paint and Saved)
'Works in sync with custom class 'clsFSW' for this purpose.
'ADDED: 15/09/2014
Private Sub objWatcher_FileChanged(ByVal FullPath As String) Handles objWatcher.FileChanged
'Try
Dim lastWriteTime As DateTime
lastWriteTime = File.GetLastWriteTime(FullPath)
Debug.Print(lastWriteTime)
If (lastWriteTime <> lastRead) Then
objWatcher.EnableRaisingEvents = False
'QuickCopy for changes files. BUG FIX
If (QuickSaveToolStripMenuItem.Checked) Then
Debug.Print("File Changed: " & FullPath & vbCrLf)
Dim tempI As System.Drawing.Bitmap = New System.Drawing.Bitmap(FullPath)
Dim tempI2 As System.Drawing.Bitmap = New System.Drawing.Bitmap(tempI, tempI.Width, tempI.Height)
CopyImageCapture(tempI2)
tempI.Dispose()
End If
lastRead = lastWriteTime
End If
'Catch ex As Exception
' MsgBox("Encountered an exception in objWatcher_FileChanged subrountine. Details - " + ex.Message)
' 'Finally
' 'objWatcher.EnableRaisingEvents = True
'End Try
End Sub
The problem is sometimes when I open the captured image and make quick saves or press save a couple of times real quick I get a "A Sharing violation occured" error
Can anyone help resolve the above issue? Which part of the code or logic is causing this to happen?
Also, if you check the above snippet, sometimes (havent seen any particular pattern) but the catch block in objWatcher_FileChanged is triggered and the error is "Parameter not found"
Can someone please help into this too?
Thanks in advance! Please let me know if any info more is required.
EDIT: Please note, the sharing violation error seems invoked from the Paint application itself and not my program, but why does it happen randomly, is a mystery to me. Is there nay loophole in the logic? Any alternative logic to what I want to achieve?
Try disposing tempI2. Windows may be locking the file used with tempI, and keeping it locked since it is assigned to tempI2. If so, it may remain locked until tempI2 is disposed.

Remove end character in a textbox without rewriting all the data

I am writing a program to communicate over the serial port. All data that is sent is mirrored back. Everything works fine except backspaces. When I hit the backspace button the only way I know how to remove the last character in the text box is to use a mid function then overwrite the current data with the new data. When a lot of data is inside the richtextbox it starts to flicker. I have tried using the richtextbox.text.remove function but I get this error. "Index and count must refer to a location within the string. Parameter name: count"
RichTextBox1.Text.Remove(RichTextBox1.TextLength, 1)
I have tried to throw some number into the function that does not cause it to error out but no data is removed from the richtextbox.
Here is the code that transmits data
KeyCharString = e.KeyChar 'stores key being pressed into KeyCharString
Try
SerialPort1.Write(KeyCharString) 'tx data for key being pressed
Catch ex As Exception
MsgBox(ex.Message) 'Displays error if serialport1 cannot be written to
End Try
If Asc(KeyCharString) = 8 Then 'If char is a backspace remove precious character and exit sub
RichTextBox1.Text = RichTextBox1.Text.Remove(RichTextBox1.TextLength, 1)
'RichTextBox1.Text = Mid(RichTextBox1.Text, 1, RichTextBox1.TextLength - 1)'Old code used to remove the character. Causes the richtextbox to flicker when rewriting the data
Exit Sub
End If
This is the code that receives data
receivedString = SerialPort1.ReadExisting.ToString
If Asc(receivedString) = 8 Then 'deletes the received data if it is a backspace
receivedString = ""
Exit Sub
End If
RichTextBox1.AppendText(receivedString) 'adds new data to the richtextbox
Is there a way to remove 1 character from the richtextbox without rewriting all the data inside it? Also, the richtextbox is read only.
The String.Remove method that you are using returns a String it does not do anything with the original string.
from MSDN Link:
Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.
Try this but I am not sure of the flicker:
RichTextBox1.Text = RichTextBox1.Text.Remove(RichTextBox1.TextLength - 1, 1)
or something like this:
RichTextBox1.SelectionStart = RichTextBox1.TextLength - 1
RichTextBox1.SelectionLength = 1
RichTextBox1.ReadOnly = False
RichTextBox1.SelectedText = ""
RichTextBox1.ReadOnly = True

VB IRC Client - writeStream only displays single word in IRC

Morning All,
I have been writing an ever so simple IRC client in visual basic. I have a niggly issue whereby when I am writing to the network stream. On other clients my message cuts off after the first space character. I'm sure this is something simple as the messages are being sent, receiving is fine and debugging the issue it wherever I read the message (i.e. if I debug.print the message being written to the stream it still includes all the words and spaces.) Here is my code.
Thanks in advance
'Send data to IRC Server
Sub Send(ByVal message)
Try
'Reformat message to IRC command
message = message & vbCrLf
Debug.Print(message)
'Convert message string into bytes
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(message)
'Write data to stream
ircStream.Write(sendBytes, 0, sendBytes.Length)
'Run test to see if the string sent matches the user input
Dim messageSent As String = Encoding.ASCII.GetString(sendBytes)
Debug.Print(messageSent)
'Display message on the screen( 0 = Sent Formatting )
PrintToScreen(message, 0)
Catch ex As Exception
'Catch error and display error message in the debug console
Debug.Print("Error Sending")
End Try
End Sub
You probably just need to prepend a ':' to your message like so...
PRIVMSG #chan_name :your message with spaces
By flushing, calling the flush function of the stream... Which (if I remember correctly) clears the data in the buffer, and writes it at the same time.
ircStream.Flush()