TypeBuilder.AddDeclarativeSecurity 메서드
해당 형식에 선언적 보안을 추가합니다.
네임스페이스: System.Reflection.Emit
어셈블리: mscorlib(mscorlib.dll)
구문
‘선언
Public Sub AddDeclarativeSecurity ( _
action As SecurityAction, _
pset As PermissionSet _
)
‘사용 방법
Dim instance As TypeBuilder
Dim action As SecurityAction
Dim pset As PermissionSet
instance.AddDeclarativeSecurity(action, pset)
public void AddDeclarativeSecurity (
SecurityAction action,
PermissionSet pset
)
public:
void AddDeclarativeSecurity (
SecurityAction action,
PermissionSet^ pset
)
public void AddDeclarativeSecurity (
SecurityAction action,
PermissionSet pset
)
public function AddDeclarativeSecurity (
action : SecurityAction,
pset : PermissionSet
)
매개 변수
- action
취할 보안 동작(예: Demand, Assert 등)입니다.
- pset
동작이 적용될 권한 집합입니다.
예외
예외 형식 | 조건 |
---|---|
action이 잘못된 경우(RequestMinimum, RequestOptional 및 RequestRefuse가 잘못된 경우) |
|
포함하는 형식을 CreateType을 사용하여 만든 경우 - 또는 - AddDeclarativeSecurity에 의해 이미 추가된 동작이 권한 집합 pset에 들어 있는 경우 |
|
pset이 Null 참조(Visual Basic의 경우 Nothing)인 경우 |
설명
Demand, Assert 또는 Deny 같은 보안 동작을 지정하고 해당 동작에 적용되는 권한 집합을 지정하는 호출을 할 때마다 AddDeclarativeSecurity를 계속 호출할 수 있습니다.
예제
다음 코드 예제에서는 AddDeclarativeSecurity를 사용하여 동적 형식에 'demand' 보안 동작을 추가하는 방법을 보여 줍니다.
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Security
Imports System.Security.Permissions
Namespace CustomAttribute_Sample
Class MyApplication
' Create a dynamic type, MyDynamicClass, that demands
' ControlEvidence permission.
'
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 and add a security permission
' with the ControlEvidence flag.
'
Dim myPermissionSet As New PermissionSet(PermissionState.None)
Dim ce As New SecurityPermission(SecurityPermissionFlag.ControlEvidence)
myPermissionSet.AddPermission(ce)
' 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.
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
<PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
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 the 'Greeting' property value.
Dim objectGreeting As Object = _
customClassType.InvokeMember("Greeting", _
BindingFlags.GetProperty, Nothing, myCustomObject, Nothing)
Console.WriteLine("Property Value: " & objectGreeting.ToString())
Console.WriteLine("")
' Create a permission set that's the same as the set
' demanded by the MyDynamicClass class.
'
Dim myPermissionSet As New PermissionSet(PermissionState.None)
Dim ce As New SecurityPermission(SecurityPermissionFlag.ControlEvidence)
myPermissionSet.AddPermission(ce)
' 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.
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
End Class 'MyApplication
End Namespace 'CustomAttribute_Sample
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 + "'");
}
}
}
}
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 = gcnew 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 = gcnew PermissionSet(PermissionState::None);
myPermissionSet->AddPermission(
gcnew 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", String::typeid, FieldAttributes::Private );
// Define constructor.
array<Type^>^constructorArgs = {String::typeid};
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'.
array<Type^>^propertyArgs = gcnew array<Type^>(0);
PropertyBuilder^ myPropertyBuilder = myTypeBuilder->DefineProperty( "Greeting", PropertyAttributes::None, String::typeid, propertyArgs );
// Create the get_Greeting method.
MethodBuilder^ getGreetingMethod = myTypeBuilder->DefineMethod( "get_Greeting", static_cast<MethodAttributes>(MethodAttributes::Public | MethodAttributes::HideBySig | MethodAttributes::SpecialName), String::typeid, nullptr );
// 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( "Trying to Create Instance with Default permission." );
// Create an instance of the "MyDynamicClass" class.
array<Object^>^temp0 = {"HelloWorld!!!"};
Object^ myCustomObject = Activator::CreateInstance( customClassType, temp0 );
// Get 'Greeting' property.
Object^ objectGreeting = customClassType->InvokeMember( "Greeting", BindingFlags::GetProperty, nullptr, myCustomObject, nullptr );
Console::WriteLine( "Property Value : {0}", objectGreeting );
Console::WriteLine( "" );
// Create a permission set that's the same as the set
// demanded by the MyDynamicClass class.
//
PermissionSet^ myPermissionSet = gcnew PermissionSet( PermissionState::None );
myPermissionSet->AddPermission(
gcnew 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.
array<Object^>^temp1 = {"HelloWorld!!!"};
Object^ myNewCustomObject = Activator::CreateInstance( customClassType, temp1 );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: Failed to create Instance" );
Console::WriteLine( "'{0}'", 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
.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.
버전 정보
.NET Framework
2.0, 1.1, 1.0에서 지원
참고 항목
참조
TypeBuilder 클래스
TypeBuilder 멤버
System.Reflection.Emit 네임스페이스