Creating a Sandboxed Instance

In .NET 4.0 the policy APIs have changed a bit. Here's how you can create a sandboxed instance of a type, which must inherit from MarshalByRefObject:

static T CreateRestrictedType<T>(SecurityZone zone, params Assembly [] fullTrustAssemblies) where T : MarshalByRefObject, new()
{
	return(CreateRestrictedType<T>(zone, fullTrustAssemblies, new IPermission [0]));
}

static T CreateRestrictedType<T>(SecurityZone zone, params IPermission [] additionalPermissions) where T : MarshalByRefObject, new()
{
	return(CreateRestrictedType<T>(zone, new Assembly [0], additionalPermissions));
}

static T CreateRestrictedType<T>(SecurityZone zone, Assembly [] fullTrustAssemblies, IPermission [] additionalPermissions) where T : MarshalByRefObject, new()
{
	Evidence evidence = new Evidence();
	evidence.AddHostEvidence(new Zone(zone));
			
	PermissionSet evidencePermissionSet = SecurityManager.GetStandardSandbox(evidence);

	foreach (IPermission permission in additionalPermissions ?? new IPermission[ 0 ])
	{
		evidencePermissionSet.AddPermission(permission);
	}

	StrongName [] strongNames = (fullTrustAssemblies ?? new Assembly[0]).Select(a => a.Evidence.GetHostEvidence<StrongName>()).ToArray();

	AppDomainSetup adSetup = new AppDomainSetup();
	adSetup.ApplicationBase = Path.GetDirectoryName(typeof(T).Assembly.Location);

	AppDomain newDomain = AppDomain.CreateDomain("Sandbox", evidence, adSetup, evidencePermissionSet, strongNames);

	ObjectHandle handle = Activator.CreateInstanceFrom(newDomain, typeof(T).Assembly.ManifestModule.FullyQualifiedName, typeof(T).FullName);

	return (handle.Unwrap() as T);
}

Bookmark and Share

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website