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
)

Parameters

action
Type: System.Security.Permissions.SecurityAction

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

pset
Type: System.Security.PermissionSet

The set of permissions the action applies to.

ExceptionCondition
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 null.

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.

NoteNote:

In the .NET Framework versions 1.0, 1.1, and 2.0, the declarative security attributes applied to a type by using this method are stored in the old XML metadata format. See Emitting Declarative Security Attributes.

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 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft