Export (0) Print
Expand All

TypeBuilder.AddDeclarativeSecurity Method

Adds declarative security to this type.

[Visual Basic]
Public Sub AddDeclarativeSecurity( _
   ByVal action As SecurityAction, _
   ByVal pset As PermissionSet _
)
[C#]
public void AddDeclarativeSecurity(
 SecurityAction action,
 PermissionSet pset
);
[C++]
public: void AddDeclarativeSecurity(
 SecurityAction action,
 PermissionSet* pset
);
[JScript]
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.

Exceptions

Exception Type Condition
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).

Remarks

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.

Example

[Visual Basic, C#, C++] The following code sample demonstrates the use of AddDeclarativeSecurity to add a 'demand' security action to a dynamic type.

[Visual Basic] 
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Security
Imports System.Security.Permissions

Namespace CustomAttribute_Sample
   Class MyApplication
      Public Shared Sub Main()
         Dim customClassType As Type = CreateCallee(Thread.GetDomain())
         Console.WriteLine("Trying to Create Instance with Default permission.")
         ' Create an instance of the "MyDynamicClass" class.
         Dim myCustomObject As Object = _
                  Activator.CreateInstance(customClassType, New Object() {"HelloWorld!!!"})
         ' Get 'Greeting' property.
         Dim objectGreeting As Object = _
                  customClassType.InvokeMember("Greeting", _
                  BindingFlags.GetProperty, Nothing, myCustomObject, Nothing)
         Console.WriteLine("Property Value :" + objectGreeting.ToString())
         Console.WriteLine("")
         ' Create a permission set.
         Dim myPermissionSet As New PermissionSet(PermissionState.None)
         ' Create Environment Read Permission on 'TEMP' folder.
         myPermissionSet.AddPermission(New EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP"))
         ' Deny all permissions on 'TEMP' folder.
         myPermissionSet.Deny()
         Console.WriteLine("Trying to Create Instance after permission has been denied.")
         Try
            ' Create an instance of the "MyDynamicClass" class.
            Dim myNewCustomObject As Object = _
                     Activator.CreateInstance(customClassType, New Object() {"HelloWorld!!!"})
         Catch e As Exception
            Console.WriteLine("Exception: Failed to create Instance")
            Console.WriteLine("(" + e.Message + ")")
         End Try
      End Sub 'Main
      
      ' Assumption : Dynamically created class might require reading of ;
      ' environment variable "TEMP",hence demands permission from caller.
      Private Shared Function CreateCallee(appDomain As AppDomain) As Type
         ' Create a simple name for the assembly.        
         Dim myAssemblyName As New AssemblyName()
         myAssemblyName.Name = "EmittedAssembly"
         ' Create the called dynamic assembly.
         Dim myAssemblyBuilder As AssemblyBuilder = _
                  appDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run)
         Dim myModuleBuilder As ModuleBuilder = _
                  myAssemblyBuilder.DefineDynamicModule("EmittedModule")
         ' Define a public class named "MyDynamicClass" in the assembly.
         Dim myTypeBuilder As TypeBuilder = _
                  myModuleBuilder.DefineType("MyDynamicClass", TypeAttributes.Public)
         ' Create a permission set.
         Dim myPermissionSet As New PermissionSet(PermissionState.None)
         ' Create Environment Read permission on 'TEMP' folder.
         myPermissionSet.AddPermission(New EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP"))
         ' Add declarative security with 'demand' security action.
         myTypeBuilder.AddDeclarativeSecurity(SecurityAction.Demand, myPermissionSet)
         ' Define a private String field named "m_greeting" in the type.
         Dim myFieldBuilder As FieldBuilder = _
                  myTypeBuilder.DefineField("m_greeting", GetType(String), FieldAttributes.Private)
         ' Define constructor.
         Dim constructorArgs() As Type = New Type() {GetType(String)}
         Dim myConstructorBuilder As ConstructorBuilder = _
                  myTypeBuilder.DefineConstructor(MethodAttributes.Public, _
                  CallingConventions.Standard, constructorArgs)
         ' Generate IL for the method.The constructor stores its argument in the private field.
         Dim constructorIL As ILGenerator = myConstructorBuilder.GetILGenerator()
         constructorIL.Emit(OpCodes.Ldarg_0)
         constructorIL.Emit(OpCodes.Ldarg_1)
         constructorIL.Emit(OpCodes.Stfld, myFieldBuilder)
         constructorIL.Emit(OpCodes.Ret)
         ' Define property 'Greeting'.
         Dim propertyArgs() As Type
         Dim myPropertyBuilder As PropertyBuilder = _
                  myTypeBuilder.DefineProperty("Greeting", PropertyAttributes.None, _
                  GetType(String), propertyArgs)
         ' Create the get_Greeting method.
         Dim getGreetingMethod As MethodBuilder = _
                  myTypeBuilder.DefineMethod("get_Greeting", MethodAttributes.Public Or _
                  MethodAttributes.HideBySig Or MethodAttributes.SpecialName, _
                  GetType(String), Nothing)
         ' Generate IL for get_Greeting method.
         Dim methodIL As ILGenerator = getGreetingMethod.GetILGenerator()
         methodIL.Emit(OpCodes.Ldarg_0)
         methodIL.Emit(OpCodes.Ldfld, myFieldBuilder)
         methodIL.Emit(OpCodes.Ret)
         myPropertyBuilder.SetGetMethod(getGreetingMethod)
         Dim myCustomClassType As Type = myTypeBuilder.CreateType()
         Return myCustomClassType
      End Function 'CreateCallee
   End Class 'MyApplication
End Namespace 'CustomAttribute_Sample

[C#] 
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Security.Permissions;

namespace CustomAttribute_Sample
{

   class MyApplication
   {
      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.
         PermissionSet myPermissionSet = new PermissionSet(PermissionState.None);
         // Create Environment Read Permission on 'TEMP' folder.
         myPermissionSet.AddPermission(
            new EnvironmentPermission(EnvironmentPermissionAccess.Read , "TEMP"));
         // Deny all permissions on 'TEMP' folder.
         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+")");
         }
      }
// Assumption : Dynamically created class might require reading of ;
// environment variable "TEMP",hence demands permission from caller.
      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.
         PermissionSet myPermissionSet = new PermissionSet(PermissionState.None);
         // Create Environment Read permission on 'TEMP' folder.
         myPermissionSet.AddPermission(
            new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP"));
         // Add declarative security with 'demand' security action.
         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);
      }
   }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Security;
using namespace System::Security::Permissions;

// Assumption : Dynamically created class might require reading of ;
// environment variable "TEMP", hence demands permission from caller.
Type* CreateCallee(AppDomain* appDomain) {
   // Create a simple name for the assembly.
   AssemblyName* myAssemblyName = new AssemblyName();
   myAssemblyName->Name = S"EmittedAssembly";
   // Create the called dynamic assembly.
   AssemblyBuilder*  myAssemblyBuilder =
      appDomain->DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess::Run);
   ModuleBuilder*  myModuleBuilder = myAssemblyBuilder->DefineDynamicModule(S"EmittedModule");
   // Define a public class named "MyDynamicClass" in the assembly.
   TypeBuilder*  myTypeBuilder = myModuleBuilder->DefineType(S"MyDynamicClass",
      TypeAttributes::Public);
   // Create a permission set.
   PermissionSet* myPermissionSet = new PermissionSet(PermissionState::None);
   // Create Environment Read permission on 'TEMP' folder.
   myPermissionSet->AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess::Read, S"TEMP"));
   // Add declarative security with 'demand' security action.
   myTypeBuilder->AddDeclarativeSecurity(SecurityAction::Demand , myPermissionSet);
   // Define a private String field named "m_greeting" in the type.
   FieldBuilder*  myFieldBuilder = myTypeBuilder->DefineField(S"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[] = new Type*[0];
   PropertyBuilder*  myPropertyBuilder = myTypeBuilder->DefineProperty(S"Greeting",
      PropertyAttributes::None, __typeof(String), propertyArgs);
   // Create the get_Greeting method.
   MethodBuilder*  getGreetingMethod = myTypeBuilder->DefineMethod(S"get_Greeting",static_cast<MethodAttributes>(MethodAttributes::Public|MethodAttributes::HideBySig|MethodAttributes::SpecialName),
      __typeof(String), 0);
   // 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);
}

int main() {
   Type*  customClassType = CreateCallee(Thread::GetDomain());
   Console::WriteLine(S"Trying to Create Instance with Default permission.");
   // Create an instance of the "MyDynamicClass" class.
   Object* temp0 [] = {S"HelloWorld!!!"};
   Object*  myCustomObject = Activator::CreateInstance(customClassType, temp0);
   // Get 'Greeting' property.
   Object* objectGreeting =  customClassType->InvokeMember(S"Greeting",
      BindingFlags::GetProperty,
      0,
      myCustomObject,
      0);

   Console::WriteLine(S"Property Value : {0}", objectGreeting);
   Console::WriteLine(S"");
   // Create a permission set.
   PermissionSet* myPermissionSet = new PermissionSet(PermissionState::None);
   // Create Environment Read Permission on 'TEMP' folder.
   myPermissionSet->AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess::Read , S"TEMP"));
   // Deny all permissions on 'TEMP' folder.
   myPermissionSet->Deny();
   Console::WriteLine(S"Trying to Create Instance after permission has been denied.");
   try {
      // Create an instance of the "MyDynamicClass" class.
      Object* temp1 [] = {S"HelloWorld!!!"};
      Object*  myNewCustomObject = Activator::CreateInstance(customClassType, temp1);
   } catch (Exception* e) {
      Console::WriteLine(S"Exception: Failed to create Instance");
      Console::WriteLine(S"({0})", e->Message);
   }
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

TypeBuilder Class | TypeBuilder Members | System.Reflection.Emit Namespace

Show:
© 2015 Microsoft