Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

HostProtectionAttribute Class

Allows the use of declarative security actions to determine host protection requirements. This class cannot be inherited.

Namespace:  System.Security.Permissions
Assembly:  mscorlib (in mscorlib.dll)
[SerializableAttribute]
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets.Assembly|AttributeTargets.Class|AttributeTargets.Struct|AttributeTargets.Constructor|AttributeTargets.Method|AttributeTargets.Delegate, AllowMultiple = true, 
	Inherited = false)]
public sealed class HostProtectionAttribute : CodeAccessSecurityAttribute

The HostProtectionAttribute type exposes the following members.

  NameDescription
Public methodHostProtectionAttribute()Initializes a new instance of the HostProtectionAttribute class with default values.
Public methodHostProtectionAttribute(SecurityAction)Initializes a new instance of the HostProtectionAttribute class with the specified SecurityAction value.
Top
  NameDescription
Public propertyActionGets or sets a security action. (Inherited from SecurityAttribute.)
Public propertyExternalProcessMgmtGets or sets a value indicating whether external process management is exposed.
Public propertyExternalThreadingGets or sets a value indicating whether external threading is exposed.
Public propertyMayLeakOnAbortGets or sets a value indicating whether resources might leak memory if the operation is terminated.
Public propertyResourcesGets or sets flags specifying categories of functionality that are potentially harmful to the host.
Public propertySecurityInfrastructureGets or sets a value indicating whether the security infrastructure is exposed.
Public propertySelfAffectingProcessMgmtGets or sets a value indicating whether self-affecting process management is exposed.
Public propertySelfAffectingThreadingGets or sets a value indicating whether self-affecting threading is exposed.
Public propertySharedStateGets or sets a value indicating whether shared state is exposed.
Public propertySynchronizationGets or sets a value indicating whether synchronization is exposed.
Public propertyTypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Public propertyUIGets or sets a value indicating whether the user interface is exposed.
Public propertyUnrestrictedGets or sets a value indicating whether full (unrestricted) permission to the resource protected by the attribute is declared. (Inherited from SecurityAttribute.)
Top
  NameDescription
Public methodCreatePermissionCreates and returns a new host protection permission. (Overrides SecurityAttribute.CreatePermission().)
Public methodEqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Public methodGetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public methodMatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Explicit interface implemetationPrivate method_Attribute.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.InvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top

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.

Important noteImportant

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

NoteNote

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

NoteNote

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

The following code example illustrates the use of the HostProtectionAttribute attribute with a variety of 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

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.