TraceSection Класс

Определение

Настройка службы трассировки ASP.NET. Этот класс не наследуется.

public ref class TraceSection sealed : System::Configuration::ConfigurationSection
public sealed class TraceSection : System.Configuration.ConfigurationSection
type TraceSection = class
    inherit ConfigurationSection
Public NotInheritable Class TraceSection
Inherits ConfigurationSection
Наследование

Примеры

В следующем примере кода показано, как использовать TraceSection тип .

using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Web.Configuration;

namespace Samples.Aspnet.SystemWebConfiguration
{
    // Accesses the System.Web.Configuration.TraceSection members
    // selected by the user.
    class UsingTraceSection
    {
        public static void Main()
        {
            // Process the System.Web.Configuration.TraceSectionobject.
            try
            {
                // Get the Web application configuration.
                System.Configuration.Configuration configuration = 
                    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnet");
                
                // Get the section.
                System.Web.Configuration.TraceSection traceSection = 
                    (System.Web.Configuration.TraceSection) 
                    configuration.GetSection("system.web/trace");

// Get the current PageOutput property value.
Boolean pageOutputValue = traceSection.PageOutput;

// Set the PageOutput property to true.
traceSection.PageOutput = true;

                

// Get the current WriteToDiagnosticsTrace property value.
Boolean writeToDiagnosticsTraceValue = traceSection.WriteToDiagnosticsTrace;

// Set the WriteToDiagnosticsTrace property to true.
traceSection.WriteToDiagnosticsTrace = true;

                

// Get the current MostRecent property value.
Boolean mostRecentValue = traceSection.MostRecent;

// Set the MostRecent property to true.
traceSection.MostRecent = true;

                

// Get the current RequestLimit property value.
Int32 requestLimitValue = traceSection.RequestLimit;

// Set the RequestLimit property to 256.
traceSection.RequestLimit = 256;

                

// Get the current LocalOnly property value.
Boolean localOnlyValue = traceSection.LocalOnly;

// Set the LocalOnly property to false.
traceSection.LocalOnly = false;

                

// Get the current Enabled property value.
Boolean enabledValue = traceSection.Enabled;

// Set the Enabled property to false.
traceSection.Enabled = false;

                

// Get the current Mode property value.
// TraceDisplayMode modeValue = traceSection.TraceMode;

// Set the Mode property to TraceDisplayMode.SortyByTime.
// traceSection.Mode = TraceDisplayMode.SortByTime;

                
                // Update if not locked.
                if (! traceSection.SectionInformation.IsLocked)
                {
                    configuration.Save();
                    Console.WriteLine("** Configuration updated.");
                }
                else
                {
                    Console.WriteLine("** Could not update, section is locked.");
                }
            }
            catch (System.ArgumentException e)
            {
                // Unknown error.
                Console.WriteLine(
                    "A invalid argument exception detected in UsingTraceSection Main. Check your");
                Console.WriteLine("command line for errors.");
            }
        }
    } // UsingTraceSection class end.
} // Samples.Aspnet.SystemWebConfiguration namespace end.
Imports System.Collections
Imports System.Collections.Specialized
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Configuration
Imports System.Web.Configuration

Namespace Samples.Aspnet.SystemWebConfiguration
    ' Accesses the System.Web.Configuration.TraceSection members
    ' selected by the user.
    Class UsingTraceSection
        Public Shared Sub Main()
            ' Process the System.Web.Configuration.TraceSectionobject.
            Try
                ' Get the Web application configuration.
                Dim configuration As System.Configuration.Configuration = _
                    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnet")

                ' Get the section.
                Dim traceSection As System.Web.Configuration.TraceSection = _
                    CType(configuration.GetSection("system.web/trace"), _
                    System.Web.Configuration.TraceSection)

                ' Get the current PageOutput property value.
                Dim pageOutputValue As Boolean = traceSection.PageOutput

                ' Set the PageOutput property to true.
                traceSection.PageOutput = True



                ' Get the current WriteToDiagnosticsTrace property value.
                Dim writeToDiagnosticsTraceValue As Boolean = traceSection.WriteToDiagnosticsTrace

                ' Set the WriteToDiagnosticsTrace property to true.
                traceSection.WriteToDiagnosticsTrace = True



                ' Get the current MostRecent property value.
                Dim mostRecentValue As Boolean = traceSection.MostRecent

                ' Set the MostRecent property to true.
                traceSection.MostRecent = True



                ' Get the current RequestLimit property value.
                Dim requestLimitValue As Int32 = traceSection.RequestLimit

                ' Set the RequestLimit property to 256.
                traceSection.RequestLimit = 256



                ' Get the current LocalOnly property value.
                Dim localOnlyValue As Boolean = traceSection.LocalOnly

                ' Set the LocalOnly property to false.
                traceSection.LocalOnly = False



                ' Get the current Enabled property value.
                Dim enabledValue As Boolean = traceSection.Enabled

                ' Set the Enabled property to false.
                traceSection.Enabled = False



                ' Get the current Mode property value.
                'Dim modeValue As TraceDisplayMode = traceSection.TraceMode

                ' Set the Mode property to TraceDisplayMode.SortByTime.
                'traceSection.Mode = TraceDisplayMode.SortByTime


                ' Update if not locked.
                If Not traceSection.SectionInformation.IsLocked Then
                    configuration.Save()
                    Console.WriteLine("** Configuration updated.")
                Else
                    Console.WriteLine("** Could not update, section is locked.")
                End If
            Catch e As System.ArgumentException
                ' Unknown error.
                Console.WriteLine( _
                    "A invalid argument exception detected in UsingTraceSection Main. Check your")
                Console.WriteLine("command line for errors.")
            End Try
        End Sub
    End Class
    
End Namespace ' Samples.Aspnet.SystemWebConfiguration

Комментарии

Класс TraceSection предоставляет способ программного доступа и изменения содержимого раздела файла trace конфигурации. В trace этом разделе настраиваются функции ASP.NET трассировки и управляется сбор, хранение и отображение результатов трассировки.

Если трассировка включена, каждый запрос страницы создает сообщения трассировки, которые можно добавить в выходные данные страницы или сохранить в журнале трассировки приложения. Для просмотра содержимого журнала трассировки можно использовать средство просмотра ASP.NET (Trace.axd).

Конструкторы

TraceSection()

Инициализирует новый экземпляр класса TraceSection значениями по умолчанию.

Свойства

CurrentConfiguration

Возвращает ссылку на экземпляр Configuration верхнего уровня, представляющий иерархию конфигурации, к которой относится текущий экземпляр ConfigurationElement.

(Унаследовано от ConfigurationElement)
ElementInformation

Возвращает объект ElementInformation, содержащий неизменяемую информацию и функциональность объекта ConfigurationElement.

(Унаследовано от ConfigurationElement)
ElementProperty

Возвращает объект ConfigurationElementProperty, представляющий сам объект ConfigurationElement.

(Унаследовано от ConfigurationElement)
Enabled

Возвращает или задает значение, указывающее на то, включена ли служба трассировки ASP.NET.

EvaluationContext

Возвращает объект ContextInformation для объекта ConfigurationElement.

(Унаследовано от ConfigurationElement)
HasContext

Возвращает значение, указывающее, имеет ли свойство CurrentConfiguration значение null.

(Унаследовано от ConfigurationElement)
Item[ConfigurationProperty]

Возвращает или задает свойство или атрибут данного элемента конфигурации.

(Унаследовано от ConfigurationElement)
Item[String]

Получает или задает свойство, атрибут или дочерний элемент данного элемента конфигурации.

(Унаследовано от ConfigurationElement)
LocalOnly

Возвращает или задает значение, указывающее, доступна ли программа просмотра трассировки ASP.NET (Trace.axd) только для запросов из хоста веб-сервера.

LockAllAttributesExcept

Возвращает коллекцию заблокированных атрибутов.

(Унаследовано от ConfigurationElement)
LockAllElementsExcept

Возвращает коллекцию заблокированных элементов.

(Унаследовано от ConfigurationElement)
LockAttributes

Возвращает коллекцию заблокированных атрибутов.

(Унаследовано от ConfigurationElement)
LockElements

Возвращает коллекцию заблокированных элементов.

(Унаследовано от ConfigurationElement)
LockItem

Возвращает или задает значение, указывающее, заблокирован ли элемент.

(Унаследовано от ConfigurationElement)
MostRecent

Возвращает или задает значение, указывающее на то, всегда ли последние запросы хранятся на сервере.

PageOutput

Возвращает или задает значение, указывающее на то, добавлены ли сведения о трассировке ASP.NET к выводу каждой страницы.

Properties

Возвращает коллекцию свойств.

(Унаследовано от ConfigurationElement)
RequestLimit

Возвращает или задает значение, указывающее на максимальное количество запросов приложению, для которых ASP.NET хранит сведения о трассировке.

SectionInformation

Возвращает объект SectionInformation, содержащий неизменяемую информацию и функциональность объекта ConfigurationSection.

(Унаследовано от ConfigurationSection)
TraceMode

Возвращает или задает порядок, в котором отображаются сведения о трассировке ASP.NET.

WriteToDiagnosticsTrace

Возвращает или задает значение, указывающее на то, направляются ли созданные посредством трассировки страницы сообщения экземпляру класса Trace.

Методы

DeserializeElement(XmlReader, Boolean)

Считывает XML из файла конфигурации.

(Унаследовано от ConfigurationElement)
DeserializeSection(XmlReader)

Считывает XML из файла конфигурации.

(Унаследовано от ConfigurationSection)
Equals(Object)

Сравнивает текущий экземпляр ConfigurationElement с указанным объектом.

(Унаследовано от ConfigurationElement)
GetHashCode()

Получает уникальное значение, представляющее текущий экземпляр ConfigurationElement.

(Унаследовано от ConfigurationElement)
GetRuntimeObject()

Возвращает пользовательский объект при переопределении в производном классе.

(Унаследовано от ConfigurationSection)
GetTransformedAssemblyString(String)

Возвращает преобразованную версию указанного имени сборки.

(Унаследовано от ConfigurationElement)
GetTransformedTypeString(String)

Возвращает преобразованную версию указанного имени типа.

(Унаследовано от ConfigurationElement)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
Init()

Задает объект ConfigurationElement в исходное состояние.

(Унаследовано от ConfigurationElement)
InitializeDefault()

Используется для инициализации набора значений по умолчанию для объекта ConfigurationElement.

(Унаследовано от ConfigurationElement)
IsModified()

При реализации в производном классе указывает, был ли изменен данный элемент конфигурации с момента последнего сохранения или загрузки.

(Унаследовано от ConfigurationSection)
IsReadOnly()

Получает значение, показывающее, является ли объект ConfigurationElement доступным только для чтения.

(Унаследовано от ConfigurationElement)
ListErrors(IList)

Добавляет ошибку "недействительное свойство" в данном объекте ConfigurationElement и всех его дочерних элементах к переданному списку.

(Унаследовано от ConfigurationElement)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
OnDeserializeUnrecognizedAttribute(String, String)

Возвращает значение, указывающее, встретился ли неизвестный атрибут при десериализации.

(Унаследовано от ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Возвращает значение, указывающее, встретился ли неизвестный элемент при десериализации.

(Унаследовано от ConfigurationElement)
OnRequiredPropertyNotFound(String)

Выдает исключение, если требуемое свойство не найдено.

(Унаследовано от ConfigurationElement)
PostDeserialize()

Вызывается после десериализации.

(Унаследовано от ConfigurationElement)
PreSerialize(XmlWriter)

Вызывается до сериализации.

(Унаследовано от ConfigurationElement)
Reset(ConfigurationElement)

Восстанавливает внутреннее состояние объекта ConfigurationElement, включая блокировки и коллекции свойств.

(Унаследовано от ConfigurationElement)
ResetModified()

Переустанавливает значение метода IsModified() в false при реализации в производном классе.

(Унаследовано от ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Записывает содержание данного элемента конфигурации в файл конфигурации при реализации в производном классе.

(Унаследовано от ConfigurationElement)
SerializeSection(ConfigurationElement, String, ConfigurationSaveMode)

Создает XML-строку, содержащую разъединенное представление об объекте ConfigurationSection, как об отдельном разделе, записываемым в файл.

(Унаследовано от ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Записывает внешние теги данного элемента конфигурации в файл конфигурации при реализации в производном классе.

(Унаследовано от ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Задает для свойства указанное значение.

(Унаследовано от ConfigurationElement)
SetReadOnly()

Задает свойство IsReadOnly() для объекта ConfigurationElement и всех подчиненных элементов.

(Унаследовано от ConfigurationElement)
ShouldSerializeElementInTargetVersion(ConfigurationElement, String, FrameworkName)

Указывает, следует ли сериализовать указанный элемент при сериализации иерархии объектов конфигурации для указанной целевой версии платформа .NET Framework.

(Унаследовано от ConfigurationSection)
ShouldSerializePropertyInTargetVersion(ConfigurationProperty, String, FrameworkName, ConfigurationElement)

Указывает, следует ли сериализовать указанное свойство при сериализации иерархии объектов конфигурации для указанной целевой версии платформа .NET Framework.

(Унаследовано от ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Указывает, следует ли сериализовать текущий ConfigurationSection экземпляр при сериализации иерархии объектов конфигурации для указанной целевой версии платформа .NET Framework.

(Унаследовано от ConfigurationSection)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Изменяет объект ConfigurationElement для удаления всех значений, которые не должны сохраняться.

(Унаследовано от ConfigurationElement)

Применяется к

См. также раздел