Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase HostProtectionAttribute

 

Publicado: noviembre de 2016

Permite al uso de acciones de seguridad declarativa para determinar los requisitos de protección del host. Esta clase no puede heredarse.

Espacio de nombres:   System.Security.Permissions
Ensamblado:  mscorlib (en mscorlib.dll)

System.Object
  System.Attribute
    System.Security.Permissions.SecurityAttribute
      System.Security.Permissions.CodeAccessSecurityAttribute
        System.Security.Permissions.HostProtectionAttribute

<SerializableAttribute>
<AttributeUsageAttribute(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Struct Or AttributeTargets.Constructor Or AttributeTargets.Method Or AttributeTargets.Delegate,
	AllowMultiple := True, Inherited := False)>
<ComVisibleAttribute(True)>
Public NotInheritable Class HostProtectionAttribute
	Inherits CodeAccessSecurityAttribute

NombreDescripción
System_CAPS_pubmethodHostProtectionAttribute()

Inicializa una nueva instancia de la clase HostProtectionAttribute con valores predeterminados.

System_CAPS_pubmethodHostProtectionAttribute(SecurityAction)

Inicializa una nueva instancia de la clase HostProtectionAttribute con el valor SecurityAction especificado.

NombreDescripción
System_CAPS_pubpropertyAction

Obtiene o establece una acción de seguridad.(Heredado de SecurityAttribute).

System_CAPS_pubpropertyExternalProcessMgmt

Obtiene o establece un valor que indica si la administración de procesos externos está expuesta.

System_CAPS_pubpropertyExternalThreading

Obtiene o establece un valor que indica si el subproceso externo está expuesto.

System_CAPS_pubpropertyMayLeakOnAbort

Obtiene o establece un valor que indica si los recursos podrían perder memoria en caso de finalizarse la operación.

System_CAPS_pubpropertyResources

Obtiene o establece marcadores que especifican categorías de funcionalidad que son potencialmente dañinas para el host.

System_CAPS_pubpropertySecurityInfrastructure

Obtiene o establece un valor que indica si la infraestructura de seguridad está expuesta.

System_CAPS_pubpropertySelfAffectingProcessMgmt

Obtiene o establece un valor que indica si la administración de procesos con efecto sobre sí mismos está expuesta.

System_CAPS_pubpropertySelfAffectingThreading

Obtiene o establece un valor que indica si el subproceso con efecto sobre sí mismo está expuesto.

System_CAPS_pubpropertySharedState

Obtiene o establece un valor que indica si el estado compartido está expuesto.

System_CAPS_pubpropertySynchronization

Obtiene o establece un valor que indica si la sincronización está expuesta.

System_CAPS_pubpropertyTypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.(Heredado de Attribute).

System_CAPS_pubpropertyUI

Obtiene o establece un valor que indica si la interfaz de usuario está expuesta.

System_CAPS_pubpropertyUnrestricted

Obtiene o establece un valor que indica si se declara el permiso completo de (sin restricciones) al recurso protegido por el atributo.(Heredado de SecurityAttribute).

NombreDescripción
System_CAPS_pubmethodCreatePermission()

Crea y devuelve un nuevo permiso de protección de host.(Invalida SecurityAttribute.CreatePermission()).

System_CAPS_pubmethodEquals(Object)

Esta API admite la infraestructura producto y no está diseñada para usarse directamente desde el código. Devuelve un valor que indica si esta instancia equivale al objeto especificado. (Heredado de Attribute).

System_CAPS_pubmethodGetHashCode()

Devuelve el código hash de esta instancia.(Heredado de Attribute).

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_pubmethodIsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.(Heredado de Attribute).

System_CAPS_pubmethodMatch(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual al objeto especificado. (Heredado de Attribute).

System_CAPS_pubmethodToString()

Devuelve una cadena que representa al objeto actual. (Heredado de Object).

NombreDescripción
System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información del tipo de un objeto, que puede utilizarse para obtener la información del tipo de una interfaz. (Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de tipo de información que suministra un objeto (0 ó 1)

(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.(Heredado de Attribute).

This attribute affects only unmanaged applications that host the common language runtime and implement host protection, such as SQL Server. If the code is run in a client application or on a server that is not host-protected, the attribute "evaporates"; it is not detected and therefore not applied. When applied, the security action results in the creation of a link demand based on the host resources the class or method exposes.

System_CAPS_importantImportante

The purpose of this attribute is to enforce host-specific programming model guidelines, not security behavior. Although a link demand is used to check for conformance to programming model requirements, the T:System.Security.Permissions.HostProtectionAttribute is not a security permission.

If the host does not have programming model requirements, the link demands do not occur.

This attribute identifies the following:

  • Methods or classes that do not fit the host programming model, but are otherwise benign.

  • Methods or classes that do not fit the host programming model and could lead to destabilizing server-managed user code.

  • Methods or classes that do not fit the host programming model and could lead to a destabilization of the server process itself.

System_CAPS_noteNota

If you are creating a class library that is to be called by applications that may execute in a host protected environment, you should apply this attribute to members that expose T:System.Security.Permissions.HostProtectionResource resource categories. The .NET Framework class library members with this attribute cause only the immediate caller to be checked. Your library member must also cause a check of its immediate caller in the same manner.

System_CAPS_noteNota

Do not use the Native Image Generator (Ngen.exe) to create a native image of assemblies that are protected by the T:System.Security.Permissions.HostProtectionAttribute. In a full-trust environment, the image is always loaded, without regard to the T:System.Security.Permissions.HostProtectionAttribute, and in a partial-trust environment the image is not loaded.

The following code example illustrates the use of the T:System.Security.Permissions.HostProtectionAttribute attribute with a variety of T:System.Security.Permissions.HostProtectionResource values.

Imports System
Imports System.IO
Imports System.Threading
Imports System.Security
Imports System.Security.Policy
Imports System.Security.Principal
Imports System.Security.Permissions
Imports System.Diagnostics
Imports System.ComponentModel
Imports System.Windows.Forms


' If this application is run on a server that implements host protection, the
' HostProtectionAttribute attribute is applied. If the application is run on 
' a server that is not host-protected, the attribute evaporates; it is not  
' detected and therefore not applied. Host protection can be configured with  
' members of the HostProtectionResource enumeration to customize the  
' protection offered. 
' The primary intent of this sample is to show situations in which the 
' HostProtectionAttribute attribute might be meaningfully used.  The 
' environment required to demonstrate a particular behavior is too 
' complex to invoke within the scope of this sample.

Class HostProtectionExample
    Public Shared Success As Integer = 100

    ' Use the enumeration flags to indicate that this method exposes 
    ' shared state and self-affecting process management.
    ' Either of the following attribute statements can be used to set the 
    ' resource flags.
    <HostProtectionAttribute(SharedState := True, _
        SelfAffectingProcessMgmt := True), _
        HostProtectionAttribute( _
        Resources := HostProtectionResource.SharedState Or _
        HostProtectionResource.SelfAffectingProcessMgmt)> _
    Private Shared Sub [Exit](ByVal Message As String, ByVal Code As Integer)

        ' Exit the sample when an exception is thrown.
        Console.WriteLine((ControlChars.Lf & "FAILED: " & Message & " " & _
            Code.ToString()))
        Environment.ExitCode = Code
        Environment.Exit(Code)
    End Sub 'ExitExit

    ' Use the enumeration flags to indicate that this method exposes shared
    ' state, self-affecting process management, and self-affecting threading.
    <HostProtectionAttribute(SharedState := True, _
        SelfAffectingProcessMgmt := True, _
        SelfAffectingThreading := True, UI := True)> _
    Private Shared Sub ExecuteBreak()

        ' This method allows the user to quit the sample.
        Console.WriteLine("Executing Debugger.Break.")
        Debugger.Break()
        Debugger.Log(1, "info", "test message")
    End Sub 'ExecuteBreak

    ' Use the enumeration flags to indicate that this method exposes shared  
    ' state, self-affecting threading, and the security infrastructure.
    <HostProtectionAttribute(SharedState := True, _
        SelfAffectingThreading := True, _
        SecurityInfrastructure := True)> _
    Private Shared Function ApplyIdentity() As Integer

        ' ApplyIdentity sets the current identity.
        Dim roles(1) As String
        Try
            Dim mAD As AppDomain = AppDomain.CurrentDomain
            Dim mGenPr As _
                New GenericPrincipal(WindowsIdentity.GetCurrent(), roles)
            mAD.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
            mAD.SetThreadPrincipal(mGenPr)
            Return Success
        Catch e As Exception
            [Exit](e.ToString(), 5)
        End Try
        Return 0
    End Function 'ApplyIdentity

    ' The following method is started on a separate thread.
    Public Shared Sub WatchFileEvents()
        Try
            Console.WriteLine("In the child thread.")
            Dim watcher As New FileSystemWatcher()
            watcher.Path = "C:\Temp"

            ' Watch for changes in LastAccess and LastWrite times, and 
            ' name changes to files or directories. 
            watcher.NotifyFilter = NotifyFilters.LastAccess Or _
                NotifyFilters.LastWrite Or NotifyFilters.FileName Or _
                NotifyFilters.DirectoryName

            ' Watch only text files.
            watcher.Filter = "*.txt"

            ' Add event handlers.
            AddHandler watcher.Changed, AddressOf OnChanged
            AddHandler watcher.Created, AddressOf OnChanged
            AddHandler watcher.Deleted, AddressOf OnChanged

            ' Begin watching.
            watcher.EnableRaisingEvents = True

            ' Wait for the user to quit the program.
            Console.WriteLine("Event handlers have been enabled.")
            While Console.ReadLine() <> "q"c
            End While
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub 'WatchFileEvents

    ' Use the enumeration flags to indicate that this method exposes  
    ' synchronization and external threading.
    <HostProtectionAttribute(Synchronization := True, _
        ExternalThreading := True)> _
    Private Shared Sub StartThread()
        Dim t As New Thread(New ThreadStart(AddressOf WatchFileEvents))

        ' Start the new thread. On a uniprocessor, the thread is not given 
        ' any processor time until the main thread yields the processor.  
        t.Start()

        ' Give the new thread a chance to execute.
        Thread.Sleep(1000)
    End Sub 'StartThread

    ' Call methods that show the use of the HostProtectionResource enumeration.
    <HostProtectionAttribute(Resources := HostProtectionResource.All)> _
    Overloads Shared Function Main(ByVal args() As String) As Integer
        Try
            ' Show use of the HostProtectionResource.SharedState,
            ' HostProtectionResource.SelfAffectingThreading, and
            ' HostProtectionResource.Security enumeration values.
            ApplyIdentity()
            Directory.CreateDirectory("C:\Temp")

            ' Show use of the HostProtectionResource.Synchronization and
            ' HostProtectionResource.ExternalThreading enumeration values.
            StartThread()
            Console.WriteLine("In the main thread.")
            Console.WriteLine("Deleting and creating 'MyTestFile.txt'.")
            If File.Exists("C:\Temp\MyTestFile.txt") Then
                File.Delete("C:\Temp\MyTestFile.txt")
            End If

            Dim sr As StreamWriter = File.CreateText("C:\Temp\MyTestFile.txt")
            sr.WriteLine("This is my file.")
            sr.Close()
            Thread.Sleep(1000)

            ' Show use of the HostProtectionResource.SharedState, 
            ' HostProtectionResource.SelfProcessMgmt,
            ' HostProtectionResource.SelfAffectingThreading, and
            ' HostProtectionResource.UI enumeration values.
            ExecuteBreak()

            ' Show the use of the 
            ' HostProtectionResource.ExternalProcessManagement 
            ' enumeration value.
            Dim myControl As New MyControl()
            Console.WriteLine("Enter 'q' to quit the sample.")
            Return 100
        Catch e As Exception
            [Exit](e.ToString(), 0)
            Return 0
        End Try
    End Function 'Main

    ' Define the event handlers.
    Private Shared Sub OnChanged(ByVal [source] As Object, _
        ByVal e As FileSystemEventArgs)

        ' Specify whether a file is changed, created, or deleted.
        Console.WriteLine("In the OnChanged event handler.")
        Console.WriteLine(("File: " & e.FullPath & " " & _
            e.ChangeType.ToString()))
    End Sub 'OnChanged
End Class 'HostProtectionExample 

' The following class is an example of code that exposes 
' external process management.
' Add the LicenseProviderAttribute to the control.
<LicenseProvider(GetType(LicFileLicenseProvider))> _
Public Class MyControl
    Inherits System.Windows.Forms.Control

    ' Create a new, null license.
    Private license As License = Nothing

    <HostProtectionAttribute(ExternalProcessMgmt := True)> _
    Public Sub New()

        ' Determine if a valid license can be granted.
        Dim isValid As Boolean = LicenseManager.IsValid(GetType(MyControl))
        Console.WriteLine(("The result of the IsValid method call is " & _
            isValid.ToString()))
    End Sub 'NewNew

    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (license Is Nothing) Then
                license.Dispose()
                license = Nothing
            End If
        End If
    End Sub 'Dispose
End Class 'MyControl

.NET Framework
Disponible desde 2.0

Cualquier miembro ( Compartido en Visual Basic) estático público de este tipo es seguro para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Volver al principio
Mostrar: