Last week, when I posted about failing to run in partial trust gracefully, the method I showed only worked if your main assembly could be loaded. However, if it has a minimum permission request that cannot be satisfied, your main method won't ever be called, and you won't be able to fail gracefully.
For instance, the following code:
If I compile this code to main.exe, and run it from a partial trust environment, the application bombs out with the following exception:
As I said above, this exception is thrown before Main ever gets to execute, so there's no way to setup a handler for this exception. So how can you display a nicer error to your users?
One easy way is to create a shim application that will attempt to load your entry point for you. Since your shim application won't have the declarative request on it, it should be able to load. And once it's loaded, we can simply catch the FileLoadException that the entry point is throwing, and recover by showing the error message to the user.
We'll want to be careful however, that we don't catch every FileLoadException, since we don't want to display our message if some other assembly happens to fail to load. One simple shim application would look something like this:
Now, instead of running main.exe, I run shim.exe instead. The shim wraps main.exe with a try...catch block, which handles the exception that occurs when main fails to load. The throw clause rethrows the exception if it wasn't a failure to load the main assembly, so that any installed unhandled exception filters (or a debugger if there are none) will get called.
There are a few problems with this approach. Assembly.GetEntryAssembly() will return shim.exe instead of main.exe, the shim application will be at the root of every call stack, and you have to ensure that your users call the shim instead of the main application.
Tomorrow, we'll try to address some of the inadequacies of this method, and solve the problem in a better way.