using
System;
using
System.IO;
using
System.Reflection;
using
System.Security;
using
System.Security.Policy;
using
System.Security.Permissions;
// Create the strong name key file...
[assembly: AssemblyKeyFile("..\\..\\Dummy.snk")]
[assembly:AllowPartiallyTrustedCallersAttribute()]
namespace
APTCAAndAppDomains
{
class
Program
{
static void
Main
(
string
[] args)
{
new
Program().Go();
}
void
Go()
{
// Create the partially-trusted AppDomain
Evidence ev = new Evidence();
ev.AddHost(new Zone(SecurityZone.Internet));
AppDomain ad = AppDomain.CreateDomain("PTDomain", ev);
// Load the helper assembly
// (As noted below, ideally this should be in a
// different assembly, but we're doing an all-in-one
// special to keep the code simple)
string
assemblyName = this.GetType().Assembly.GetName().Name;
DangerousType dt = ad.CreateInstanceAndUnwrap(assemblyName,
"APTCAAndAppDomains.DangerousType"
)
as
DangerousType;
// Load the Proxy and let it do its thing!
Proxy p = new Proxy();
p.InvokeDangerousStuff(dt);
}
}
// -----
// Ideally these next two types would be in a separate assembly
// (so that the whole program isn't loaded in both AppDomains)
// but to keep the code simple we put them in here
// -----
// This is the proxy class that will invoke the
// internal method for us. It can have a full Demand
// as it will only be instantiated in the FullTrust domain
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public class
Proxy
{
public void
InvokeDangerousStuff(DangerousType dt)
{
dt.DoDangerousStuff();
}
}
// This is the "dangerous" type that needs to do things
// under the liberation of an Assert, and thus needs
// to be protected with an "internal" modifier
public class
DangerousType : MarshalByRefObject
{
// Here's where the dangerous stuff happens
internal void
DoDangerousStuff()
{
Console.WriteLine("In AppDomain " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("----------");
// Assert the right to do whatever we want
new
PermissionSet(PermissionState.Unrestricted).Assert();
StreamReader sr = File.OpenText("c:\\boot.ini");
Console.WriteLine(sr.ReadToEnd());
sr.Close();
}
}
}