Tuesday, March 04, 2008

Code Access Security For Child AppDomain

I recently configured an existing application to use ClickOnce deployment. All seemed to go well until I tried to run the application, whereupon it threw an exception on a line that had previously been working perfectly:

AppDomain childDomain;

childDomain = AppDomain.CreateDomain(ChildAppDomainName);

//Following line throws exception

childDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);

The exception was:

{"Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."}

The application was configured to run as FullTrust. To cut a long and frustrating story short, It turned out that the security settings were not being propagated to the child AppDomain. I changed the code to the following:

AppDomain childDomain;

Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;

Evidence childEvidence = new Evidence(baseEvidence);

childDomain = AppDomain.CreateDomain(ChildAppDomainName, childEvidence, AppDomain.CurrentDomain.SetupInformation);

This allowed the child AppDomain to inherit the settings from the parent domain and everything worked as expected once more.