SecurityElement Klasa

Definicja

Reprezentuje model obiektów XML do kodowania obiektów zabezpieczeń. Klasa ta nie może być dziedziczona.

C#
public sealed class SecurityElement
C#
[System.Serializable]
public sealed class SecurityElement
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SecurityElement
Dziedziczenie
SecurityElement
Atrybuty

Przykłady

W poniższym przykładzie przedstawiono użycie składowych SecurityElement klasy.

C#
using System;
using System.Security;
using System.Collections;

class SecurityElementMembers
{
    [STAThread]
    static void Main(string[] args)
    {
        SecurityElement xmlRootElement =
            new SecurityElement("RootTag", "XML security tree");

        AddAttribute(xmlRootElement,"creationdate",DateTime.Now.ToString());
        AddChildElement(xmlRootElement,"destroytime",
            DateTime.Now.AddSeconds(1.0).ToString());

        SecurityElement windowsRoleElement =
            new SecurityElement("WindowsMembership.WindowsRole");

        windowsRoleElement.AddAttribute("version","1.00");

        // Add a child element and a creationdate attribute.
        AddChildElement(windowsRoleElement,"BabyElement",
            "This is a child element");
        AddAttribute(windowsRoleElement,"creationdate",
            DateTime.Now.ToString());

        xmlRootElement.AddChild(windowsRoleElement);

        CompareAttributes(xmlRootElement, "creationdate");
        ConvertToHashTable(xmlRootElement);

        DisplaySummary(xmlRootElement);

        // Determine if the security element is too old to keep.
        xmlRootElement = DestroyTree(xmlRootElement);
        if (xmlRootElement != null)
        {
            string elementInXml = xmlRootElement.ToString();
            Console.WriteLine(elementInXml);
        }

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

    // Add an attribute to the specified security element.
    private static SecurityElement AddAttribute(
        SecurityElement xmlElement,
        string attributeName,
        string attributeValue)
    {
        if (xmlElement != null)
        {
            // Verify that the attribute name and value are valid XML formats.
            if (SecurityElement.IsValidAttributeName(attributeName) &&
                SecurityElement.IsValidAttributeValue(attributeValue))
            {
                // Add the attribute to the security element.
                xmlElement.AddAttribute(attributeName, attributeValue);
            }
        }
        return xmlElement;
    }

    // Add a child element to the specified security element.
    private static SecurityElement AddChildElement(
        SecurityElement parentElement,
        string tagName,
        string tagText)
    {
        if (parentElement != null)
        {
            // Ensure that the tag text is in valid XML format.
            if (!SecurityElement.IsValidText(tagText))
            {
                // Replace invalid text with valid XML text
                // to enforce proper XML formatting.
                tagText = SecurityElement.Escape(tagText);
            }

            // Determine whether the tag is in valid XML format.
            if (SecurityElement.IsValidTag(tagName))
            {
                SecurityElement childElement;
                childElement = parentElement.SearchForChildByTag(tagName);

                if (childElement != null)
                {
                    String elementText;
                    elementText = parentElement.SearchForTextOfTag(tagName);

                    if (!elementText.Equals(tagText))
                    {
                        // Add child element to the parent security element.
                        parentElement.AddChild(
                            new SecurityElement(tagName, tagText));
                    }
                }
                else
                {
                    // Add child element to the parent security element.
                    parentElement.AddChild(
                        new SecurityElement(tagName, tagText));
                }
            }
        }
        return parentElement;
    }

    // Create and display a summary sentence
    // about the specified security element.
    private static void DisplaySummary(SecurityElement xmlElement)
    {
        // Retrieve tag name for the security element.
        string xmlTreeName = xmlElement.Tag.ToString();

        // Retrieve tag text for the security element.
        string xmlTreeDescription = xmlElement.Text;

        // Retrieve value of the creationdate attribute.
        string xmlCreationDate = xmlElement.Attribute("creationdate");

        // Retrieve the number of children under the security element.
        string childrenCount = xmlElement.Children.Count.ToString();

        string outputMessage = "The security XML tree named " + xmlTreeName;
        outputMessage += "(" + xmlTreeDescription + ")";
        outputMessage += " was created on " + xmlCreationDate + " and ";
        outputMessage += "contains " + childrenCount + " child elements.";

        Console.WriteLine(outputMessage);
    }

    // Compare the first two occurrences of an attribute
    // in the specified security element.
    private static void CompareAttributes(
        SecurityElement xmlElement, string attributeName)
    {
        // Create a hash table containing the security element's attributes.
        Hashtable attributeKeys = xmlElement.Attributes;
        string attributeValue = attributeKeys[attributeName].ToString();

        foreach(SecurityElement xmlChild in xmlElement.Children)
        {
            if (attributeValue.Equals(xmlChild.Attribute(attributeName)))
            {
                // The security elements were created at the exact same time.
            }
        }
    }

    // Convert the contents of the specified security element
    // to hash codes stored in a hash table.
    private static void ConvertToHashTable(SecurityElement xmlElement)
    {
        // Create a hash table to hold hash codes of the security elements.
        Hashtable xmlAsHash = new Hashtable();
        int rootIndex = xmlElement.GetHashCode();
        xmlAsHash.Add(rootIndex, "root");

        int parentNum = 0;

        foreach(SecurityElement xmlParent in xmlElement.Children)
        {
            parentNum++;
            xmlAsHash.Add(xmlParent.GetHashCode(), "parent" + parentNum);
            if ((xmlParent.Children != null) &&
                (xmlParent.Children.Count > 0))
            {
                int childNum = 0;
                foreach(SecurityElement xmlChild in xmlParent.Children)
                {
                    childNum++;
                    xmlAsHash.Add(xmlChild.GetHashCode(), "child" + childNum);
                }
            }
        }
    }

    // Delete the specified security element if the current time is past
    // the time stored in the destroytime tag.
    private static SecurityElement DestroyTree(SecurityElement xmlElement)
    {
        SecurityElement localXmlElement = xmlElement;
        SecurityElement destroyElement =
            localXmlElement.SearchForChildByTag("destroytime");

        // Verify that a destroytime tag exists.
        if (localXmlElement.SearchForChildByTag("destroytime") != null)
        {
            // Retrieve the destroytime text to get the time
            // the tree can be destroyed.
            string storedDestroyTime =
                localXmlElement.SearchForTextOfTag("destroytime");

            DateTime destroyTime = DateTime.Parse(storedDestroyTime);
            if (DateTime.Now > destroyTime)
            {
                localXmlElement = null;
                Console.WriteLine("The XML security tree has been deleted.");
            }
        }

        // Verify that xmlElement is of type SecurityElement.
        if (xmlElement.GetType().Equals(
            typeof(System.Security.SecurityElement)))
        {
            // Determine whether the localXmlElement object
            // differs from xmlElement.
            if (xmlElement.Equals(localXmlElement))
            {
                // Verify that the tags, attributes and children of the
                // two security elements are identical.
                if (xmlElement.Equal(localXmlElement))
                {
                    // Return the original security element.
                    return xmlElement;
                }
            }
        }

        // Return the modified security element.
        return localXmlElement;
    }
}
//
// This sample produces the following output:
//
// The security XML tree named RootTag(XML security tree)
// was created on 2/23/2004 1:23:00 PM and contains 2 child elements.
//<RootTag creationdate="2/23/2004 1:23:00 PM">XML security tree
//   <destroytime>2/23/2004 1:23:01 PM</destroytime>
//   <WindowsMembership.WindowsRole version="1.00"
//                                  creationdate="2/23/2004 1:23:00 PM">
//      <BabyElement>This is a child element.</BabyElement>
//
//This sample completed successfully; press Exit to continue.

Uwagi

Ta klasa ma być uproszczoną implementacją prostego modelu obiektów XML do użycia w systemie zabezpieczeń, a nie jako ogólnego modelu obiektów XML. W tej dokumentacji założono podstawową wiedzę na temat kodu XML.

Prosty model obiektów XML dla elementu składa się z następujących części:

  • Tag jest nazwą elementu.

  • Atrybuty to zero lub więcej par atrybutów nazwa/wartość w elemecie.

  • Elementy podrzędne to zero lub więcej elementów zagnieżdżonych w obrębie <tag> elementów i </tag>.

Zdecydowanie zaleca się, aby reprezentacja XML oparta na atrybutach była używana do wyrażania elementów zabezpieczeń i ich wartości. Oznacza to, że właściwości elementu są wyrażane jako atrybuty, a wartości właściwości są wyrażane jako wartości atrybutów. Unikaj zagnieżdżania tekstu w tagach. W przypadku każdej <tag>text</tag> reprezentacji reprezentacja typu <tag value="text"/> jest zwykle dostępna. Użycie tej reprezentacji XML opartej na atrybutach zwiększa czytelność i umożliwia łatwą przenośność WMI wynikowej serializacji XML.

Nazwa atrybutu musi być jedną lub dłuższą i nie może być null. Jeśli jest używana reprezentacja wartości opartej na elementach, elementy z ciągiem null tekstowym reprezentowanym w formularzu<tag/>; w przeciwnym razie tekst jest rozdzielany przez <tag> tokeny i .</tag> Oba formularze można łączyć z atrybutami, które są wyświetlane, jeśli istnieją.

Tagi, atrybuty i tekst elementów, jeśli istnieją, są zawsze uwzględniane wielkość liter. Formularz XML zawiera cudzysłów i ucieczki w razie potrzeby. Wartości ciągów, które zawierają znaki nieprawidłowe do użycia w wyniku XML w elemecie ArgumentException. Te reguły mają zastosowanie do wszystkich właściwości i metod.

Uwaga

Ze względów wydajności ważność znaku jest sprawdzana tylko wtedy, gdy element jest zakodowany w formularzu tekstowym XML, a nie na każdym zestawie właściwości lub metody. Metody statyczne umożliwiają jawne sprawdzanie w razie potrzeby.

Konstruktory

SecurityElement(String)

Inicjuje SecurityElement nowe wystąpienie klasy z określonym tagiem.

SecurityElement(String, String)

Inicjuje SecurityElement nowe wystąpienie klasy z określonym tagiem i tekstem.

Właściwości

Attributes

Pobiera lub ustawia atrybuty elementu XML jako pary nazwa/wartość.

Children

Pobiera lub ustawia tablicę elementów podrzędnych elementu XML.

Tag

Pobiera lub ustawia nazwę tagu elementu XML.

Text

Pobiera lub ustawia tekst w elemecie XML.

Metody

AddAttribute(String, String)

Dodaje atrybut name/value do elementu XML.

AddChild(SecurityElement)

Dodaje element podrzędny do elementu XML.

Attribute(String)

Znajduje atrybut według nazwy w elemecie XML.

Copy()

Tworzy i zwraca identyczną kopię bieżącego SecurityElement obiektu.

Equal(SecurityElement)

Porównuje dwa obiekty elementów XML pod kątem równości.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
Escape(String)

Zastępuje nieprawidłowe znaki XML w ciągu prawidłowym odpowiednikiem XML.

FromString(String)

Tworzy element zabezpieczeń na podstawie ciągu zakodowanego w formacie XML.

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera bieżące wystąpienie.

(Odziedziczone po Object)
IsValidAttributeName(String)

Określa, czy ciąg jest prawidłową nazwą atrybutu.

IsValidAttributeValue(String)

Określa, czy ciąg jest prawidłową wartością atrybutu.

IsValidTag(String)

Określa, czy ciąg jest prawidłowym tagiem.

IsValidText(String)

Określa, czy ciąg jest prawidłowy jako tekst w elemecie XML.

MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
SearchForChildByTag(String)

Znajduje element podrzędny według jego nazwy tagu.

SearchForTextOfTag(String)

Znajduje element podrzędny według jego nazwy tagu i zwraca zawarty tekst.

ToString()

Tworzy reprezentację ciągu elementu XML i jego atrybutów składowych, elementów podrzędnych i tekstu.

Dotyczy

Produkt Wersje
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1