Export (0) Print
Expand All

FileCodeGroup Class

Grants permission to manipulate files located in the code assemblies to code assemblies that match the membership condition. This class cannot be inherited.

Namespace: System.Security.Policy
Assembly: mscorlib (in mscorlib.dll)

[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public sealed class FileCodeGroup : CodeGroup
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class FileCodeGroup extends CodeGroup
SerializableAttribute 
ComVisibleAttribute(true) 
public final class FileCodeGroup extends CodeGroup

Code groups are the building blocks of code access security policy. Each policy level consists of a root code group that can have child code groups. Each child code group can have their own child code groups; this behavior extends to any number of levels, forming a tree. Each code group has a membership condition that determines if a given assembly belongs to it based on the evidence for that assembly. Only code groups whose membership conditions match a given assembly and their child code groups apply policy.

FileCodeGroup has the same child matching semantics as UnionCodeGroup. However, FileCodeGroup returns a permission set containing a dynamically-calculated FileIOPermission that grants file access to the directory from which the code is run; UnionCodeGroup only returns a static permission set. The type of file access granted is passed as a parameter to the constructor.

This code group only matches assemblies run over a file protocol, that is, assemblies that have URLs that point to a file or UNC path.

The following example shows the use of members of the FileCodeGroup class.

using System;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;

class Members
{
    [STAThread]
    static void Main(string[] args)
    {
        FileCodeGroup fileCodeGroup = constructDefaultGroup();
        
        // Create a deep copy of the FileCodeGroup.
        FileCodeGroup copyCodeGroup = (FileCodeGroup)fileCodeGroup.Copy();

        CompareTwoCodeGroups(fileCodeGroup, copyCodeGroup);

        addPolicy(ref fileCodeGroup);
        addXmlMember(ref fileCodeGroup);
        updateMembershipCondition(ref fileCodeGroup);
        addChildCodeGroup(ref fileCodeGroup);

        Console.Write("Comparing the resolved code group ");
        Console.WriteLine("with the initial code group.");
        FileCodeGroup resolvedCodeGroup =
            ResolveGroupToEvidence(fileCodeGroup);
        if (CompareTwoCodeGroups(fileCodeGroup, resolvedCodeGroup))
        {
            PrintCodeGroup(resolvedCodeGroup);
        }
        else
        {
            PrintCodeGroup(fileCodeGroup);
        }
        
        Console.WriteLine("This sample completed successfully; " +
            "press Enter to exit.");
        Console.ReadLine();
    }

    // Construct a new FileCodeGroup with Read, Write, Append 
    // and PathDiscovery access.
    private static FileCodeGroup constructDefaultGroup()
    {
        // Construct a new file code group that has complete access to
        // files in the specified path.
        FileCodeGroup fileCodeGroup = 
            new FileCodeGroup(
            new AllMembershipCondition(),
            FileIOPermissionAccess.AllAccess);

        // Set the name of the file code group.
        fileCodeGroup.Name = "TempCodeGroup";

        // Set the description of the file code group.
        fileCodeGroup.Description = "Temp folder permissions group";

        // Retrieve the string representation of the  fileCodeGroups 
        // attributes. FileCodeGroup does not use AttributeString, so the
        // value should be null.
        if (fileCodeGroup.AttributeString != null)
        {
            throw new NullReferenceException(
                "The AttributeString property should be null.");
        }

        return fileCodeGroup;
    }

    // Add file permission to restrict write access to all files on the
    // local machine.
    private static void addPolicy(ref FileCodeGroup fileCodeGroup)
    {
        // Set the PolicyStatement property to a policy with read access to
        // the root directory of drive C.
        FileIOPermission rootFilePermissions = 
            new FileIOPermission(PermissionState.None);
        rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read;
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read,"C:\\");

        NamedPermissionSet namedPermissions =
            new NamedPermissionSet("RootPermissions");
        namedPermissions.AddPermission(rootFilePermissions);
        
        fileCodeGroup.PolicyStatement =
            new PolicyStatement(namedPermissions);
    }

    // Set the membership condition of the specified FileCodeGroup 
    // to the Intranet zone.
    private static void updateMembershipCondition(
        ref FileCodeGroup fileCodeGroup)
    {
        ZoneMembershipCondition zoneCondition =
            new ZoneMembershipCondition(SecurityZone.Intranet);
        fileCodeGroup.MembershipCondition = zoneCondition;
    }

    // Add a child group with read-access file permission to the specified 
    // code group.
    private static void addChildCodeGroup(ref FileCodeGroup fileCodeGroup)
    {
        // Create a file code group with read-access permission.
        FileCodeGroup tempFolderCodeGroup = new FileCodeGroup(
            new AllMembershipCondition(), 
            FileIOPermissionAccess.Read);

        // Set the name of the child code group and add it to 
        // the specified code group.
        tempFolderCodeGroup.Name = "Read-only group";
        fileCodeGroup.AddChild(tempFolderCodeGroup);
    }

    // Compare the two specified file code groups for equality.
    private static bool CompareTwoCodeGroups(
        FileCodeGroup firstCodeGroup, FileCodeGroup secondCodeGroup)
    {
        if (firstCodeGroup.Equals(secondCodeGroup))
        {
            Console.WriteLine("The two code groups are equal.");
            return true;
        }
        else 
        {
            Console.WriteLine("The two code groups are not equal.");
            return false;
        }
    }

    // Retrieve the resolved policy based on Evidence from the executing 
    // assembly found in the specified code group.
    private static string ResolveEvidence(CodeGroup fileCodeGroup)
    {
        string policyString = "";

        // Resolve the policy based on evidence in the executing assembly.
        Assembly assembly = Assembly.GetExecutingAssembly();
        Evidence executingEvidence = assembly.Evidence;

        PolicyStatement policy = fileCodeGroup.Resolve(executingEvidence);

        if (policy != null)
        {
            policyString = policy.ToString();
        }

        return policyString;
    }

    // Retrieve the resolved code group based on the Evidence from 
    // the executing assembly found in the specified code group.
    private static FileCodeGroup ResolveGroupToEvidence(
        FileCodeGroup fileCodeGroup)
    {
        // Resolve matching code groups to the executing assembly.
        Assembly assembly = Assembly.GetExecutingAssembly();
        Evidence evidence = assembly.Evidence;
        CodeGroup codeGroup = 
            fileCodeGroup.ResolveMatchingCodeGroups(evidence);

        return (FileCodeGroup)codeGroup;
    }

    // If a domain attribute is not found in the specified FileCodeGroup,
    // add a child XML element identifying a custom membership condition.
    private static void addXmlMember(ref FileCodeGroup fileCodeGroup)
    {
        SecurityElement xmlElement = fileCodeGroup.ToXml();

        SecurityElement rootElement = new SecurityElement("CodeGroup");

        if (xmlElement.Attribute("domain") == null) 
        {
            SecurityElement newElement = 
                new SecurityElement("CustomMembershipCondition");
            newElement.AddAttribute("class","CustomMembershipCondition");
            newElement.AddAttribute("version","1");
            newElement.AddAttribute("domain","contoso.com");

            rootElement.AddChild(newElement);

            fileCodeGroup.FromXml(rootElement);
        }

        Console.WriteLine("Added a custom membership condition:");
        Console.WriteLine(rootElement.ToString());
    }


    // Print the properties of the specified code group to the console.
    private static void PrintCodeGroup(CodeGroup codeGroup)
    {
        // Compare the type of the specified object with the FileCodeGroup
        // type.
        if (!codeGroup.GetType().Equals(typeof(FileCodeGroup)))
        {
            throw new ArgumentException("Expected the FileCodeGroup type.");
        }
        
        string codeGroupName = codeGroup.Name;
        string membershipCondition = codeGroup.MembershipCondition.ToString();
        string permissionSetName = codeGroup.PermissionSetName;

        int hashCode = codeGroup.GetHashCode();

        string mergeLogic = "";
        if (codeGroup.MergeLogic.Equals("Union"))
        {
            mergeLogic = " with Union merge logic";
        }

        // Retrieve the class path for FileCodeGroup.
        string fileGroupClass = codeGroup.ToString();

        // Write summary to the console window.
        Console.WriteLine("\n*** " + fileGroupClass + " summary ***");
        Console.Write("A FileCodeGroup named ");
        Console.Write(codeGroupName + mergeLogic);
        Console.Write(" has been created with hash code" + hashCode + ".");
        Console.Write("This code group contains a " + membershipCondition);
        Console.Write(" membership condition with the ");
        Console.Write(permissionSetName + " permission set. ");

        Console.Write("The code group has the following security policy: ");
        Console.WriteLine(ResolveEvidence(codeGroup));

        
        int childCount = codeGroup.Children.Count;
        if (childCount > 0 )
        {
            Console.Write("There are " + childCount);
            Console.WriteLine(" child code groups in this code group.");

            // Iterate through the child code groups to display their names
            // and remove them from the specified code group.
            for (int i=0; i < childCount; i++)
            {
                // Get child code group as type FileCodeGroup.
                FileCodeGroup childCodeGroup = 
                    (FileCodeGroup)codeGroup.Children[i];
                
                Console.Write("Removing the " + childCodeGroup.Name + ".");
                // Remove child code group.
                codeGroup.RemoveChild(childCodeGroup);
            }

            Console.WriteLine();
        }
        else
        {
            Console.Write("There are no child code groups");
            Console.WriteLine(" in this code group.");
        }
    }
}
//
// This sample produces the following output:
//
// The two code groups are equal.
// Added a custom membership condition:
// <CodeGroup>
// <CustomMembershipCondition class="CustomMembershipCondition"
//                                version="1"
//                                domain="contoso.com"/>
//                                </CodeGroup>
// Comparing the resolved code group with the initial code group.
// The two code groups are not equal.
// 
// *** System.Security.Policy.FileCodeGroup summary ***
// A FileCodeGroup named  with Union merge logic has been created with hash
// code 113151473. This code group contains a Zone - Intranet membership
// condition with the Same directory FileIO - NoAccess permission set. The
// code group has the following security policy:
// There are 1 child code groups in this code group.
// Removing the Read-only group.
// This sample completed successfully; press Enter to exit.

import System.*;
import System.Security.*;
import System.Security.Policy.*;
import System.Security.Permissions.*;
import System.Reflection.*;

class Members
{
    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        FileCodeGroup fileCodeGroup = ConstructDefaultGroup();
        // Create a deep copy of the FileCodeGroup.
        FileCodeGroup copyCodeGroup = (FileCodeGroup)(fileCodeGroup.Copy());
        CompareTwoCodeGroups(fileCodeGroup, copyCodeGroup);
        AddPolicy(fileCodeGroup);
        AddXmlMember(fileCodeGroup);
        UpdateMembershipCondition(fileCodeGroup);
        AddChildCodeGroup(fileCodeGroup);

        Console.Write("Comparing the resolved code group ");
        Console.WriteLine("with the initial code group.");
        FileCodeGroup resolvedCodeGroup = ResolveGroupToEvidence(fileCodeGroup);
        if (CompareTwoCodeGroups(fileCodeGroup, resolvedCodeGroup)) {
            PrintCodeGroup(resolvedCodeGroup);
        }
        else {
            PrintCodeGroup(fileCodeGroup);
        }

        Console.WriteLine("This sample completed successfully; " 
            + "press Enter to exit.");
        Console.ReadLine();
    } //main

    // Construct a new FileCodeGroup with Read, Write, Append 
    // and PathDiscovery access.
    private static FileCodeGroup ConstructDefaultGroup()
    {
        // Construct a new file code group that has complete access to
        // files in the specified path.
        FileCodeGroup fileCodeGroup = new FileCodeGroup(new 
            AllMembershipCondition(), FileIOPermissionAccess.AllAccess);
        // Set the name of the file code group.
        fileCodeGroup.set_Name("TempCodeGroup");
        // Set the description of the file code group.
        fileCodeGroup.set_Description("Temp folder permissions group");
        // Retrieve the string representation of the  fileCodeGroups 
        // attributes. FileCodeGroup does not use AttributeString, so the
        // value should be null.
        if (fileCodeGroup.get_AttributeString() != null) {
            throw new NullReferenceException("The AttributeString property "
                + "should be null.");
        }
        return fileCodeGroup;
    } //ConstructDefaultGroup

    // Add file permission to restrict write access to all files on the
    // local machine.
    private static void AddPolicy(FileCodeGroup fileCodeGroup)
    {
        // Set the PolicyStatement property to a policy with read access to
        // the root directory of drive C.
        FileIOPermission rootFilePermissions = new FileIOPermission(
            PermissionState.None);
        rootFilePermissions.set_AllLocalFiles(FileIOPermissionAccess.Read);
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\");

        NamedPermissionSet namedPermissions = new NamedPermissionSet(
            "RootPermissions");
        namedPermissions.AddPermission(rootFilePermissions);
        fileCodeGroup.set_PolicyStatement(new PolicyStatement(namedPermissions));
    } //AddPolicy
   
    // Set the membership condition of the specified FileCodeGroup 
    // to the Intranet zone.
    private static void UpdateMembershipCondition(FileCodeGroup fileCodeGroup)
    {
        ZoneMembershipCondition zoneCondition = new ZoneMembershipCondition(
            SecurityZone.Intranet);
        fileCodeGroup.set_MembershipCondition(zoneCondition);
    } //UpdateMembershipCondition
    
    // Add a child group with read-access file permission to the specified 
    // code group.
    private static void AddChildCodeGroup(FileCodeGroup fileCodeGroup)
    {
        // Create a file code group with read-access permission.
        FileCodeGroup tempFolderCodeGroup = new FileCodeGroup(new 
            AllMembershipCondition(), FileIOPermissionAccess.Read);
        // Set the name of the child code group and add it to 
        // the specified code group.
        tempFolderCodeGroup.set_Name("Read-only group");
        fileCodeGroup.AddChild(tempFolderCodeGroup);
    } //AddChildCodeGroup

    // Compare the two specified file code groups for equality.
    private static boolean CompareTwoCodeGroups(FileCodeGroup firstCodeGroup,
        FileCodeGroup secondCodeGroup)
    {
        if (firstCodeGroup.Equals(secondCodeGroup)) {
            Console.WriteLine("The two code groups are equal.");
            return true;
        }
        else {
            Console.WriteLine("The two code groups are not equal.");
            return false;
        }
    } //CompareTwoCodeGroups

    // Retrieve the resolved policy based on Evidence from the executing 
    // assembly found in the specified code group.
    private static String ResolveEvidence(CodeGroup fileCodeGroup)
    {
        String policyString = "";
        // Resolve the policy based on evidence in the executing assembly.
        Assembly assembly = Assembly.GetExecutingAssembly();
        Evidence executingEvidence = assembly.get_Evidence();
        PolicyStatement policy = fileCodeGroup.Resolve(executingEvidence);
        if (policy != null) {
            policyString = policy.ToString();
        }
        return policyString;
    } //ResolveEvidence

    // Retrieve the resolved code group based on the Evidence from 
    // the executing assembly found in the specified code group.
    private static FileCodeGroup ResolveGroupToEvidence(FileCodeGroup 
        fileCodeGroup)
    {
        // Resolve matching code groups to the executing assembly.
        Assembly assembly = Assembly.GetExecutingAssembly();
        Evidence evidence = assembly.get_Evidence();
        CodeGroup codeGroup = fileCodeGroup.ResolveMatchingCodeGroups(evidence);
        return ((FileCodeGroup)(codeGroup));
    } //ResolveGroupToEvidence

    // If a domain attribute is not found in the specified FileCodeGroup,
    // add a child XML element identifying a custom membership condition.
    private static void AddXmlMember(FileCodeGroup fileCodeGroup)
    {
        SecurityElement xmlElement = fileCodeGroup.ToXml();
        SecurityElement rootElement = new SecurityElement("CodeGroup");
        if (xmlElement.Attribute("domain") == null) {
            SecurityElement newElement = new SecurityElement(
                "CustomMembershipCondition");
            newElement.AddAttribute("class", "CustomMembershipCondition");
            newElement.AddAttribute("version", "1");
            newElement.AddAttribute("domain", "contoso.com");
            rootElement.AddChild(newElement);
            fileCodeGroup.FromXml(rootElement);
        }
        Console.WriteLine("Added a custom membership condition:");
        Console.WriteLine(rootElement.ToString());
    } //AddXmlMember

    // Print the properties of the specified code group to the console.
    private static void PrintCodeGroup(CodeGroup codeGroup)
    {
        // Compare the type of the specified object with the FileCodeGroup
        // type.
        if (!(codeGroup.GetType().Equals(FileCodeGroup.class.ToType()))) {
            throw new ArgumentException("Expected the FileCodeGroup type.");
        }
        String codeGroupName = codeGroup.get_Name();
        String membershipCondition = codeGroup.get_MembershipCondition().
            ToString();
        String permissionSetName = codeGroup.get_PermissionSetName();
        int hashCode = codeGroup.GetHashCode();
        String mergeLogic = "";
        if (codeGroup.get_MergeLogic().Equals("Union")) {
            mergeLogic = " with Union merge logic";
        }
     
        // Retrieve the class path for FileCodeGroup.
        String fileGroupClass = codeGroup.ToString();
        // Write summary to the console window.
        Console.WriteLine("\n*** " + fileGroupClass + " summary ***");
        Console.Write("A FileCodeGroup named ");
        Console.Write(codeGroupName + mergeLogic);
        Console.Write(" has been created with hash code" + hashCode + ".");
        Console.Write("This code group contains a " + membershipCondition);
        Console.Write(" membership condition with the ");
        Console.Write(permissionSetName + " permission set. ");
        Console.Write("The code group has the following security policy: ");
        Console.WriteLine(ResolveEvidence(codeGroup));

        int childCount = codeGroup.get_Children().get_Count();
        if (childCount > 0) {
            Console.Write("There are " + childCount);
            Console.WriteLine(" child code groups in this code group.");
            // Iterate through the child code groups to display their names
            // and remove them from the specified code group.
            for (int i = 0; i < childCount; i++) {
                // Get child code group as type FileCodeGroup.
                FileCodeGroup childCodeGroup = (FileCodeGroup)(codeGroup.
                    get_Children().get_Item(i));
                Console.Write("Removing the " + childCodeGroup.get_Name() + ".");
                // Remove child code group.
                codeGroup.RemoveChild(childCodeGroup);
            }
            Console.WriteLine();
        }
        else {
            Console.Write("There are no child code groups");
            Console.WriteLine(" in this code group.");
        }
    } //PrintCodeGroup
} //Members
//
// This sample produces the following output:
//
// The two code groups are equal.
// Added a custom membership condition:
// <CodeGroup>
// <CustomMembershipCondition class="CustomMembershipCondition"
//                                version="1"
//                                domain="contoso.com"/>
//                                </CodeGroup>
// Comparing the resolved code group with the initial code group.
// The two code groups are not equal.
// 
// *** System.Security.Policy.FileCodeGroup summary ***
// A FileCodeGroup named  with Union merge logic has been created with hash
// code 113151473. This code group contains a Zone - Intranet membership
// condition with the Same directory FileIO - NoAccess permission set. The
// code group has the following security policy:
// There are 1 child code groups in this code group.
// Removing the Read-only group.
// This sample completed successfully; press Enter to exit.

System.Object
   System.Security.Policy.CodeGroup
    System.Security.Policy.FileCodeGroup

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 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft