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ли |
| 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() метода |
| 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) |