One of our applications failed certification today because of an issue I should have known about. Even though the scenario in which an exception occurs is fairly easy, solving the problem properly involves a little work and a little thinking. Other blog entries have been written about this particular problem, although suggested solutions did not seem to work for me. Let me first show the original code:
Running this code and clicking the Start button on the phone while the MessageBox is visible results in the following exception when running with the debugger attached (it results in an application termination when running stand-alone):
The NavigationFailed event is raised. This is caused by the fact that the MessageBox returns when clicking the phone’s Start button with a return value of MessageBoxResult.Cancel. Since in the above code fragment, the Cancel button is used to navigate to some page, even though the application is supposed to go to the background in order to display the start screen on the phone, navigation fails. The interesting part is that the application does not have a clue that the user pressed the Start button on the phone. So some thinking is required to fix this issue.
Single stepping through the problematic method TurnCard_Click showed another behavior:
This at least made clear that indeed the call to the NavigationService caused the problem. To solve the problem, what can be done is protecting calls to the NavigationService by catching this particular exception:
This does solve the problem, although I don’t like it that an exception is thrown in a situation that the operating system should somehow prevent us against (maybe by returning some other value when the MessageBox returns without the user clicking on one of its buttons). If you want to have a little more flexibility, and don’t mind coding a bit more, there is another possible solution. Instead of using a MessageBox, you can make use of the Guide.BeginShowMessageBox method that is defined in the XNA Framework. This method is a bit more complex, but also much more flexible then its Silverlight counterpart. BeginShowMessageBox is asynchronous, which means that you need to take care with calling code that is supposed to run on the UI Thread.
The interesting code can be found in the EnteredAnswer method, where we retrieve the key the user entered in the message box. Since EndShowMessageBox returns a nullable integer, it has this nice way of using null in those cases where the user did not click any key (in other words, for instance when the message box is removed as a result of the application going to the background). So now we have a way of detecting if we can navigate (result has a value other then null). The sample code also sets a boolean variable messageBoxVisible, which is used in combination with PhoneApplicationPage.State to display the message box again when the user returns to the application. Hopefully this time the application will pass certification.