This documentation is archived and is not being maintained.

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> _
<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
Dim instance As HostProtectionAttribute

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

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.


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.


Do not use the Native Image Generator (Ngen.exe) 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.

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

<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, _
<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, _

' 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 & " " & _
        Environment.ExitCode = Code
    End Sub 'Exit 

    ' 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.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 
            Dim mAD As AppDomain = AppDomain.CurrentDomain
            Dim mGenPr As _
                New GenericPrincipal(WindowsIdentity.GetCurrent(), roles)
            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()
            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 _

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

        ' Give the new thread a chance to execute.
    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 
            ' Show use of the HostProtectionResource.SharedState, 
            ' HostProtectionResource.SelfAffectingThreading, and 
            ' HostProtectionResource.Security enumeration values.

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

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

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

            ' 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 & " " & _
    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 " & _
    End Sub 'New 

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0