Creating a Sandboxed Instance

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Fri, 10 Dec 2010 13:59:14 GMT Indexed on 2010/12/10 22:18 UTC
Read the original article Hit count: 320

Filed under:

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

© ASP.net Weblogs or respective owner

Related posts about .NET