Vista: Application Recovery

Mon, August 21, 2006, 04:28 PM under Windows | Vista
Out of the many new native functions in Vista, two that I've been looking at using from managed code are the Application Recovery APIs.

There are 9 functions but two are the main ones: RegisterApplicationRestart and RegisterApplicationRecoveryCallback. These two serve two different, but complementary goals:
1. When your application crashes, it automatically restarts
2. When your application crashes, it gets a chance to save some recovery information

To demo this we need:
a) A new Windows Form application that has a button for crashing the application. Something like this:
// crash
private void button2_Click(object sender, EventArgs e)
{
int zero = 0;
int error = 5 / zero;
}
b) We must turn off .NET's exception handling. I've previously talked about global exception handling in .NET 2.0 but I never mentioned the ability to turn off plain exception catching, which we can do in our config file or in the Main function like this:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
c) We then need to re-declare in managed code the RegisterApplicationRestart like this:
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern uint RegisterApplicationRestart(string pszCommandline, int dwFlags);
Taking advantage of the API involves two lines of code in two different places.
d) First, we need to actually tell Vista that we want to be restarted (do this in your form_load or wherever else you see fit):
RegisterApplicationRestart("some_text_like_eg_pathname ", 0);

e) Second, on startup check if our application crashed last time (and use the string we passed to the API call):
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
this.Text = args[1];
}
Now run your app, and after you have called RegisterApplicationRestart, wait for 60 seconds before hitting the button that crashes your app. If you have windows error reporting enabled, you'll see the dialogs for checking for a solution, sending information and sending additional information. This is an interactive process where you can OK or cancel communications with winqual. Either way, once those dialogs are gone, your application will restart :-)

The other relevant restart functions that you could pinvoke are GetApplicationRestartSettings and UnregisterApplicationRestart.

In the next blog post, we'll look at the RegisterApplicationRecoveryCallback.
Comments are closed.