Sandboxing an Assembly
If your application is loading an assembly and then executing code within that assembly you may want to “sandbox” that assembly and run the assembly in the “Internet Zone”. This will control access to local resources, such as the file system and the registry. To do this, the assembly must be loaded into an AppDomain, and this has the additional advantage that the assembly can be unloaded once execution is completed.
The following ‘using’ statements will be required for these code examples:
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
First, you need to create an evidence object which specifies the “Internet Zone”:
object[] hostEvidence = { new Zone(SecurityZone.Internet) };
Evidence intEvidence = new Evidence(hostEvidence, null);
The AppDomain can now be created and the assembly loaded into the AppDomain:
AppDomain ad = AppDomain.CreateDomain(“AddIns”, null);
TestLib.TestLib remoteWorker = (TestLib.TestLib)
ad.CreateInstanceFromAndUnwrap(
@”TestLib.dll”,
“TestLib.TestLib”,
false, // don’t ignore case
0, // binding attributes
null, // use default binder
null, // args passed to constructor (none)
null, // use culture from current thread
null, // no activation attributes
intEvidence); //evidence
In this case the assembly is loaded from a file called”TestLib.DLL”. By calling CreateInstanceFromAndUnwrap an instance of the class “TestLib” is created and through this instance methods in the class can be called:
double l;
l = remoteWorker.theMethod();
This assumes that the class TestLib has a method called ‘theMethod’ that takes no arguments and returns a double.
You might be tempted to apply the evidence to the AppDomain – the second parameter in CreateDomain is null in the code above but a reference to the evidence can be passed. However, when the AppDomain tries to load the assembly it will fail as the AppDomain has no access to the file system and so cannot load the assembly!