Export (0) Print
Expand All

SecurityPermission Class

Describes a set of security permissions applied to code. This class cannot be inherited.

For a list of all members of this type, see SecurityPermission Members.

System.Object
   System.Security.CodeAccessPermission
      System.Security.Permissions.SecurityPermission

[Visual Basic]
<Serializable>
NotInheritable Public Class SecurityPermission
   Inherits CodeAccessPermission
   Implements IUnrestrictedPermission
[C#]
[Serializable]
public sealed class SecurityPermission : CodeAccessPermission,
   IUnrestrictedPermission
[C++]
[Serializable]
public __gc __sealed class SecurityPermission : public
   CodeAccessPermission, IUnrestrictedPermission
[JScript]
public
   Serializable
class SecurityPermission extends CodeAccessPermission
   implements IUnrestrictedPermission

Thread Safety

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

Remarks

This permission uses the SecurityPermissionFlag enumeration. The values for this enumeration can be found in its documentation.

Example

[Visual Basic] 
' This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml and FromXml methods 
' of the SecurityPermission Class.
Imports System
Imports System.Security
Imports System.Security.Permissions
Imports Microsoft.VisualBasic

<Assembly: CLSCompliant(True)> 

Public Class SecurityPermissionDemo

    ' IsSubsetOf determines whether the current permission is a subset of the specified permission.
    Private Function IsSubsetOfDemo() As Boolean
        Dim returnValue As Boolean = True
        Dim Security1, Security2 As SecurityPermissionFlag
        Dim SecurityPerm1, SecurityPerm2 As SecurityPermission
        Dim SecurityGen1 As New SecurityGenerator()
        Dim SecurityGen2 As New SecurityGenerator()
        SecurityGen1.ResetIndex()
        While SecurityGen1.CreateSecurity(SecurityPerm1, Security1)
            If SecurityPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            SecurityGen2.ResetIndex()
            Console.WriteLine("********************************************************" & ControlChars.Lf)

            While SecurityGen2.CreateSecurity(SecurityPerm2, Security2)
                If SecurityPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                Try
                    If SecurityPerm1.IsSubsetOf(SecurityPerm2) Then
                        Console.WriteLine((SecurityPerm1.Flags.ToString().ToString() _
                        & " is a subset of " & SecurityPerm2.Flags.ToString()))
                    Else
                        Console.WriteLine((SecurityPerm1.Flags.ToString() & " is not a subset of " _
                        & SecurityPerm2.Flags.ToString()))
                    End If
                Catch e As Exception
                    Console.WriteLine(("An exception was thrown for subset :" & SecurityPerm1.ToString() _
                    & ControlChars.Lf & SecurityPerm2.ToString() & ControlChars.Lf & e.ToString()))
                    returnValue = False
                End Try
ContinueWhile2:
            End While
ContinueWhile1:
        End While
        Return returnValue
    End Function 'IsSubsetOfDemo

    ' Union creates a new permission that is the union of the current permission and 
    ' the specified permission.
    Private Function UnionDemo() As Boolean
        Dim returnValue As Boolean = True
        Dim Security1, Security2 As SecurityPermissionFlag
        Dim SecurityPerm1, SecurityPerm2 As SecurityPermission
        Dim SecurityPerm3 As IPermission
        Dim SecurityGen1 As New SecurityGenerator()
        Dim SecurityGen2 As New SecurityGenerator()
        SecurityGen1.ResetIndex()
        While SecurityGen1.CreateSecurity(SecurityPerm1, Security1)
            If SecurityPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)
            SecurityGen2.ResetIndex()

            While SecurityGen2.CreateSecurity(SecurityPerm2, Security2)
                If SecurityPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                SecurityPerm3 = CType(SecurityPerm1.Union(SecurityPerm2), SecurityPermission)
                SecurityPerm3 = SecurityPerm1.Union(SecurityPerm2)

                If SecurityPerm3 Is Nothing Then
                    Console.WriteLine(("The union of " & Security1 & " and " & Security2 & " is null."))
                Else
                    Console.WriteLine(("The union of " & SecurityPerm1.Flags.ToString() _
                    & " and " & SecurityPerm2.Flags.ToString() & " = " & CType(SecurityPerm3, SecurityPermission).Flags.ToString().ToString()))
                End If
ContinueWhile2:
            End While
ContinueWhile1:
        End While


        Return returnValue
    End Function 'UnionDemo

    ' Intersect creates and returns a new permission that is the intersection of the current 
    ' permission and the permission specified.
    Private Function IntersectDemo() As Boolean
        Dim returnValue As Boolean = True
        Dim Security1, Security2 As SecurityPermissionFlag
        Dim SecurityPerm1, SecurityPerm2, SecurityPerm3 As SecurityPermission
        Dim SecurityGen1 As New SecurityGenerator()
        Dim SecurityGen2 As New SecurityGenerator()
        SecurityGen1.ResetIndex()
        While SecurityGen1.CreateSecurity(SecurityPerm1, Security1)
            If SecurityPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)
            SecurityGen2.ResetIndex()

            While SecurityGen2.CreateSecurity(SecurityPerm2, Security2)
                If SecurityPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                SecurityPerm3 = CType(SecurityPerm1.Intersect(SecurityPerm2), SecurityPermission)
                If Not (SecurityPerm3 Is Nothing) Then
                    Console.WriteLine(("The intersection of " & Security1.ToString() & " and " _
                    & Security2.ToString() & " = " _
                    & CType(SecurityPerm3, SecurityPermission).Flags.ToString().ToString()))
                Else
                    Console.WriteLine(("The intersection of " & Security1.ToString() & " and " _
                    & Security2.ToString() & " is null."))
                End If
ContinueWhile2:
            End While
ContinueWhile1:
        End While

        Return returnValue
    End Function 'IntersectDemo

    'Copy creates and returns an identical copy of the current permission.
    Private Function CopyDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim Security1 As SecurityPermissionFlag
        Dim SecurityPerm1, SecurityPerm2 As SecurityPermission

        Dim SecurityGen1 As New SecurityGenerator()
        Dim SecurityGen2 As New SecurityGenerator()

        SecurityGen1.ResetIndex()
        While SecurityGen1.CreateSecurity(SecurityPerm1, Security1)
            If SecurityPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            SecurityGen2.ResetIndex()
            Console.WriteLine("********************************************************" & ControlChars.Lf)
            Try
                SecurityPerm2 = CType(SecurityPerm1.Copy(), SecurityPermission)
                Console.WriteLine(("Result of copy = " & SecurityPerm2.ToString()))

            Catch e As Exception
                Console.WriteLine(("Copy failed :" & SecurityPerm1.ToString() & e.ToString()))
                GoTo ContinueWhile1
            End Try
ContinueWhile1:
        End While
        Return returnValue
    End Function 'CopyDemo

    ' ToXml creates an XML encoding of the permission and its current state; 
    ' FromXml reconstructs a permission with the specified state from the XML encoding. 
    Private Function ToFromXmlDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim Security1 As SecurityPermissionFlag
        Dim SecurityPerm1, SecurityPerm2 As SecurityPermission
        Dim SecurityGen1 As New SecurityGenerator()
        Dim SecurityGen2 As New SecurityGenerator()
        SecurityGen1.ResetIndex()
        While SecurityGen1.CreateSecurity(SecurityPerm1, Security1)
            If SecurityPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("********************************************************" & ControlChars.Lf)
            SecurityGen2.ResetIndex()
            Try
                SecurityPerm2 = New SecurityPermission(PermissionState.None)
                SecurityPerm2.FromXml(SecurityPerm1.ToXml())
                Console.WriteLine(("Result of ToFromXml = " & SecurityPerm2.ToString()))

            Catch e As Exception
                Console.WriteLine(("ToFromXml failed :" & SecurityPerm1.ToString() & e.ToString()))
                GoTo ContinueWhile1
            End Try
ContinueWhile1:
        End While

        Return returnValue
    End Function 'ToFromXmlDemo

    ' Invoke all demos.
    Public Function runDemo() As Boolean
        Dim returnCode As Boolean = True
        Dim tempReturnCode As Boolean

        ' Call the IsSubsetOf demo.
        tempReturnCode = IsSubsetOfDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("IsSubsetOf demo completed successfully.")
        Else
            Console.Out.WriteLine("IsSubsetOf demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        ' Call the Union demo.
        tempReturnCode = UnionDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("Union demo completed successfully.")
        Else
            Console.Out.WriteLine("Union demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        ' Call the Intersect demo.    
        tempReturnCode = IntersectDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("Intersect demo completed successfully.")
        Else
            Console.Out.WriteLine("Intersect demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode


        ' Call the Copy demo.    
        tempReturnCode = CopyDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("Copy demo completed successfully.")
        Else
            Console.Out.WriteLine("Copy demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        ' Call the ToFromXml demo.    
        tempReturnCode = ToFromXmlDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("ToFromXml demo completed successfully.")
        Else
            Console.Out.WriteLine("ToFromXml demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        Return returnCode
    End Function 'runDemo

    ' Test harness.
    Public Overloads Shared Sub Main(ByVal args() As [String])
        Try
            Dim democase As New SecurityPermissionDemo()
            Dim returnCode As Boolean = democase.runDemo()
            If returnCode Then
                Console.Out.WriteLine("SecurityPermission demo completed successfully.")
                Console.Out.WriteLine("Press the Enter key to exit.")
                Dim consoleInput As String = Console.ReadLine()
                System.Environment.ExitCode = 100
            Else
                Console.Out.WriteLine("SecurityPermission demo failed.")
                Console.Out.WriteLine("Press the Enter key to exit.")
                Dim consoleInput As String = Console.ReadLine()
                System.Environment.ExitCode = 101
            End If
        Catch e As Exception
            Console.Out.WriteLine("SecurityPermission demo failed.")
            Console.WriteLine(e.ToString())
            Console.Out.WriteLine("Press the Enter key to exit.")
            Dim consoleInput As String = Console.ReadLine()
            System.Environment.ExitCode = 101
        End Try
    End Sub 'Main
End Class 'SecurityPermissionDemo


' This class generates SecurityPermission objects.

Friend Class SecurityGenerator


    Private mySecurity As SecurityPermissionFlag() = {SecurityPermissionFlag.AllFlags, _
        SecurityPermissionFlag.Assertion, SecurityPermissionFlag.ControlAppDomain, _
        SecurityPermissionFlag.ControlDomainPolicy, SecurityPermissionFlag.ControlEvidence, _
        SecurityPermissionFlag.ControlPolicy, SecurityPermissionFlag.ControlPrincipal, _
        SecurityPermissionFlag.ControlThread, SecurityPermissionFlag.Execution, _
        SecurityPermissionFlag.Infrastructure, SecurityPermissionFlag.NoFlags, _
        SecurityPermissionFlag.RemotingConfiguration, _
        SecurityPermissionFlag.SerializationFormatter, _
        SecurityPermissionFlag.SkipVerification, _
        SecurityPermissionFlag.UnmanagedCode}

    Private reflectionIndex As Integer = 0


    Public Sub New()
        ResetIndex()
    End Sub 'New


    Public Sub ResetIndex()
        reflectionIndex = 0
    End Sub 'ResetIndex

    ' CreateSecurity creates a SecurityPermission object.
    Public Function CreateSecurity(ByRef SecurityPerm As SecurityPermission, _
        ByRef Security As SecurityPermissionFlag) As Boolean

        If reflectionIndex >= mySecurity.Length Then
            SecurityPerm = New SecurityPermission(PermissionState.None)
            Security = SecurityPermissionFlag.NoFlags
            reflectionIndex &= 1
            Return False
        End If
        Security = mySecurity(reflectionIndex)
        reflectionIndex = reflectionIndex + 1
        Try
            SecurityPerm = New SecurityPermission(Security)
            Return True
        Catch e As Exception
            Console.WriteLine(("Cannot create SecurityPermission: " & Security & " " & e.ToString()))
            SecurityPerm = New SecurityPermission(PermissionState.None)
            Security = SecurityPermissionFlag.NoFlags
            Return True
        End Try
    End Function 'CreateSecurity
' End of SecurityGenerator.

[C#] 
// This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml and FromXml methods 
// of the SecurityPermission Class.

using System;
using System.Security; 
using System.Security.Permissions; 

[assembly:CLSCompliant(true)]
public class SecurityPermissionDemo
{
    // IsSubsetOf determines whether the current permission is a subset of the specified permission.
    private bool IsSubsetOfDemo()
    {
        bool returnValue = true;
        SecurityPermissionFlag Security1,Security2;
        SecurityPermission SecurityPerm1,SecurityPerm2;
        SecurityGenerator SecurityGen1 = new SecurityGenerator();
        SecurityGenerator SecurityGen2 = new SecurityGenerator();
        SecurityGen1.ResetIndex();
        while(SecurityGen1.CreateSecurity(out SecurityPerm1, out Security1)) 
        {
            if(SecurityPerm1 == null) continue;
            SecurityGen2.ResetIndex();
            Console.WriteLine("********************************************************\n");

            while(SecurityGen2.CreateSecurity(out SecurityPerm2, out Security2)) 
            {
                if(SecurityPerm2 == null) continue;
                try
                {            
                    if (SecurityPerm1.IsSubsetOf(SecurityPerm2))
                    {
                        Console.WriteLine(SecurityPerm1.Flags + " is a subset of " + 
                            SecurityPerm2.Flags);
                    }
                    else
                    {
                        Console.WriteLine(SecurityPerm1.Flags + " is not a subset of " + 
                            SecurityPerm2.Flags);
                    }
                }
                catch(Exception e) 
                {
                    Console.WriteLine("An exception was thrown for subset :" + SecurityPerm1 + "\n" + 
                        SecurityPerm2 +"\n" + e);
                    returnValue=false;
                }
            }
        }
        return returnValue;
    }
    // Union creates a new permission that is the union of the current permission and the specified permission.
    private bool UnionDemo()
    {
        bool returnValue = true;
        SecurityPermissionFlag Security1,Security2;
        SecurityPermission SecurityPerm1,SecurityPerm2;
        IPermission SecurityPerm3;
        SecurityGenerator SecurityGen1 = new SecurityGenerator();
        SecurityGenerator SecurityGen2 = new SecurityGenerator();
        SecurityGen1.ResetIndex();
        while(SecurityGen1.CreateSecurity(out SecurityPerm1, out Security1)) 
        {
            if(SecurityPerm1 == null) continue;
            Console.WriteLine("**********************************************************\n");
            SecurityGen2.ResetIndex();

            while(SecurityGen2.CreateSecurity(out SecurityPerm2, out Security2)) 
            {
                if(SecurityPerm2 == null) continue;
                SecurityPerm3 = (SecurityPermission)SecurityPerm1.Union(SecurityPerm2);
                SecurityPerm3 = SecurityPerm1.Union(SecurityPerm2);

                if(SecurityPerm3 == null)  
                {
                    Console.WriteLine("The union of " +  Security1 + " and " + Security2 + " is null." );
                }
                else
                {
                    Console.WriteLine("The union of " + SecurityPerm1.Flags + " and " + 
                        SecurityPerm2.Flags + " = " + 
                        ((SecurityPermission)SecurityPerm3).Flags.ToString());
                }

            }
        }

        return returnValue;

    }
    // Intersect creates and returns a new permission that is the intersection of the current 
    // permission and the permission specified.
    private bool IntersectDemo()
    {
        bool returnValue = true;
        SecurityPermissionFlag Security1,Security2;
        SecurityPermission SecurityPerm1,SecurityPerm2,SecurityPerm3;
        SecurityGenerator SecurityGen1 = new SecurityGenerator();
        SecurityGenerator SecurityGen2 = new SecurityGenerator();
        SecurityGen1.ResetIndex();
        while(SecurityGen1.CreateSecurity(out SecurityPerm1, out Security1)) 
        {
            if(SecurityPerm1 == null) continue;
            Console.WriteLine("**********************************************************\n");
            SecurityGen2.ResetIndex();

            while(SecurityGen2.CreateSecurity(out SecurityPerm2, out Security2)) 
            {
                if(SecurityPerm2 == null) continue;
    
                SecurityPerm3 = (SecurityPermission)SecurityPerm1.Intersect(SecurityPerm2);
                if (SecurityPerm3 != null)
                {
                    Console.WriteLine("The intersection of " + Security1 + " and " + Security2 + " = " + 
                        ((SecurityPermission)SecurityPerm3).Flags.ToString());
                }
                else
                {
                    Console.WriteLine("The intersection of " + Security1 + " and " + Security2 + " is null." );
                }
            }
        }

        return returnValue;
    }
    //Copy creates and returns an identical copy of the current permission.
    private bool CopyDemo()
    {

        bool returnValue = true;

        SecurityPermissionFlag Security1;
        SecurityPermission SecurityPerm1,SecurityPerm2;

        SecurityGenerator SecurityGen1 = new SecurityGenerator();
        SecurityGenerator SecurityGen2 = new SecurityGenerator();

        SecurityGen1.ResetIndex();
        while(SecurityGen1.CreateSecurity(out SecurityPerm1, out Security1)) 
        {
            if(SecurityPerm1 == null) continue;
            SecurityGen2.ResetIndex();
            Console.WriteLine("********************************************************\n");
            try
            {            
                SecurityPerm2 = (SecurityPermission)SecurityPerm1.Copy();
                Console.WriteLine("Result of copy = " + SecurityPerm2.ToString());

            }
            catch(Exception e) 
            {
                Console.WriteLine("Copy failed :" + SecurityPerm1.ToString() + e);
                continue;
            }
        }
        return returnValue;
    }
    // ToXml creates an XML encoding of the permission and its current state; 
    // FromXml reconstructs a permission with the specified state from the XML encoding. 
    private bool ToFromXmlDemo()
    {

        bool returnValue = true;

        SecurityPermissionFlag Security1;
        SecurityPermission SecurityPerm1,SecurityPerm2;
        SecurityGenerator SecurityGen1 = new SecurityGenerator();
        SecurityGenerator SecurityGen2 = new SecurityGenerator();
        SecurityGen1.ResetIndex();
        while(SecurityGen1.CreateSecurity(out SecurityPerm1, out Security1)) 
        {
            if(SecurityPerm1 == null) continue;
            Console.WriteLine("********************************************************\n");
            SecurityGen2.ResetIndex();
            try
            {            
                SecurityPerm2= new SecurityPermission(PermissionState.None);
                SecurityPerm2.FromXml(SecurityPerm1.ToXml());
                Console.WriteLine("Result of ToFromXml = " +
                    SecurityPerm2.ToString());
    
            }
            catch(Exception e) 
            {
                Console.WriteLine("ToFromXml failed :" + SecurityPerm1.ToString() + e);
                continue;
            }
        }

        return returnValue;

    }
    // Invoke all demos.
    public bool runDemo()
    {
        bool returnCode = true;
        bool tempReturnCode;

        // Call the IsSubsetOf demo.
        tempReturnCode= IsSubsetOfDemo();
        if(tempReturnCode)Console.Out.WriteLine("IsSubsetOf demo completed successfully.");
        else Console.Out.WriteLine("IsSubsetOf demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the Union demo.
        tempReturnCode= UnionDemo();
        if(tempReturnCode)Console.Out.WriteLine("Union demo completed successfully.");
        else Console.Out.WriteLine("Union demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the Intersect demo.    
        tempReturnCode= IntersectDemo();
        if(tempReturnCode)Console.Out.WriteLine("Intersect demo completed successfully.");
        else Console.Out.WriteLine("Intersect demo failed.");
        returnCode=tempReturnCode && returnCode;


        // Call the Copy demo.    
        tempReturnCode= CopyDemo();
        if(tempReturnCode)Console.Out.WriteLine("Copy demo completed successfully.");
        else Console.Out.WriteLine("Copy demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the ToFromXml demo.    
        tempReturnCode= ToFromXmlDemo();
        if(tempReturnCode)Console.Out.WriteLine("ToFromXml demo completed successfully.");
        else Console.Out.WriteLine("ToFromXml demo failed.");
        returnCode=tempReturnCode && returnCode;

        return (  returnCode );    
    }
    // Test harness.
    public static void Main(String[] args) 
    {
        try
        {
            SecurityPermissionDemo democase = new SecurityPermissionDemo();
            bool returnCode = democase.runDemo();
            if (returnCode)
            {
                Console.Out.WriteLine("SecurityPermission demo completed successfully.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 100;
            }
            else
            {
                Console.Out.WriteLine("SecurityPermission demo failed.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 101;
            }
        }
        catch(Exception e)
        {
            Console.Out.WriteLine("SecurityPermission demo failed.");
            Console.WriteLine(e.ToString());
            Console.Out.WriteLine("Press the Enter key to exit.");
            string consoleInput = Console.ReadLine();
            System.Environment.ExitCode = 101;
        }
    }
}


// This class generates SecurityPermission objects.

internal  class SecurityGenerator
{


    private SecurityPermissionFlag[] mySecurity = 
        {SecurityPermissionFlag.AllFlags,
         SecurityPermissionFlag.Assertion,
         SecurityPermissionFlag.ControlAppDomain,
         SecurityPermissionFlag.ControlDomainPolicy,
         SecurityPermissionFlag.ControlEvidence,
         SecurityPermissionFlag.ControlPolicy,
         SecurityPermissionFlag.ControlPrincipal,
         SecurityPermissionFlag.ControlThread,
         SecurityPermissionFlag.Execution,
         SecurityPermissionFlag.Infrastructure,
         SecurityPermissionFlag.NoFlags,
         SecurityPermissionFlag.RemotingConfiguration,
         SecurityPermissionFlag.SerializationFormatter,
         SecurityPermissionFlag.SkipVerification,
         SecurityPermissionFlag.UnmanagedCode};

    private int reflectionIndex = 0;

    public SecurityGenerator()
    {
        ResetIndex();
    }

    public void ResetIndex()
    {
        reflectionIndex = 0;
    }
    // CreateSecurity creates a SecurityPermission object.
    public bool CreateSecurity(out SecurityPermission SecurityPerm, out SecurityPermissionFlag Security)
    {

        if(reflectionIndex >= mySecurity.Length) 
        {
            SecurityPerm = new SecurityPermission(PermissionState.None);
            Security=SecurityPermissionFlag.NoFlags;
            reflectionIndex++;
            return false;
        }
        Security = mySecurity[reflectionIndex++];
        try
        {
            SecurityPerm = new SecurityPermission(Security);
            return true;
        } 
        catch(Exception e)
        {
            Console.WriteLine("Cannot create SecurityPermission: " + Security +" "+e);
            SecurityPerm = new SecurityPermission(PermissionState.None);
            Security=SecurityPermissionFlag.NoFlags;
            return true;
        }
    }
} // End of SecurityGenerator.

[C++] 
// This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml and FromXml methods 
// of the SecurityPermission Class.

#using <mscorlib.dll>
using namespace System;
using namespace System::Security; 
using namespace System::Security::Permissions; 
using namespace System::Runtime::InteropServices;

[assembly:CLSCompliant(true)];


// This class generates SecurityPermission objects.

private __gc class SecurityGenerator
{


private:
    SecurityPermissionFlag mySecurity[];
    int reflectionIndex;

public:
    SecurityGenerator()
    {
        SecurityPermissionFlag temp[] = 
        {SecurityPermissionFlag::AllFlags,
        SecurityPermissionFlag::Assertion,
        SecurityPermissionFlag::ControlAppDomain,
        SecurityPermissionFlag::ControlDomainPolicy,
        SecurityPermissionFlag::ControlEvidence,
        SecurityPermissionFlag::ControlPolicy,
        SecurityPermissionFlag::ControlPrincipal,
        SecurityPermissionFlag::ControlThread,
        SecurityPermissionFlag::Execution,
        SecurityPermissionFlag::Infrastructure,
        SecurityPermissionFlag::NoFlags,
        SecurityPermissionFlag::RemotingConfiguration,
        SecurityPermissionFlag::SerializationFormatter,
        SecurityPermissionFlag::SkipVerification,
        SecurityPermissionFlag::UnmanagedCode};
        mySecurity = temp;
        reflectionIndex = 0;
        ResetIndex();
    }

    void ResetIndex()
    {
        reflectionIndex = 0;
    }

    // CreateSecurity creates a SecurityPermission object.
    bool CreateSecurity([Out] SecurityPermission** SecurityPerm, [Out] SecurityPermissionFlag* Security)
    {

        if(reflectionIndex >= mySecurity->Length) 
        {
            *SecurityPerm = new SecurityPermission(PermissionState::None);
            *Security=SecurityPermissionFlag::NoFlags;
            reflectionIndex++;
            return false;
        }
        *Security = mySecurity[reflectionIndex++];
        try
        {
            *SecurityPerm = new SecurityPermission(*Security);
            return true;
        } 
        catch(Exception* e)
        {
            Console::WriteLine(S"Cannot create SecurityPermission: {0} {1}", __box(*Security), e);
            *SecurityPerm = new SecurityPermission(PermissionState::None);
            *Security=SecurityPermissionFlag::NoFlags;
            return true;
        }
    }
}; // End of SecurityGenerator.

public __gc class SecurityPermissionDemo
{
    // IsSubsetOf determines whether the current permission is a subset of the specified permission.
private:
    bool IsSubsetOfDemo()
    {
        bool returnValue = true;
        SecurityPermissionFlag Security1,Security2;
        SecurityPermission* SecurityPerm1;
        SecurityPermission* SecurityPerm2;
        SecurityGenerator* SecurityGen1 = new SecurityGenerator();
        SecurityGenerator* SecurityGen2 = new SecurityGenerator();
        SecurityGen1->ResetIndex();
        while(SecurityGen1->CreateSecurity(&SecurityPerm1, &Security1)) 
        {
            if(SecurityPerm1 == 0) continue;
            SecurityGen2->ResetIndex();
            Console::WriteLine(S"********************************************************\n");

            while(SecurityGen2->CreateSecurity(&SecurityPerm2, &Security2)) 
            {
                if(SecurityPerm2 == 0) continue;
                try
                {            
                    if (SecurityPerm1->IsSubsetOf(SecurityPerm2))
                    {
                        Console::WriteLine(S"{0} is a subset of {1}",
                            __box(SecurityPerm1->Flags), __box(SecurityPerm2->Flags));
                    }
                    else
                    {
                        Console::WriteLine(S"{0} is not a subset of {1}",
                            __box(SecurityPerm1->Flags), __box(SecurityPerm2->Flags));
                    }
                }
                catch(Exception* e) 
                {
                    Console::WriteLine(S"An exception was thrown for subset :{0}\n{1}\n{2}",
                        SecurityPerm1, SecurityPerm2, e);
                    returnValue=false;
                }
            }
        }
        return returnValue;
    }
    // Union creates a new permission that is the union of the current permission and the specified permission.
    bool UnionDemo()
    {
        bool returnValue = true;
        SecurityPermissionFlag Security1,Security2;
        SecurityPermission* SecurityPerm1;
        SecurityPermission* SecurityPerm2;
        IPermission* SecurityPerm3;
        SecurityGenerator* SecurityGen1 = new SecurityGenerator();
        SecurityGenerator* SecurityGen2 = new SecurityGenerator();
        SecurityGen1->ResetIndex();
        while(SecurityGen1->CreateSecurity(&SecurityPerm1, &Security1)) 
        {
            if(SecurityPerm1 == 0) continue;
            Console::WriteLine(S"**********************************************************\n");
            SecurityGen2->ResetIndex();

            while(SecurityGen2->CreateSecurity(&SecurityPerm2, &Security2)) 
            {
                if(SecurityPerm2 == 0) continue;
                SecurityPerm3 = dynamic_cast<SecurityPermission*>(SecurityPerm1->Union(SecurityPerm2));
                SecurityPerm3 = SecurityPerm1->Union(SecurityPerm2);

                if(SecurityPerm3 == 0)  
                {
                    Console::WriteLine(S"The union of {0} and {1} is null.", __box(Security1), __box(Security2));
                }
                else
                {
                    Console::WriteLine(S"The union of {0} and {1} = {2}",
                        __box(SecurityPerm1->Flags), __box(SecurityPerm2->Flags),
                        __box((dynamic_cast<SecurityPermission*>(SecurityPerm3))->Flags));
                }

            }
        }

        return returnValue;

    }
    // Intersect creates and returns a new permission that is the intersection of the current 
    // permission and the permission specified.
    bool IntersectDemo()
    {
        bool returnValue = true;
        SecurityPermissionFlag Security1,Security2;
        SecurityPermission* SecurityPerm1;
        SecurityPermission* SecurityPerm2;
        SecurityPermission* SecurityPerm3;
        SecurityGenerator* SecurityGen1 = new SecurityGenerator();
        SecurityGenerator* SecurityGen2 = new SecurityGenerator();
        SecurityGen1->ResetIndex();
        while(SecurityGen1->CreateSecurity(&SecurityPerm1, &Security1)) 
        {
            if(SecurityPerm1 == 0) continue;
            Console::WriteLine(S"**********************************************************\n");
            SecurityGen2->ResetIndex();

            while(SecurityGen2->CreateSecurity(&SecurityPerm2, &Security2)) 
            {
                if(SecurityPerm2 == 0) continue;

                SecurityPerm3 = dynamic_cast<SecurityPermission*>(SecurityPerm1->Intersect(SecurityPerm2));
                if (SecurityPerm3 != 0)
                {
                    Console::WriteLine(S"The intersection of {0} and {1} = {2}",
                        __box(Security1), __box(Security2),
                        __box((dynamic_cast<SecurityPermission*>(SecurityPerm3))->Flags));
                }
                else
                {
                    Console::WriteLine(S"The intersection of {0} and {1} is null.", __box(Security1), __box(Security2));
                }
            }
        }

        return returnValue;
    }
    //Copy creates and returns an identical copy of the current permission.
    bool CopyDemo()
    {

        bool returnValue = true;

        SecurityPermissionFlag Security1;
        SecurityPermission* SecurityPerm1;
        SecurityPermission* SecurityPerm2;

        SecurityGenerator* SecurityGen1 = new SecurityGenerator();
        SecurityGenerator* SecurityGen2 = new SecurityGenerator();

        SecurityGen1->ResetIndex();
        while(SecurityGen1->CreateSecurity(&SecurityPerm1, &Security1)) 
        {
            if(SecurityPerm1 == 0) continue;
            SecurityGen2->ResetIndex();
            Console::WriteLine(S"********************************************************\n");
            try
            {            
                SecurityPerm2 = dynamic_cast<SecurityPermission*>(SecurityPerm1->Copy());
                Console::WriteLine(S"Result of copy = {0}", SecurityPerm2);

            }
            catch(Exception* e) 
            {
                Console::WriteLine(S"Copy failed :{0}{1}", SecurityPerm1, e);
                continue;
            }
        }
        return returnValue;
    }
    // ToXml creates an XML encoding of the permission and its current state; 
    // FromXml reconstructs a permission with the specified state from the XML encoding. 
    bool ToFromXmlDemo()
    {

        bool returnValue = true;

        SecurityPermissionFlag Security1;
        SecurityPermission* SecurityPerm1;
        SecurityPermission* SecurityPerm2;
        SecurityGenerator* SecurityGen1 = new SecurityGenerator();
        SecurityGenerator* SecurityGen2 = new SecurityGenerator();
        SecurityGen1->ResetIndex();
        while(SecurityGen1->CreateSecurity(&SecurityPerm1, &Security1)) 
        {
            if(SecurityPerm1 == 0) continue;
            Console::WriteLine(S"********************************************************\n");
            SecurityGen2->ResetIndex();
            try
            {            
                SecurityPerm2= new SecurityPermission(PermissionState::None);
                SecurityPerm2->FromXml(SecurityPerm1->ToXml());
                Console::WriteLine(S"Result of ToFromXml = {0}", SecurityPerm2);

            }
            catch(Exception* e) 
            {
                Console::WriteLine(S"ToFromXml failed :{0}{1}", SecurityPerm1, e);
                continue;
            }
        }

        return returnValue;

    }
    // Invoke all demos.
public:
    bool runDemo()
    {
        bool returnCode = true;
        bool tempReturnCode;

        // Call the IsSubsetOf demo.
        tempReturnCode= IsSubsetOfDemo();
        if(tempReturnCode)Console::Out->WriteLine(S"IsSubsetOf demo completed successfully.");
        else Console::Out->WriteLine(S"IsSubsetOf demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the Union demo.
        tempReturnCode= UnionDemo();
        if(tempReturnCode)Console::Out->WriteLine(S"Union demo completed successfully.");
        else Console::Out->WriteLine(S"Union demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the Intersect demo.    
        tempReturnCode= IntersectDemo();
        if(tempReturnCode)Console::Out->WriteLine(S"Intersect demo completed successfully.");
        else Console::Out->WriteLine(S"Intersect demo failed.");
        returnCode=tempReturnCode && returnCode;


        // Call the Copy demo.    
        tempReturnCode= CopyDemo();
        if(tempReturnCode)Console::Out->WriteLine(S"Copy demo completed successfully.");
        else Console::Out->WriteLine(S"Copy demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the ToFromXml demo.    
        tempReturnCode= ToFromXmlDemo();
        if(tempReturnCode)Console::Out->WriteLine(S"ToFromXml demo completed successfully.");
        else Console::Out->WriteLine(S"ToFromXml demo failed.");
        returnCode=tempReturnCode && returnCode;

        return (  returnCode );    
    }
};
// Test harness.
int main() 
{
    try
    {
        SecurityPermissionDemo* democase = new SecurityPermissionDemo();
        bool returnCode = democase->runDemo();
        if (returnCode)
        {
            Console::Out->WriteLine(S"SecurityPermission demo completed successfully.");
            Console::Out->WriteLine(S"Press the Enter key to exit.");
            String* consoleInput = Console::ReadLine();
            System::Environment::ExitCode = 100;
        }
        else
        {
            Console::Out->WriteLine(S"SecurityPermission demo failed.");
            Console::Out->WriteLine(S"Press the Enter key to exit.");
            String* consoleInput = Console::ReadLine();
            System::Environment::ExitCode = 101;
        }
    }
    catch(Exception* e)
    {
        Console::Out->WriteLine(S"SecurityPermission demo failed.");
        Console::WriteLine(e);
        Console::Out->WriteLine(S"Press the Enter key to exit.");
        String* consoleInput = Console::ReadLine();
        System::Environment::ExitCode = 101;
    }
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Security.Permissions

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: Mscorlib (in Mscorlib.dll)

See Also

SecurityPermission Members | System.Security.Permissions Namespace | Permissions | Requesting Permissions | SecurityPermissionAttribute | SecurityPermissionFlag

Show:
© 2014 Microsoft