Saturday, March 10, 2012

“ScatterPuzzle” Surface SDK Sample Error

 

Today I was playing with some Surface 2.0 SDK samples and working on my personal Surface prototypes when I started to get a confusing error when I tried to run the ScatterPuzzle sample. Below a screenshot of the exception message:

image

The error is telling me that the invocation of the constructor of the main window is failing. However the reason is obscure. The exception details say that the problem is a mal formed path, but the line and position indication is telling me nothing relevant since it points to the application namespace declaration:

xmlns:sp="clr-namespace:ScatterPuzzle"

If you put a breakpoint in the constructor and debug the application, you will be able to follow the execution of the constructor step by step. In my case, I found out that the path to the images was not being retrieved correctly by the following piece of code:

The CommonFolder element corresponds to a custom class defined in the app that uses a KnownFolder list of Guids to know folders, in this case, Sample Pictures and Sample Videos public folders in Windows. The class uses the following method to retrieve the folder path based on the passed Guid:

The issue here is that the application is not handling the edge case when one or both of the folders don’t exist in the local machine. In my case, I had deleted the “Sample Pictures” folder from the public user’s “Public Pictures” folder, so when the application tried to load the list of images from the empty path, the exception was being thrown.

Of course the right solution is not only to create the missing folder on the local machine, but also to update the code to prevent the exception by checking the path being passed. In the main Window1.xaml.cs file, locate the LoadPuzzleList() method, which contains the code to load the files with extension “jpg” from the pictures folder. As you can see the code doesn’t check if the path set in the constructor is null or empty. Lets add the code required to perform this simple check:

Do the same for the videos path. Now if I run the application and one or both folders don;t exist on the machine, the app will run without exceptions and just display the existing videos or images, or by default an empty list if both folders are not present.

imageApp running with only videos

image

App running with pictures and videos

That’s all for now. I hope it helps and saves you time figuring out the reason of the exception if you were getting it, and also to remind you to always improve your code by checking this type of edge cases.

Cheers!

No comments:

Post a Comment