My program in vb.net often end abruptly. How to find end command? - vb.net

I think there is an end command somewhere that I miss and got called.
However, how to find it.
If I search for end then there are so many end. End sub, end function.
I just want the program to break just before abruptly end.
Is this because of some out of memory or what?
The program run in debug mode. Suddenly it ends. So it runs 100 threads and then the vb 2012 is still running but the program have stopped. As if someone press the stop button or some end statement reached.

Depending on your technology stack, try overriding the OnExit method:
protected override void OnExit(ExitEventArgs e) {
base.OnExit(e);
}
Set a break point on the base.onExit(e); line and then look in the call stack. Or if you aren't in the debugger, write to a message box the previously called method.

If you want to find End and ignore End Sub etc. you can search using regular expressions (Ctrl+F Alt+E)
End\r?$
Finds End at the end of a line. Interestingly, it's exactly the example in the MSDN regex page

Related

In VB.NET use a textbox as a log for which if statement it is beeing proccesed inside a sub

Hi i have a Sub that has multiple if statements in it.
Each if statement has a large loop that searches for specific files and text inside files.
I tried various ways to use a text box in order to get the information which if is currently proccessing at the time and i see that for some reason the ui is not refreshed until the sub finishes and so i see everytime in the textbox the last proceesed if message.
What do you think is the best way to handle it?
I hope that this has nothing to do with threads because threads are something that i am not familiar with !
I think using Application.DoEvents() is an easy choice. But I don't know if that would be the desired behavior.
If the use of Application.DoEvents() fails, another thread should handle it.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.doevents?view=netframework-3.5
I use this:
Public Sub logWithCrLf(tx As TextBox, s As String)
tx.AppendText(s & vbCrLf)
tx.Select(tx.TextLength - 1, 0)
tx.ScrollToCaret()
tx.Refresh()
End Sub
I see that it scrolls a bit smoother using tx.AppendText(s) than tx.Text &= s, which scrolls up to 0 then down to caret again.
(I write this as an answer to contribute with the tx.AppendText() recommendation)

Async event handler - flycapture from PointGrey

I am using Point Grey's FlyCapture API to drive some cameras.
In a public class, I implemented all the starting and initializing code ; in the following _cam refers to a ManagedGigECamera.
Because I have 16 cameras, I want the code to be as fast as possible, so I wanted to use tasks.
Here is the code I use:
_cam.StartCapture(AddressOf OnImageGrabbed)
.../...
Public Sub OnImageGrabbed(ByVal raw_image As ManagedImage)
Dim t As Task = Task.Run(Sub()
'save image to disk or whatever
End Sub)
t.Wait()
End Sub
The above gives -sort of- satisfaction. By viewing image timestamps, I can see that some images are saved seconds after they are grabbed, and even some images are skipped altogether...
I wanted to make sure each call to OnImageGrabbed would start a new task, and tried the following, but it crashes right away with 'object not set to an instance of an object' (can't really debug, the code is running on a remote machine)
_cam.StartCapture(AddressOf OnImageGrabbed)
.../...
Public Async Sub OnImageGrabbed(ByVal raw_image As ManagedImage)
Await Task.Run(Sub()
'save image to disk or whatever
End Sub)
End Sub
All in all, my questions are:
how can I run an event handler asynchronously ?
why, using the first code, do I get (what appears to be) random delays between each call
to OnImageGrabbed ? I mean the differences in time between image timestamps is never the same, and tend to increase on the long run (first few images are almost synchronized, but after 1 minute or so, each image is separated by more and more time). Memory leak ? GC ?
Thanks in advance for any hint !
EDIT:
In the end I changed the way the system works: I fire a software trigger on each camera using a timer, and each trigger is fired 'in parallel':
Parallel.ForEach(Of ListOfCameras)(SingleCamera,
Sub(aCamera, loopstate, num)
aCamera.FireTrigger()
End Sub)
Starting a task and then immediately blocking on it (via Wait) nets you nothing. You may as well just run the saving-image code directly.
The second example is actually asynchronous. You're probably getting an exception because the ManagedImage argument or one of its child objects is being disposed. Remember that the code raising the event has no idea that your code is asynchronous; it's up to you to copy out what you need from the event arguments if you're going to use it asynchronously.

VB.NET Service Skipping Over Sub Procedure

I'm writing a Windows Service in VB using Visual Studio 2010. The service is going to check for changes to a table in a database every minute or so. I have experience with VB6 but am new to both VB.NET and creating services, so I might be overlooking something obvious here. When the service is stopped, paused, started, or resumed, a sub procedure is supposed to be called. The problem is that the program skips right over the call to the sub procedure. I set break points at OnPause() and OnContinue() and stepped through the code, to confirm that the program is skipping right over the calls to AgentStopped() and AgentStarted(). What am I doing wrong?
Protected Overrides Sub OnPause()
Log.WriteEntry("Agent paused.") 'This is written to the log
AgentStopped() 'This line is skipped
End Sub
Protected Overrides Sub OnContinue()
Log.WriteEntry("Agent restarted.") 'This is written to the log
AgentStarted() 'This line is skipped
End Sub
Private Sub AgentStarted()
Log.WriteEntry("AgentStarted called.") 'This never written to the log
End Sub
Private Sub AgentStopped()
Log.WriteEntry("AgentStopped called.") 'This never written to the log
End Sub
As you understand, there is no way for the lines you imply to be skipped since the containing method is called. Something else is happening. I suppose the code you are showing is simplified. Right?
I would bet that either you are running a wrong version of your code by mistake, or on your real code an exception occurs inside the called methods (AgentStarted and AgentStopped).
In order to debug this, I would follow these steps:
Change the current log messages and add messages after the call to the functions
Protected Overrides Sub OnPause()
Log.WriteEntry("Agent pause beginning.")
AgentStopped()
Log.WriteEntry("Agent pause ending.")
End Sub
Protected Overrides Sub OnContinue()
Log.WriteEntry("Agent restart beginning.")
AgentStarted()
Log.WriteEntry("Agent restart ending.")
End Sub
If you see the new messages, you will be able to verify that you are actually running the right version of the code and not an older version deployed by mistake.
You should use exception handling with try - catch. I am not really sure (I have never used it), but perhaps using the UnhandledException event to get info for possible uncaught exceptions could be helpful. Another option would be to check the windows event log for errors occuring while executing a web service.
Hope I helped!

How to call another module without returning to the first one after completion?

This is probably the dumbest question I've ever asked here, but it's hard to find answers to things like this.
I have a program with a bunch of modules/subs that each calculate a different variable. They're pretty complex, so I like to keep them separate. Now I want an earlier module to skip to another module based on user input. I thought I could use the call (sub name) method for this, but then the program returns to where the call line was and continues on that module from where it left off.
Example:
Module 1:
Sub NewPracticeSub()
Call otherpracticesub
MsgBox ("We've gone back to this sub... :(")
End Sub
Module 2:
Sub otherpracticesub()
MsgBox ("We're in the other practice sub!")
End Sub
I don't want it to return to Module 1. What can I do to have it switch control to Module 2 without it then returning to complete Module 1 upon completion of Module 2?
I feel like I just used the most confusing language possible to explain all of this, but thank you for your help anyways!!
Edit: I know I used the words module and sub interchangeably, and I know they're different. I like to keep each sub (which are each very large in my program) in their own modules because it's easier to keep track of them, and easier to explain/demonstrate the application flow to other people.
I think all you're looking for is the command Exit Sub which will make the program leave the subroutine without continuing any further, But the way you usually want to do this is, rather than calling a Sub, rather call a Function that returns a boolean value.
So, for example:
Public Function MyFunc() as Boolean
....
If [good] MyFunc = True
Else MyFunc = False
End Function
Then you could do something along the lines of:
Sub MyCallingSub()
...
If MyFunc = True then Exit Sub
Else ...
End Sub
It just adds in A LOT more felxibility and ability to choose whether you want to continue further in your sub or not.
Hope that makes sense.
Other than using the ugly End statement which I will describe below (and strongly recommend you to avoid), I'm not aware of any way to circumvent the call stack. Even John's response necessarily returns to the calling procedure, and evaluates another statement to determine whether to proceed or end.
This may yield undesirable outcomes, which is why I hesitate to recommend it, in favor of properly structuring your code, loops, etc., with respect to the call stack.
In any case, here is how you can use the End statement within your child subroutines, without needing any sort of public/global variables. This still allows you the flexibility to decide when & where to invoke the End statement, so it need not always be invoked.
Sub NewPracticeSub()
Call otherpracticesub, True
MsgBox ("We've gone back to this sub... :(")
End Sub
Sub otherpracticesub(Optional endAll as Boolean=False)
MsgBox ("We're in the other practice sub!")
If endAll then End '## Only invoke End when True is passed to this subroutine
End Sub
Why I say this method should be avoided, via MSDN:
"Note The End statement stops code execution abruptly, without
invoking the Unload, QueryUnload, or Terminate event, or any other
Visual Basic code. Code you have placed in the Unload, QueryUnload,
and Terminate events of forms and class modules is not executed.
Objects created from class modules are destroyed, files opened using
the Open statement are closed, and memory used by your program is
freed. Object references held by other programs are invalidated.
The End statement provides a way to force your program to halt. For
normal termination of a Visual Basic program, you should unload all
forms. Your program closes as soon as there are no other programs
holding references to objects created from your public class modules
and no code executing."
It will always return but that doesn't mean its a problem. I suggest you use Exit Sub as follows:
Sub NewPracticeSub()
Call otherpracticesub
**Exit Sub**
'Nothing more can execute here so its no longer a worry
End Sub
Module 2:
Sub otherpracticesub()
MsgBox ("We're in the other practice sub!")
End Sub

vb.net: Jump out of exceptioned function

I am just reworking my VB6 in .NET.
I have a function that is called NonNullString(byval uAny As Object) As String
In VB6 I worked with a sqlite wrapper, and a recordset's member could be accessed by using
Dim sString$
sString = r("somefield")
(without ".Value")
I have really many of these fields, and I changed most of them to ".Value", but for some I forgot it.
An exception is therefore raised in the function NoNullString, and I am looking for a way to quickly jump out of the function in order to see what the caller was and improve the code.
F5 does not do the job.
Does anybody have any ideas?
Thank you!
Press CTRL+L to see call stack. From there you can navigate through the stack.
You can then use Set Next Statement (CTRL+F9) on the End Function of your errored function. Two times F10 to complete execution of this function. Repeat this step till you are in the scope where you think the error originated. Then, if you are on x86 (so you have Edit&Continue available), fix your code, and drag your currently executed line to the moment when this fix would occur. And then try running your function again.
Unfortunately, you cannot Set Next Statement outside of the current block function/sub, which I was going to suggest originally.