Exceptions not caught in release build (WinForm desktop app, C#, VS 2010) - c#-4.0

I developed a desktop application, it's almost done but still contains some bugs which I'm eliminating.
I use a general [try...catch] block wrapped around my application
[STAThread]
static void Main()
{
try
{
program = new Program();
// ...
}
catch (Exception x)
{
// ...
MessageBox.Show(
message,
Resources.MESSAGEBOX_ERROR_CRASH_Caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
my Program class constructor being:
public Program()
{
// [...]
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// [...]
frmLogon = new Logon();
Application.Run(frmLogon);
}
to ensure that any unhandled exception will bubble all the way up the stack and is at least responded to with some communicative message box.
It works fine when I run the application under Visual Studio (debug mode), but when I deployed it and installed on my PC, it doesn't - that's what I get when the bug (which I've already identified, by the way) causes it to read from a null array
Why? It baffles me really. Why was it "unhandled"? It was my understanding that try...catch should work regardless of whether it's release or debug mode, otherwise what would be the point.

This is kind of old, but if you still need a solution, you need to handle some events, enclosing the entire thing in a try catch won't work. Do something like this:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.UnhandledException += ProcessAppException;
Application.ThreadException += ProcessThrException;
Application.Run(new MainForm());
}
private static void ProcessAppException(object sender, UnhandledExceptionEventArgs e)
{
XtraFunctions.LogException((Exception)e.ExceptionObject);
throw (Exception)e.ExceptionObject; //MessageBox in your case.
}
private static void ProcessThrException(object sender, ThreadExceptionEventArgs e)
{
XtraFunctions.LogException(e.Exception);
throw e.Exception; //MessageBox in your case.
}
When an exception isn't caught, it will go through one of those before displaying the exception dialog. So you have the option to override it and display a nice message of your choice.

Related

Why C#8 Default implementations of interface members will report an error

Why C#8 Default implementations of interface members will report an error?
public interface Logger
{
void Info(string message);
void Error(string message);
// C#8 Default implementations of interface
void Warn(string message)
{
// "interface method cannot declare a body" error message
}
}
and
.NET Core 3.0 is configured as shown in the screenshot.
This is a Resharper/Rider bug: https://youtrack.jetbrains.com/issue/RSRP-474628
The feature is sound and your setup is correct. Also the following works for me, i can compile and run the following in .Net Core 3
class Program
{
interface IDefaultInterfaceMethod
{
void DefaultMethod()
{
Console.WriteLine("I am a default method in the interface!");
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
Note though, i get your error in the IDE!! yet there was no error in the error window. However, it still compiles and runs so it is not C#8.. Seeing this is a sure-sign something else is the issue
In Short, this is likely a Resharper problem, when i suspended Resharper the false positive went away

C++ CLI Invoke issues

I have a MainForm class (as you'd expect, it is a form) that has a text box on it. I also have another class called 'Application_Server' That does a load of other stuff (not just form-background related, quite a lot of network based stuff etc.).
The Application_Server class runs in it's own thread, but needs to be able to update the controls on the form, for this question, we will stick with just the textbox.
The problem is that even though I am executing the command to set the text of the textBox control via 'Invoke' I am still getting the following exception during runtime:
Additional information: Cross-thread operation not valid: Control
'DebugTextBox' accessed from a thread other than the thread it was
created on.
What could be causing this? I am definitely invoking a delegate within MainForm.
Here are the relevant code segments (cut down for readability):
MainForm.h:
public ref class MainForm : public System::Windows::Forms::Form {
delegate void del_updateDebugText(String^ msg);
del_updateDebugText^ updateDebugText = gcnew del_updateDebugText(this, &MainForm::postDebugMessage);
private: void postDebugMessage(String^ message);
};
MainForm.cpp:
void EagleEye_Server::MainForm::postDebugMessage(String^ message)
{
Monitor::Enter(DebugTextBox);
if (this->DebugTextBox->InvokeRequired)
{
this->Invoke(updateDebugText, gcnew array<Object^> { message });
}
else
{
this->DebugTextBox->AppendText(message);
}
Monitor::Exit(DebugTextBox);
}
And finally, the code calling it:
void ServerAppManager::postDebugMessage(System::String^ message)
{
mainFormHandle->updateDebugText(message);
}
void ServerAppManager::applicationStep()
{
postDebugMessage("Starting\n");
// This is Run in seperate thread in MainForm.cpp
while (s_appState == ApplicationState::RUN)
{
postDebugMessage("Testing\n");
}
}
Thanks!
From background worker called bwSearch we do the call as following from the DoWork event handler:
private: System::Void bwSearch_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
//... logic
UpdateTxtOutput("Some message");
//... more logic
}
I have a RitchTextBox called txtOutput, also the windows form control containing this code is called frmMain, the UpdateTxtOutput is defined in three parts as follows:
delegate void UpdateTxtOutputDelegate(String^ text);
void UpdateTxtOutput(String^ text)
{
UpdateTxtOutputDelegate^ action = gcnew UpdateTxtOutputDelegate(this, &frmMain::Worker);
this->BeginInvoke(action, text);
}
void Worker(String^ text)
{
txtOutput->AppendText("\t" + text + "\n");
}
I managed to get it working by simplifying the method within the 'MainForm' class to:
void EagleEye_Server::MainForm::postDebugMessage(String^ message)
{
Monitor::Enter(DebugTextBox);
DebugTextBox->AppendText(message);
Monitor::Exit(DebugTextBox);
}
And then moving the 'Invoke' call to the method calling the delegate, not pretty but it works for now. I think the issue may have been caused by the form getting stuck inside an Invoke loop. I say this as I noticed that the form would lock up and stop responding after it hit the recursive Invoke statement.

Blackberry Thread Image from JSON

I am looking for a way to display images on my ListField from a background thread. First in my drawListRow i try this
path = (String) imagePaths.elementAt(index);
bit = connectServerForImage(path);
g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);
but can't scroll smoothly throughout the list, and they say do not do networking or other blocking operations on the UI. But i also try this
private class imgConnection extends Thread
{
public imgConnection() {
super();
}
public void run() {
try {
for (int i = 0; i < imagePaths.size(); i++)
{
final int index = i;
String path = imagePaths.elementAt(index).toString();
bit = connectServerForImage(path);
image.addElement(bit);
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.setSize(image.size());
subManager.add(_list);
screen.invalidate();
}
});
}
}
public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
bit = (Bitmap) image.elementAt(index);
g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);
}
but nothing happens. Any idea, comments.
You are right, i just started java development 2 weeks ago particularly BB development and i try this link. I want to add a background thread to download image after i got the path url from json return.
first thread:
_connectionthread = new Connection();
_connectionthread.start();
private class Connection extends Thread
{
public Connection()
{
super();
}
public void run() {
try {}
catch (Exception e) {}
}
}
second thread:
_imgConnectionThread = new ImgConnection();
_imgConnectionThread.start();
private class ImgConnection extends Thread
{
public ImgConnection() {
super();
}
public void run() {
try {
}
catch (Exception e)
{
}
}
}
how to update images on ListField?
Answer is based on code from - pastebin.com/90UKTHzP
Terrible code! It's really hard to read and undersand! It looks like you copy pasted several examples from different locations. Also you overriding default behavior with same behavior. Also MainScreen already has VerticalManagerField. Also you're adding list every iteration to manager which will cause IAE. And main one thread is depended on result of second one. They start at the same time, but getting json from server and it's processing could take longer time, so image thread most probably will finish his run without any result.
So main recommendation to fix it - read clean code book! Read more about java development - conventions, multithreading. Read about BB development - UI api, networking.
And finally - start only one thread to get and parse json. After you get it finished - start another thread to get images.
There some minor things that could save you more battery and processor time also - start loading images on demand - when it painted or going to be painted (user scrolls list).
By convention, Java class names start with a capital letter, so imgConnection should really be ImgConnection.
In your sample code, I don't see imgConnection being instantiated anywhere, and I don't see any call to Thread.start(), which is the way a thread i started. Without Thread.start() it is not surprising nothing is happening - the thread is never starting.

Why does this NOT cause crash? I am updating UI from other thread

This example is copied from a book on Android. As you can see from my question, I am new to Android and trying to understand. This application should crash but it does not (I am updating UI from another thread. Which is not allowed.It should cause a crash. It does not. Why?). My code is:
final ProgressDialog dialogue = ProgressDialog.show(this, "title", "message");
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(7000);
dialogue.dismiss();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
This is done in OnCreate function. I am confused with line - dialogue.dismiss(); Isn't that updating UI (dismissing dialogue) from another thread? Why does this app not cause segmentation fault?
Thanks.
the dismiss() method can be run safetly on any thread as described in the Android documentation.
public void dismiss ()
Since: API Level 1 Dismiss this dialog, removing it from the screen.
This method can be invoked safely from any thread. Note that you
should not override this method to do cleanup when the dialog is
dismissed, instead implement that in onStop().

Error Handling Strategy for Sandboxed SharePoint Solutions

I am looking to develop an error handling strategy for a SharePoint solution that makes use of sandboxed webparts. I was initially looking at a general exception handling approach based on this article, but this doesn't work for sandboxed webparts. Once an unhandled exception has been thrown in the sandbox, the user code service appears to take control, so that the exception handling in the base web part isn't reached. Are there any established error handling approaches for sandboxed solutions?
Is anyone aware of a method of determining when an unhandled exception has been thrown in a sandboxed webpart, if only to change the displayed error message to a more user friendly message? I would like to replace the standard "Web Part Error: Unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain: An unexpected error has occurred." message at very least.
Thanks, MagicAndi.
Actually, you can follow the approach suggested by the article you mentioned. You just have to provide safe overridables for all virtual properties and methods your descendant web parts are going to override. The patter can be described:
Override and seal every virtual property and method supposed to be overriden with code that can throw an exception.
Create a virtual counterpart of the overridable with the same prototype and call the base class from it if necessary. This is supposed to be overriden by your descendants.
Call the new overridable from the sealed member in a try&catch and remember the exception if caught there.
Rendering method either renders the usual content or the remembered error message.
This is a torso of the base class I use:
public class ErrorSafeWebPart : WebPart {
#region Error remembering and rendering
public Exception Error { get; private set; }
// Can be used to skip some code later that needs not
// be performed if the web part renders just the error.
public bool HasFailed { get { return Error != null; } }
// Remembers just the first error; following errors are
// usually a consequence of the first one.
public void RememberError(Exception error) {
if (Error != null)
Error = error;
}
// You can do much better error rendering than this code...
protected virtual void RenderError(HtmlTextWriter writer) {
writer.WriteEncodedText(Error.ToString());
}
#endregion
#region Overriddables guarded against unhandled exceptions
// Descendant classes are supposed to override the new DoXxx
// methods instead of the original overridables They should
// not catch exceptions and leave it on this class.
protected override sealed void CreateChildControls() {
if (!HasFailed)
try {
DoCreateChildControls();
} catch (Exception exception) {
RememberError(exception);
}
}
protected virtual void DoCreateChildControls()
{}
protected override sealed void OnInit(EventArgs e) {
if (!HasFailed)
try {
DoOnInit(e);
} catch (Exception exception) {
RememberError(exception);
}
}
protected virtual void DoOnInit(EventArgs e) {
base.OnInit(e);
}
// Continue similarly with OnInit, OnLoad, OnPreRender, OnUnload
// and/or others that are usually overridden and should be guarded.
protected override sealed void RenderContents(HtmlTextWriter writer) {
// Try to render the normal contents if there was no error.
if (!HasFailed)
try {
DoRenderContents(writer);
} catch (Exception exception) {
RememberError(exception);
}
// If an error occurred in any phase render it now.
if (HasFailed)
RenderError(writer);
}
protected virtual void DoRenderContents(HtmlTextWriter writer) {
base.RenderContents(writer);
}
#endregion
}
--- Ferda

Resources