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 | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Delegate, 
	AllowMultiple = true, Inherited = false)]
[ComVisibleAttribute(true)]
public sealed class HostProtectionAttribute : 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.

using System;
using System.IO;
using System.Threading;
using System.Security;
using System.Security.Policy;
using System.Security.Principal;
using System.Security.Permissions;
using System.Diagnostics;
using System.ComponentModel;
using 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 static int Success = 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 |
         HostProtectionResource.SelfAffectingProcessMgmt)]
    private static void Exit(string Message, int Code)
    {
        // Exit the sample when an exception is thrown.
        Console.WriteLine("\nFAILED: " + Message + " " + Code.ToString());
        Environment.ExitCode = Code;
        Environment.Exit(Code);
    }

    // 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)]
    // This method allows the user to quit the sample.
    private static void ExecuteBreak()
    {
        Console.WriteLine("Executing Debugger.Break.");
        Debugger.Break();
        Debugger.Log(1,"info","test message");
    }

    // 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)]
    // ApplyIdentity sets the current identity.
    private static int ApplyIdentity()
    {
        string[] roles = {"User"};
        try
        {
            AppDomain mAD = AppDomain.CurrentDomain;
            GenericPrincipal mGenPr = 
                new GenericPrincipal(WindowsIdentity.GetCurrent(), roles);
            mAD.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            mAD.SetThreadPrincipal(mGenPr);
            return Success;
        }
        catch (Exception e)
        {
            Exit(e.ToString(), 5);
        }
        return 0;
    }

    // The following method is started on a separate thread.
    public static void WatchFileEvents()
    {
        try
        {
            Console.WriteLine("In the child thread.");
            FileSystemWatcher watcher = 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 
                | NotifyFilters.LastWrite
                | NotifyFilters.FileName | NotifyFilters.DirectoryName;

            // Watch only text files.
            watcher.Filter = "*.txt";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Event handlers have been enabled.");
            while(Console.Read()!='q');
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    // Use the enumeration flags to indicate that this method exposes 
    // synchronization and external threading.
    [HostProtectionAttribute(Synchronization=true, ExternalThreading=true)]
    private static void StartThread()
    {
        Thread t = new Thread(new ThreadStart(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);
    }

    // Call methods that show the use of the HostProtectionResource enumeration.
    [HostProtectionAttribute(Resources=HostProtectionResource.All)]
    static int Main(string [] args)
    {
        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"))
            {
                File.Delete("C:\\Temp\\MyTestFile.txt");
            }

            StreamWriter sr = 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.
            MyControl myControl = new MyControl ();
            Console.WriteLine ("Enter 'q' to quit the sample.");
            return 100;
        }
        catch (Exception e)
        {
            Exit(e.ToString(), 0);
            return 0;
        }
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify whether a file is changed, created, or deleted.
        Console.WriteLine("In the OnChanged event handler.");
        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
    }
}

// The following class is an example of code that exposes 
// external process management.
// Add the LicenseProviderAttribute to the control.
[LicenseProvider (typeof(LicFileLicenseProvider))]
public class MyControl : System.Windows.Forms.Control
{
    // Create a new, null license.
    private License license = null;

    [HostProtection (ExternalProcessMgmt = true)]
    public MyControl ()
    {
        // Determine if a valid license can be granted.
        bool isValid = LicenseManager.IsValid (typeof(MyControl));
        Console.WriteLine ("The result of the IsValid method call is " + 
            isValid.ToString ());
    }

    protected override void Dispose (bool disposing)
    {
        if (disposing)
        {
            if (license != null)
            {
                license.Dispose ();
                license = null;
            }
        }
    }
}

.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: