Export (0) Print
Expand All

TypeBuilder.AddDeclarativeSecurity Method

Adds declarative security to this type.

Namespace: System.Reflection.Emit
Assembly: mscorlib (in mscorlib.dll)

public void AddDeclarativeSecurity (
	SecurityAction action,
	PermissionSet pset
)
public void AddDeclarativeSecurity (
	SecurityAction action, 
	PermissionSet pset
)
public function AddDeclarativeSecurity (
	action : SecurityAction, 
	pset : PermissionSet
)

Parameters

action

The security action to be taken such as Demand, Assert, and so on.

pset

The set of permissions the action applies to.

Exception typeCondition

ArgumentOutOfRangeException

The action is invalid (RequestMinimum, RequestOptional, and RequestRefuse are invalid).

InvalidOperationException

The containing type has been created using CreateType.

-or-

The permission set pset contains an action that was added earlier by AddDeclarativeSecurity.

ArgumentNullException

pset is a null reference (Nothing in Visual Basic).

AddDeclarativeSecurity may be called several times with each call specifying a security action (such as Demand, Assert, or Deny) and a set of permissions that apply to the action.

The following code sample demonstrates the use of AddDeclarativeSecurity to add a 'demand' security action to a dynamic type.

using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Security.Permissions;

namespace CustomAttribute_Sample
{

   class MyApplication
   {
      // Create a dynamic type, MyDynamicClass, that demands
      // ControlEvidence permission.
      //
      private static Type CreateCallee(AppDomain appDomain)
      {
         // Create a simple name for the assembly.
         AssemblyName myAssemblyName = new AssemblyName();
         myAssemblyName.Name = "EmittedAssembly";
         // Create the called dynamic assembly.
         AssemblyBuilder myAssemblyBuilder =
            appDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
         ModuleBuilder myModuleBuilder = myAssemblyBuilder.DefineDynamicModule("EmittedModule");
         // Define a public class named "MyDynamicClass" in the assembly.
         TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("MyDynamicClass",
            TypeAttributes.Public);


         // Create a permission set and add a security permission
         // with the ControlEvidence flag.
         //
         PermissionSet myPermissionSet = new PermissionSet(PermissionState.None);
         myPermissionSet.AddPermission(
             new SecurityPermission(SecurityPermissionFlag.ControlEvidence));

         // Add the permission set to the MyDynamicClass type,
         // as a declarative security demand.
         //
         myTypeBuilder.AddDeclarativeSecurity(SecurityAction.Demand, myPermissionSet);


         // Define a private String field named "m_greeting" in the type.
         FieldBuilder myFieldBuilder = myTypeBuilder.DefineField("m_greeting",
            typeof(String), FieldAttributes.Private);
         // Define constructor.
         Type[] constructorArgs = { typeof(String) };
         ConstructorBuilder myConstructorBuilder = myTypeBuilder.DefineConstructor(
            MethodAttributes.Public, CallingConventions.Standard, constructorArgs);
         // Generate IL for the method.The constructor stores its argument in the private field.
         ILGenerator constructorIL = myConstructorBuilder.GetILGenerator();
         constructorIL.Emit(OpCodes.Ldarg_0);
         constructorIL.Emit(OpCodes.Ldarg_1);
         constructorIL.Emit(OpCodes.Stfld, myFieldBuilder);
         constructorIL.Emit(OpCodes.Ret);
         // Define property 'Greeting'.
         Type[] propertyArgs = {};
         PropertyBuilder myPropertyBuilder = myTypeBuilder.DefineProperty("Greeting",
            PropertyAttributes.None, typeof(string),propertyArgs);
         // Create the get_Greeting method.
         MethodBuilder getGreetingMethod = myTypeBuilder.DefineMethod("get_Greeting",
            MethodAttributes.Public|MethodAttributes.HideBySig|MethodAttributes.SpecialName,
            typeof(String), null);
         // Generate IL for get_Greeting method.
         ILGenerator methodIL = getGreetingMethod.GetILGenerator();
         methodIL.Emit(OpCodes.Ldarg_0);
         methodIL.Emit(OpCodes.Ldfld, myFieldBuilder);
         methodIL.Emit(OpCodes.Ret);
         myPropertyBuilder.SetGetMethod(getGreetingMethod);
         Type myCustomClassType = myTypeBuilder.CreateType();
         return(myCustomClassType);
      }

      [PermissionSetAttribute(SecurityAction.Demand, Name="FullTrust")]
      public static void Main()
      {
         Type customClassType = CreateCallee(Thread.GetDomain());
         Console.WriteLine("Trying to Create Instance with Default permission.");
         // Create an instance of the "MyDynamicClass" class.
         Object myCustomObject = Activator.CreateInstance(customClassType,
                                       new object[] {"HelloWorld!!!"});
         // Get 'Greeting' property.
         object objectGreeting =  customClassType.InvokeMember("Greeting",
            BindingFlags.GetProperty,
            null,
            myCustomObject,
            null);

         Console.WriteLine("Property Value: " + objectGreeting.ToString());
         Console.WriteLine("");


         // Create a permission set that's the same as the set
         // demanded by the MyDynamicClass class.
         //
         PermissionSet myPermissionSet = new PermissionSet(PermissionState.None);
         myPermissionSet.AddPermission(
             new SecurityPermission(SecurityPermissionFlag.ControlEvidence));

         // Deny the permission set, and then try to create another
         // instance of the MyDynamicClass class.
         //  
         myPermissionSet.Deny();

         Console.WriteLine("Trying to Create Instance after permission has been denied.");
         try
         {
             // Create an instance of the "MyDynamicClass" class.
             Object myNewCustomObject = Activator.CreateInstance(customClassType,
                                       new object[] {"HelloWorld!!!"});
         }
         catch( Exception e)
         {
            Console.WriteLine("Exception: Failed to create Instance");
            Console.WriteLine("'" + e.Message + "'");
         }
      }
   }
}

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft