Console.In.Peek() resulting in not enough storage is available to process this command - vb.net

I am trying to upgrade a winforms vs2005/.net2.0 project to vs2010/.net4.0. Users can print labels. During the print, if the user hits enter key multiple times, it needs to be discarded hence the following code is in place.
Friend Sub FlushKeyboard()
While Console.In.Peek() <> -1
Console.In.Read()
End While
End Sub
In vs2010 this piece of code is throwing the following error
System.IO.IOException was unhandled
HResult=-2147024888
Message=Not enough storage is available to process this command.
I am from web background so having a little tough time finding a solution for this issue at hand. How can i upgrade this piece to comply with vs2010 and then later to 2013?
update #1:
change the code to
While Console.KeyAvailable
Console.ReadKey(True)
End While
this is resulting in

Related

Finding a syntax error in a large VBA/MS Access project

I have a MS Access database that displays an error message about a SQL syntax error on launch. "Syntax Error in query. Incomplete query clause." It also shows another error a few seconds after I hit "OK" on the first one.
Here's the two errors: https://imgur.com/a/PesjIFk
But it doesn't tell me where the syntax error is. There are SQL statements in a bunch of different places all over this project. This is a really large project and it wouldn't be practical to just look through all the code hoping that I notice an error someplace. How can I find out where this error is?
EDIT: Ok, so apparently you have to have a keyboard that has a "Break" key on it in order to even find where the error is. Wow. Fortunately I happen to have one. Here's the code that Access takes me to if I press break when I see the error message. This code is for a subform of another form. It highlights the first line (Private Sub Form_Current()).
Private Sub Form_Current()
If NumEnums > 0 Then
CurrentEnum = val(Nz(bit_value_edit.value)) 'Update CurrentEnum to the currently selected enum
Call UpdateEnumsLabel(Me.Parent![enums label]) 'Update label
End If
End Sub
...and here's UpdateEnumsLabel():
Public Sub UpdateEnumsLabel(ByRef label As Control)
If NumEnums > 0 Then
label.Caption = "Enums: " & CurrentEnum & "/" & NumEnums
Else
label.Caption = "Enums: 0"
End If
End Sub
The definition for CurrentEnum:
Public CurrentEnum, CurrentPort, CurrentFile, CurrentGroup As Long
I'm thinking that this error is unrelated to the code in Form_Current(), but Access is highlighting that line because the error happens when the form is opened. But the form doesn't contain anything that uses a query, so I'm confused as to what query Access has a problem with.
When the error Message pops up, Use Control+Break. It will take you to the line causes the issue.
You should also open a module and form the debug option in the VBA editor select "Compile All Modules"
And since it appears to happening on open/load, you can check both the macros and the main modules to find anything that triggers on AutoExec.
Often ctrl-break will hit the line where you errored out. However, in the case of multiple “events”, and code without error handling, then often the error occurs in the routine that called the code, not the actual code that caused the error.
What I would do launch the application (hold down the shift key to prevent any start up code, or forms running).
Now that you launched the application, but without forms or code running, then check for an autoexecc macro (if there is one, check what code it attempts to run).
If there not an autoexec macro in use, then check under file->options->current database. In this view, you can look/see/determine what the name of the start-up form is.
Once you determined the start-up form (or start up module/code) called from autoexec macro, then you can simply add a blank code module, and place in your code the SAME command that is used to start your application.
So let’s assume no autoexec macro, and you determine that the start-up form is frmMain.
So now, we can launch the application (hold down shift key to prevent any start up code from running). Now, type into a new “test” standard code module the following code:
Sub MyGo
Stop
Docmd.OpenForm "frmMain"
End sub
So you type in above code, hit ctrl-s to save the above code. Now with your cursor anyplace inside of the above code, you simply hit F5 to run.
At this point you hit/stop on the “stop” command in the debugger. At this point, you then can hit f8 to step to the next line of code. If the form in question calls other code etc., you still be able to single step, and “eventually” you hit the line which causes the error.
While the application may be large, a simple look at the start up forms (and huts then the start-up code) means that you ONLY really need to trace and look at the start up code – not the whole application.

Adding delay in VB.Net & sorting error - 'Application' is ambiguous

I need to add a delay in my code for few seconds, for which I was using the following code:
Private Sub waitInMilliSeconds(ByVal interval As Integer)
Dim stpwt As New Stopwatch
stpwt.Start()
Do While stpwt.ElapsedMilliseconds < interval
' To allows UI to remain responsive and process other threads
Application.DoEvents()
Loop
stpwt.Stop()
End Sub
It was working fine until I included "Imports CANoe". After which I started getting error message, for line - Application.DoEvents(). Error message is :
'Application' is ambiguous, imported from the namespaces or types
'CANoe, System.Windows.Forms'.
Can someone please help me in sorting this problem? Or with an alternate way of adding delays?
P.S. :
I am a basic programmer & not an expert in VB.NET, so your comments
are very valuable to me.
I am using Microsoft Visual Basic 2010 Express edition.
I am using CANoe to send some CAN signals on CAN bus.
I want to insert a delay which will allow execution of other threads in
parallel (Ex: I have a handler which gets called whenever there is
data incoming from the COM port. I don't want this to stop when I call
a delay function)
Thanks.

Colleagues get error 5 in Excel-file with VBA, but same file works fine on my computer?

We have an Excel-file with a large amount of VBA behind it. The Excel-file works just fine on my computer, but so far 3 of my colleagues (non-IT'ers) have gotten this error:
Runtime error 5:
Invalid procedure call or argument
The error is located on this line, and I don't see why it is throwing an error there because it's just a simple Set (and it works perfectly fine on my computer):
Set MyButton = Application.CommandBars("Attributions").Controls.Add(Type:=msoControlButton, Before:=10)
We all have the exact same Excel-file. I even sent them my version of the file, in which everything is running fine and no errors happen, but even when they open my version of the file they still get the above error on the above line!
What exactly could cause this? We all have Office 2013 and updates are installed automatically. The problem started about 2 weeks ago with one colleague and since this week I heard from two other colleagues that they have the same problem. One even said it suddenly worked again after he moved to a different desk (which I doubt would have an influence) but shortly after, it started getting the error again.
I have absolutely no idea why they get the error, or what might cause it. Seeing as we now all have the same version and they still get the error, I am thinking it might have something to do with Excel itself but that's just my idea.
Does this sound familiar to anyone here? Or does anyone know what might cause this, and how it can be fixed?
Edit: a while ago I checked on my colleagues their computers to see if the CommandBar was present, and it was. Even then the error still happened.
I suggest you to use a function that checks if there is a CommandBar in your Application like this:
Function IsCommandBarValid(cbName As String) As Boolean
Dim i As Long
IsCommandBarValid = True
For i = 1 To Application.CommandBars.Count
If (Application.CommandBars(i).Name = cbName) Then
Exit Function
End If
Next i
IsCommandBarValid = False
End Function
Now, You can use it to see that your user have that CommandBar in his or her Application, then make it like this:
If (Not IsCommandBarValid("Attributions")) Then
Call Application.CommandBars.Add(Name:="Attributions")
End If
' And after this add your code
Set MyButton = Application.CommandBars("Attributions").Controls.Add(Type:=msoControlButton, Before:=10)
Invalid procedure call or argument (Error 5)
Some part of the call can't be completed. This error has the following causes and solutions:
An argument probably exceeds the range of permitted values. For example, the Sin function can only accept values within a certain range. Positive arguments less than 2,147,483,648 are accepted, while 2,147,483,648 generates this error.
Check the ranges permitted for arguments.
This error can also occur if an attempt is made to call a procedure that isn't valid on the current platform. For example, some procedures may only be valid for Microsoft Windows, or for the Macintosh, and so on.
Check platform-specific information about the procedure.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
MSDN Source Article

Capture Variable/Object Name causing the error

How can I capture the variable name or object name causing an error in VBA?
Ex
Sub test()
On Error GoTo Handler
i = 0
n = 1/i
Handler:
Select Case variablename
Case "n"
'do something................
The error is not being caused by a variable. The error is caused by the line of code that attempts to divide 1 by 0. The assignment doesn't actually happen.
The best way I've found to diagnose issues when I'm actively developing is to have Stop and then Resume in the error handler.
Public Sub func()
On Error GoTo ErrHandler
'... some code here ...
Exit Sub
ErrHandler:
Stop
Resume
End Sub
The way this works is, when there is an error VBA will break (pause the execution, show the instruction pointer arrow and yellow highlighting) on the Stop. You can step to the Resume and then once more to find out which specific line of code is causing the error.
Once you start to understand what errors you are encountering you can build individual If ... Then cases for them to handle each appropriately. When you are ready to release your code into a production environment (i.e., for other users), you would need to replace the Stop/Resume with an unexpected error handler that either logs it or displays it to the user.
While Blackhawk's answer works fine for a small example, I personally prefer to avoid modifying code to track down errors like that. If I'm working on a lot of files trying to track down a nasty bug, it's entirely possible that I might forget to remove any "special code" like Stop statements, etc. after I've finished debugging. If any such code makes it to production, that can be quite embarrassing for me. In addition, it can be annoying having to add this code to many different places in order to figure out where the error is happening in the first place (it's not always as obvious as in your example!).
For these reasons, I prefer to use the facilities provided by the VBA Editor. So:
Open the VBA Editor.
Go to Tools > Options.
Select the General tab and click the Break on All Errors radio button.
Click OK.
Now run your code and you'll notice that when it reaches this line:
n = 1/i
you'll get an error dialog saying what the problem is ("Run-time error '11': Division by zero") and you'll get the option to click the "Debug" button on the dialog, which will break execution at the above line and will highlight it in yellow.
Once you're done with your debugging and find the error that had been troubling you, you can go back to the VBA Editor options and revert the "Error Trapping" setting back to the default option ("Break on Unhandled Errors").
This way, you've done no changes to the code that you need to remember to revert before releasing the code and the actual operation to set/unset this behaviour only takes a few clicks.

Application crashes while reading Serial Ports in loop using .Net 2.0

I take a part on a project and after many tests, me and my colleagues feel little disappointed by our coding skills and methodology. The issue is the following:
The application must read data from some type of RS-485 devices connected on a single bus via one or multiple serial ports. However, these devices come from different manufactures so as a result, they have different connection settings, different command sets and return different data. Moreover, each serial port can handle none, one or multiple devices simultaneously.
Each of our custom COMPort objects contains a device list and each device contains the type and the device settings that are recommended. So, after loading all settings and building all objects, the application starts polling each device in each COMPort object list. Every time, before writing each command, the serial port buffers are emptied and its settings change (Baud-rate, Parity, Handshake) without closing and reopening the port. After every command, a Threading.Thread.Sleep(delay) is executed with variable delay, depending on the response time of each device (delay varies from 150ms to 800ms). After Sleep() ends, application Reads the serial port and gets expected data. After that, either if BytestoRead > 0 or BytestoRead = 0 or an Exception occurs(wrong data returned, error in checksums, etc.), this function returns and application continues to read the next device in the list.
So, application executes in an endless loop, reading all devices from start to end, until it finally ends when user stops it from UI (when the project is a Windows Forms) or when the service Stops (when the project is a Windows service). The application does not use DataReceived event because we faced a lots of trouble, so the Read procedure is done manually.
Finally, application has a global log file which is accessible from all objects and holds all usual and unusual events and each COMPort object has its own log file in which all valid read data are written. Moreover, each COMPort has a timer object which checks for daytime changes per second and everyday at midnight all log files close and new files are opened.
The main problem is that all this seems to work great but unfortunately the application stops writing to logs after 1-2 hours (most of the times after 1:58 minutes exactly on one client machine), then after some minutes it crashes, sometimes with Send or Don't send window and sometimes silently. The CPU load never exceeds 1% and private & virtual memory does not seem to have a leak because it doesn't grow.
I have to mention that this application is tested on 3 machines (Windows XP, Windows 2003), on the following situations: mixed types of devices, one type of device, no devices connected (using null modem cable on one development machine.) Even on the last situation, the application crashes silently. This leads me to the thought that the issue has nothing to do with the Read procedure because in the “no devices attached” scenario, there is no data to be read. Also, the project is built with VB.Net 2008 using .Net Framework 2.0.
EDIT : Below is a small summary of the Read, Write and Polling procedures. I wrote it on Notepad++ as an example because I don't have access to the real code right now, so excuse any syntax errors. The aim of this is to give a better explanation of the situation I describe above and nothing more.
Private deviceIndex as Integer = -1
Private deviceList as List(Of Devices)
Private serialPort as SerialPort()
Private Sub PollSensor()
Try
If (deviceIndex <> -1) And deviceIndex > deviceList.Count then
deviceIndex = 0
End If
With serialPort
If .IsOpen then
.DiscardInBuffer()
.DiscardOutBuffer()
' SerialPort attributes must change during runtime to suit device requirements.
' Some devices require for example 4800 BaudRate and some other 9600.
.BaudRate = deviceList(deviceIndex).BaudRate
.Parity = deviceList(deviceIndex).Parity
.Handshake = deviceList(deviceIndex).HandShake
' Write command to device, passing device specific response time.
' Some devices have for example 150ms response time and some other 800ms.
WritetoDevice(new Byte[] {01, 01}, deviceList(deviceIndex).ResponseTime)
End If
End With
Catch ex As Exception
' Log
End Try
End Sub
Private Sub WritetoDevice(ByVal command As Byte[], ByVal responseTime As Integer)
Try
serialPort.Write(command, 0, command.Length)
' Cause application to pause for time equal with the device response time.
Threading.Thread.Sleep(responseTime)
' If device response is regular, data may have been available in serial port.
If ReadDevice() = 0 then
' Poll next device
deviceIndex += 1
PollSensor()
End If
Catch ex As Exception
' Log
End Try
End Sub
Private Function ReadDevice() As Integer
Dim data as String = ""
Try
With serialPort
If .IsOpen then
If .BytesToRead() > 0 Then
Do
data += .ReadExisting()
Until .BytesToRead() = 0
' Do something with data
End If
End If
End With
Catch ex As Exception
' Log
Finally
' Continue with the next device in deviceList, ignoring the current device Read() result
' This happens because devices return faulty data too often and the polling must continue
Return 0
End Try
End Function
We have tried to use the Debug Diagnostics Tool 1.2 x86 but the results returned, do not help us to understand the source of the issue. Some of the exported reports contain the following, although all exceptions are handled in Try..Catch blocks:
- The following threads in ... are waiting in a WaitOne
- 6,25% of threads blocked
- System.ExecutionEngineException
- System.StackOverflowException
- System.OutOfMemoryException
- System.FormatException
- System.Threading.ThreadAbortException
Does anyone have a better idea on how the above scenario could work?
Feel free to criticize any of the above methods, because that will help us to become better.