How to "catch" unhandled Exceptions - compact-framework

We've developed a .NET 3.5 CF Application and we're experiencing some application crashes due to unhandled exceptions, thrown in some lib code.
The application terminates and the standard application popup exception message box is shown.
Is there a way to catch all unhandled exceptions? Or at least, catch the text from the message box. Most of our customers simply restart the device, so that we're not able to have a look on the exception message box.
Any ideas?

Have you added an UnhandledException event handler?
[MTAThread]
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
// start your app logic, etc
...
}
static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = (Exception)e.ExceptionObject;
// do something with the info here - log to a file or whatever
MessageBox.Show(exception.Message);
}

I do something similar to what ctacke does.
private static Form1 objForm;
[MTAThread]
static void Main(string[] args)
{
objForm = new Form1();
try
{
Application.Run(objForm);
} catch (Exception err) {
// do something with the info here - log to a file or whatever
MessageBox.Show(err.Message);
if ((objForm != null) && !objForm.IsDisposed)
{
// do some clean-up of your code
// (i.e. enable MS_SIPBUTTON) before application exits.
}
}
}
Perhaps he can comment on whether my technique is good or bad.

Related

Plugin Development: Eclipse hangs when testing plugin

I am new to developing plugins, and was wondering what causes a test plugin to hang when started i.e. Eclipse is unresponsive.
I know that my code is working as I developed a voice recognition plugin to write to the screen what is said and when I open notepad everything I say is printed to notepad.
So I was wondering, am I missing something in the plugin life-cycle that causes the IDE to hang when my plugin is started?
package recognise.handlers;
public class SampleHandler extends AbstractHandler {
public SampleHandler() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
return null;
}
}
Does the start.startVoiceRecognition() need to be threaded?
Thanks in advance and let me know if you would like to see my manifest/activator etc.
Conclusion
Added a job separate to the UI thread
/*
* Start a new job separate to the main thread so the UI will not
* become unresponsive when the plugin has started
*/
public void runVoiceRecognitionJob() {
Job job = new Job("Voice Recognition Job") {
#Override
protected IStatus run(IProgressMonitor monitor) {
TakeInput start = new TakeInput();
try {
start.startVoiceRecognition(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// use this to open a Shell in the UI thread
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
}
As shown start.startVoiceRecognition() is running in the UI thread, and it will block the UI thread until it is finished and the app will be unresponsive during that time. So if it is doing a significant amount of work either use a Thread or use an Eclipse Job (which runs work in a background thread managed by Eclipse).
To unblock your UI you have to use Display thread.
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
MessageDialog.openInformation(shell, "Your Popup ",
"Your job has finished.");
}
});
return null;
}
You can use Display.getDefault().asyncExec() as mentioned above, so your UI will be unblocked, while your non UI code will be executing.

Windows 8 Metro Style Clipboard Exception

I have developed an application which reads clipboard data in DispatcherTimer Tick() method.
Every second the clipboard data is read.
The application throws no exception in development machine (in debug or relase mode), however if I publish the application on a Win RT Tablet device, I have an exception while reading clipboard, but strangely only in "snap view" mode.
in full view mode, it works without any problem.
The exception is:
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))".
The code looks like;
private async Task Populate()
{
try
{
var clipboardText = await this.GetTextFromClipboard();
.....
}
catch (Exception ex)
{
this.HandleException("Error occured while reading clipboard: ", ex);
}
}
private async Task<string> GetTextFromClipboard()
{
var dataPackageView = Clipboard.GetContent(); // Exception occurs here!!!
if (dataPackageView.Contains(StandardDataFormats.Text))
{
var clipboardText = await dataPackageView.GetTextAsync();
return clipboardText;
}
return string.Empty;
}
What is wrong here and why it happens only at Snap View mode?

Error in Windows 8 xaml Modern app with thread

I have following two methods. When user clicks on start button from ui, the step geoLocator_PositionChanged in geoLocator_PositionChanged method is fired and calls the other method geoLocator_PositionChanged.But when it comes to try block while executing the first statement it throws the following error:
"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"
private async void btnStartStop_Click_1(object sender, RoutedEventArgs e)
{
geoLocator.PositionChanged += geoLocator_PositionChanged;
}
async void geoLocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
MessageDialog msgdlg = null;
bool bDisplayDialog = false;
try
{
lblAltValue.Text = args.Position.Coordinate.Altitude.ToString();
}
catch
{
}
}
Any help how can I fix this issue ?
You try to access the UI-Thread from another one.
Try something like ths
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync
(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//HERE GOES THE UI ACCESS LIKE this.textbox.text = "MY AWESOME TEXT";
});

handling app that requires web service - dealing with EndpointNotFoundExceptions

I'm almost finished my first WP7 application and I'd like to publish it to the marketplace. However, one of the stipulations for a published app is that it must not crash unexpectedly during use.
My application almost completely relies on a WCF Azure Service - so I must be connected to the Internet at all times for my functions to work (communicating with a hosted database) - including login, adding/deleting/editing/searching clients and so forth.
When not connected to the internet, or when the connection drops during use, a call to the web service will cause the application to quit. How can I handle this? I figured the failure to connect to the service would be caught and I could handle the exception, but it doesn't work this way.
LoginCommand = new RelayCommand(() =>
{
ApplicationBarHelper.UpdateBindingOnFocussedControl();
MyTrainerReference.MyTrainerServiceClient service = new MyTrainerReference.MyTrainerServiceClient();
// get list of clients from web service
service.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(service_LoginCompleted);
try
{
service.LoginAsync(Email, Password);
}
**catch (Exception ex)
{
throw new Exception(ex.Message);
}**
service.CloseAsync();
});
EDIT:
My main problem is how to handle the EndpointNotFoundException in WP7 without the application crashing.
Thanks,
Gerard.
Your code should look like
LoginCommand = new RelayCommand(Login);
...
public void Login()
{
var svc = new MyTrainerReference.MyTrainerServiceClient();
try
{
svc.LoginCompleted += LoginCompleted;
svc.LoginAsync();
}
catch (Exception e)
{
svc.CloseAsync();
ShowError(e);
}
}
private void LoginCompleted(object sender, LoginCompletedEventArgs e)
{
((MyTrainerReference.MyTrainerServiceClient)sender).LoginCompleted -= LoginCompleted;
((MyTrainerReference.MyTrainerServiceClient)sender).CloseAsync();
if (e.Error == null && !e.Cancelled)
{
// TODO process e.Result
}
else if (!e.Cancelled)
{
ShowError(e.Error);
}
}
private void ShowError(Exception e)
{
// TODO show error
MessageBox.Show(e.Message, "An error occured", MessageBoxButton.OK);
}
Your code calls LoginAsync and then immediately CloseAsync, I think this will cause problems...

Slight problem with Google Finance API

Hello all I can't seem to log in with google finance api to my account and I don't know why. Here is my code
public static void main (String [ ] args)
{
FinanceService myService = new FinanceService("exampleCo-exampleApp-1");
try
{
myService.setUserCredentials("...#gmail.com","...");
}
catch (AuthenticationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And here is my error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at com.google.gdata.util.VersionRegistry.ensureRegistry(VersionRegistry.java:88)
at com.google.gdata.client.Service.initServiceVersion(Service.java:458)
at com.google.gdata.client.Service.<clinit>(Service.java:147)
at main.main(main.java:55)
line 55 is the one that starts out FinanceService
I figured it out with the help of reddit: christophermaness.com/a-problem-with-compiling-a-java-project –