Unhandled Exception: EventArgs in vb.net missing property "handled" - vb.net

I used the following code:
Sub AppStartup()
AddHandler AppDomain.CurrentDomain.UnhandledException,
Sub(sender As Object, args As UnhandledExceptionEventArgs)
Dim e = CType(args.ExceptionObject, Exception)
ShowMessage("Oops...", HandleErr(e), MessageBoxImage.Error)
End Sub
End Sub
and I don't get the property handled Although it appears this link is supposed to be his

Your link points at XAML article, your question is probably about WinForms.
Are you starting this inside VS? Please note that exception will first be handled by VS, and then by this handler. When you run as a standalone executable, it should work as expected. You don't need to set any e.Handled to anything.

While your question doesn't really make sense, I'd say its safe to say you are trying to implement an unhandled exception handler.
This article should have all the information you need.
http://msdn.microsoft.com/en-gb/library/system.appdomain.unhandledexception.aspx

Related

How do I prevent both narrowing and late binding?

This might be a dumb question, but I just turned on Option Strict for the first time, and I'm not sure what the best approach is here.
I have a bunch of dynamically created PictureBox controls, and I'm adding event handlers when they're created to handle their paint events. In the paint event, I need to access the ClientRectangle of the PictureBox. Notice that I've changed sender As Object to sender As PictureBox:
Public Sub Example(sender As PictureBox, e As PaintEventArgs)
AlreadyExistingRectangle = sender.ClientRectangle
AlreadyExistingRectangle.Inflate(-2, -2)
' Draw stuff in AlreadyExistingRectangle
End Sub
I need the AlreadyExistingRectangle for various reasons (though I suspect there are better solutions). The reason I'm using sender as PictureBox is because my paint events are kind of slow, and I thought it might speed it up, as sender.ClientRectangle would cause late binding otherwise. But now, narrowing occurs, because the delegate sub uses sender as Object.
So, is there a simple solution, or should I just allow late binding or narrowing? And if so, which is faster?
I think it'd be best if you created a variable in the Paint event handler where you cast sender to a PictureBox. Then you can wrap the whole thing in a Try/Catch block to catch the cast exceptions that DirectCast throws if sender is not a PictureBox.
Try
Dim senderPictureBox As PictureBox = DirectCast(sender, PictureBox)
'Do your stuff...
Catch ex As InvalidCastException
'Either do something here or just ignore the error.
End Try
Alternatively, since throwing exceptions is costly for your already, as you state it, slow code, you could use TryCast which instead of throwing an exception just returns Nothing if the cast fails (this is much faster performance-wise).
Dim senderPictureBox As PictureBox = TryCast(sender, PictureBox)
If senderPictureBox IsNot Nothing Then
'Do your stuff...
End If

Visual Basic Connect to Webcam and Save Picture to File

Most simply put, I want to connect to a built in web cam in my computer using visual basic, take a single picture, and save that in a file. I have spent about an hour or so looking for a reasonable way to do this, and have found a few suggestions. Unfortunately many the methods that I have tried seem unnecessarily complicated and I have yet to see one of them work on my computer. For example, I have tried using the icam class referenced in several places, where this code
Public Class Form1
Private Sub Snap()
Dim Webcam As iCam = New iCam
Webcam.initCam(PictureBox1.Handle.ToInt32)
Application.DoEvents()
If Webcam.iRunning Then
PictureBox2.Image = Webcam.copyFrame(PictureBox1, New RectangleF(0, 0, PictureBox1.Width, PictureBox1.Height))
End If
Webcam.closeCam()
Webcam = Nothing
End Sub
Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles PictureBox2.Click
End Sub
End Class
Threw this error:
An unhandled exception of type 'System.InvalidOperationException' occurred in facerecognition.exe
Additional information: An error occurred creating the form. See Exception.InnerException for details. The error is: Failed to initialize because CategoryName is missing.
While with some work I could probably get the class functioning as it is meant to, the issue remains that there is really no simple and clean solution to this that I know of. Does anyone have a better idea of how to do this?

Can I catch all possible errors with one message? Vb.net

The project I'm working on is almost ready to ship. Occasionally, I'll encounter an error that won't allow the program to continue running like an out of bounds or a memory limitation.
These kinds of errors
I've been fixing them as I find them, but I'm sure there are others. However, I'm leaving this position in a few days so I need the users to not encounter these.
Is there a way in Vb.net that anytime one of those errors wants to pop up, it can catch it with an message box to the user that says something like "Something really bad happened. Please restart program"?
If it's a winform, you can catch the errors by handling the Application.ThreadException event.
AddHandler Application.ThreadException, AddressOf UIThreadException
Private Shared Sub UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
' Handle event here and show message
' Exception is in t.Exception
End Sub
Make sure there's no error in this error handler. I don't think it'll catch exception in other threads.
You can use the Try statement, which is a simple way to handle error.
Here is a simple example:
Try
'Do something
Catch ex As Exception
MsgBox("Error occured")
End Try

AcessViolationException was unhandled VB.net

So I have this form that loads a page, and after the page is loaded I want to insert the source into RichTextBox1.Text
However after the page load the program crashes(?) and gives me this error
"An unhandled exception of type 'System.AccessViolationException' occurred in Awesomium.Windows.Forms.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
This is my code and it is worth mentioning that I am using awesomium for this!
Public Class Form1
Dim Thread As System.Threading.Thread
Dim html_source_code As String = ""
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
Thread = New System.Threading.Thread(AddressOf Load_Page)
Thread.Start()
End Sub
Private Sub Load_Page()
While html_source_code = ""
If WebControl1.IsDocumentReady Then
html_source_code = WebControl1.ExecuteJavascriptWithResult("document.documentElement.outerHTML").ToString()
RichTextBox1.Text = html_source_code
End If
End While
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Thread = New System.Threading.Thread(AddressOf Load_Page)
Thread.Start()
End Sub
End Class
Thanks in advance!
Here is your first clue...
Control.CheckForIllegalCrossThreadCalls = False
This is a pretty obvious red flag. You should never use this except perhaps for very specific debugging purposes, and for very good reason. Given that the remainder of your code is full of illegal cross thread calls, it's no wonder your program is crashing.
Every single line of code you have written that is executed in a worker thread is touching UI components. You cannot do this. See this post for examples : Cross-thread operation not valid
UI controls are continuously operated on by the main thread of your application. The main thread must be able to access them to handle their associated events, draw them to the screen, etc. If another thread is modifying their contents while the main thread is attempting to read or write to them then bad things happen.
Consider a text box that the main thread is attempting to draw to the screen. It obtains a reference to the location of the string that contains the textbox's text and, in the middle of reading the string, another thread modifies the string, invalidating the reference that the main thread is using. When the main thread tries to read, its existing reference now points to an invalid memory location and, voila, access violation.
In almost all circumstances you should never, ever set CheckForIllegalCrossThreadCalls to False. Leaving it set True will raise an exception, but it gives you the opportunity to see where the problematic code is and allows you to correct it. Setting it False simply hides the illegal call, which may or may not fail, and your application will be vulnerable to random, buggy failures when those illegal calls end up causing problems. Suggest you do some reading about how to write multithreaded .NET applications. A good start would be here : StackOverflow Search.
See also : How to: Make Thread-Safe Calls to Windows Forms Controls

vb.net - redirect output to form textbox

I am trying to read/use the output from a python program in my vb.net project so far I'm not getting any results. What I'd like to see is the python program run (just by itself first) and all of the output get redirected into a textbox.
I've looked at some other posts about this, but I'm either missing something or not understanding something, as all I'm getting is blank output.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim PythonPath = "C:\Python27\"
Dim strPath As String = Application.StartupPath
MessageBox.Show(PythonPath & "python.exe """ & strPath & "\Resources\import_logs.py"" ")
Dim start_info As New ProcessStartInfo(TextBox1.Text)
' Make the process and set its start information.
Dim process As New Process()
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
process.StartInfo.FileName = PythonPath & "\python.exe"
process.StartInfo.Arguments = """" & strPath & "\resources\import_logs.py"""""
process.StartInfo.UseShellExecute = False
process.StartInfo.CreateNoWindow = True
process.StartInfo.RedirectStandardOutput = True
'process.StartInfo.RedirectStandardError = True
AddHandler process.OutputDataReceived, AddressOf proccess_OutputDataReceived
process.Start()
process.BeginOutputReadLine()
End Sub
Public Sub proccess_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
On Error Resume Next
' output will be in string e.Data
' modify TextBox.Text here
'Server_Logs.Text = e.Data ` Does not display anything in textbox
MsgBox(e.Data) 'It works but I want output in text box field
End Sub
End Class
Eventually I'm going to pass arguments to the python script and I'd like to get feedback that I can then use (insert error into a database, email when it's done, etc), so I'd like it to capture the process while running and not just a data dump at the end.
Any help would be much appreciated.
First things first—it's no wonder you aren't sure what's wrong with your code, you're silencing all errors that could possibly help you to diagnose it. That's the only purpose of On Error Resume Next in VB.NET. That unstructured error handling was included only for backwards compatibility with the pre-.NET versions of VB and it's time to forget that it ever existed. You certainly don't want to use it in code. (I would say "in code that you're debugging", but all code is a potential candidate for debugging and ignoring errors is just dumb.)
Anyway, on to the specific problem. We know that the call to MsgBox works, but it doesn't work right when you start interacting with controls on your form. So something is falling apart there.
It turns out that the OutputDataReceived event is raised on an entirely different thread, a different one than was used to create the process and a different one than is running your application's UI. It actually just retrieves a thread from the system thread pool.
And that's where the problem lies: you cannot manipulate UI objects on a thread other than the one that created those objects (at least not without jumping through some hoops), which is precisely what your code tries to do here. In fact, you're probably swallowing an exception that would have rather obtusely informed you of this situation.
The simple fix is to set the SynchronizingObject property of the Process class to one of your UI components (like the form, or the specific control you want to output to). This forces all event handlers to execute on the same thread that created that component. At that point, your code should work fine, because you're not trying to do any cross-thread UI access. (Message boxes are not vulnerable to this because any thread can display a message box. You're not trying to access an existing UI object that is bound to another thread.)
Alternatively, you could handle the marshalling yourself in the event handler method through the use of delegates and the BeginInvoke method, but this seems like unnecessary work to me.