WebEventProvider Clase

Definición

Proporciona la clase base para los proveedores de eventos no almacenados en búfer.Provides the base class for non buffered event providers.

public ref class WebEventProvider abstract : System::Configuration::Provider::ProviderBase
public abstract class WebEventProvider : System.Configuration.Provider.ProviderBase
type WebEventProvider = class
    inherit ProviderBase
Public MustInherit Class WebEventProvider
Inherits ProviderBase
Herencia
WebEventProvider
Derivado

Ejemplos

En el ejemplo de código siguiente se muestra cómo derivar de la WebEventProvider clase para crear un proveedor personalizado que escribe los eventos configurados en un archivo local para el que se deben conceder los derechos de acceso adecuados.The following code example shows how to derive from the WebEventProvider class to create a custom provider that writes the configured events to a local file for which appropriate access rights must be granted. Este ejemplo de proveedor personalizado es sencillo y su intención principal es proporcionarle como desarrollador control total de sus mecanismos básicos.This custom provider example is simple and its main intent is to give you as developer full control of its basic mechanisms. En un escenario real, podría usar este proveedor y especialmente el proveedor almacenado en búfer de ejemplo disponible en BufferedWebEventProvider , como un sondeo preliminar en el comportamiento de una aplicación.In a real-world scenario, you could use this provider and especially the example buffered provider available at BufferedWebEventProvider, as a preliminary probe into the behavior of an application. Esto puede ayudarle durante la fase de diseño para comprender la información disponible. Posteriormente, puede dirigir esta información a un proveedor más complejo.This can help you during the design stage to gain an understanding of the information available; then later you can direct this information to a more complex provider.

El extracto de archivo de configuración siguiente muestra una healthMonitoring configuración de sección que permite a ASP.net usar el proveedor personalizado definido anteriormente para procesar todos los eventos de supervisión de estado.The following configuration file excerpt shows a healthMonitoring section configuration that enables ASP.NET to use the custom provider defined above to process all health-monitoring events.

<healthMonitoring   
  heartBeatInterval="0"   
  enabled="true">  

    <providers>  

      <add name="SampleWebEventProvider"   
        type="SamplesAspNet.SampleEventProvider,webeventprovider, Version=1.0.1773.33989, Culture=neutral, PublicKeyToken=cf85aa6c978d9dea, processorArchitecture=MSIL" />  

    </providers>  

    <rules>  

      <rule   
        name="Custom Event Provider"  
        eventName="All Events"  
        provider="SampleWebEventProvider"  
        profile="Default" />  
    </rules>  

</healthMonitoring>  

using System;
using System.Text;
using System.IO;
using System.Web.Management;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;

namespace SamplesAspNet
{
  // Implements a custom event provider.
    public class SampleEventProvider : 
        System.Web.Management.WebEventProvider
    {

        // The local path of the file where
        // to store event information.
        private string logFilePath;
    
        // The current number of buffered messages 
        private int msgCounter;

        // The max number of messages to buffere.
        private int maxMsgNumber;

        // The message buffer.
        private System.Collections.Generic.Queue
            <WebBaseEvent> msgBuffer = 
            new Queue<WebBaseEvent>();

        // Initializes the provider.
        public SampleEventProvider(): base()
        {

            // Initialize the local path of the file 
            // that holds event information.
            logFilePath = "C:/test/log.doc";

            // Clear the message buffer.
            msgBuffer.Clear();

            // Initialize the max number of messages
            // to buffer.
            maxMsgNumber = 10;

            // More custom initialization goes here.
        }

        // Flush the input buffer if required.
        public override void Flush()
        {
            // Create a string builder to 
            // hold the event information.
            StringBuilder reData = new StringBuilder();

            // Store custom information.
            reData.Append("SampleEventProvider processing." +
                Environment.NewLine);
            reData.Append("Flush done at: {0}" +
                DateTime.Now.TimeOfDay.ToString() +
                Environment.NewLine);
            
            foreach (WebBaseEvent e in msgBuffer)
            {
                // Store event data.
                reData.Append(e.ToString());
            }

            // Store the information in the specified file.
            StoreToFile(reData, logFilePath, FileMode.Append);

            // Reset the message counter.
            msgCounter = 0;
            
            // Clear the buffer.
            msgBuffer.Clear();
        }


        // Shutdown the provider.
        public override void Shutdown()
        {
            Flush();
        }


        // Process the event that has been raised.
        public override void ProcessEvent(WebBaseEvent raisedEvent)
        { 
            if (msgCounter < maxMsgNumber)
            {
                // Buffer the event information.
                msgBuffer.Enqueue(raisedEvent);
                // Increment the message counter.
                msgCounter += 1;
            }
            else
            {
                // Flush the buffer.
                Flush();
            }
        }



        // Store event information in a local file.
        private void StoreToFile(StringBuilder text, 
            string filePath, FileMode mode)
        {
            int writeBlock;
            int startIndex;

            try
            {

                writeBlock = 256;
                startIndex = 0;

                // Open or create the local file 
                // to store the event information.
                FileStream fs = new FileStream(filePath, 
                    mode, FileAccess.Write);

                // Lock the file for writing.
                fs.Lock(startIndex, writeBlock);

                // Create a stream writer
                StreamWriter writer = new StreamWriter(fs);

                // Set the file pointer to the current 
                // position to keep adding data to it. 
                // If you want to rewrite the file use 
                // the following statement instead.
                // writer.BaseStream.Seek (0, SeekOrigin.Begin);
                writer.BaseStream.Seek(0, SeekOrigin.Current);

                //If the file already exists it must not 
                // be write protected otherwise  
                // the following write operation fails silently.
                writer.Write(text.ToString());

                // Update the underlying file
                writer.Flush();

                // Unlock the file for other processes.
                fs.Unlock(startIndex, writeBlock);

                // Close the stream writer and the underlying file     
                writer.Close();

                fs.Close();
            }
            catch (Exception e)
            {
                throw new Exception(
                    "SampleEventProvider.StoreToFile: " 
                    + e.ToString());
            }
        }
    }
}

Imports System.Text
Imports System.IO
Imports System.Web.Management
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.Web



' Implements a custom event provider.

Public Class SampleEventProvider
    Inherits System.Web.Management.WebEventProvider
    
    ' The local path of the file where
    ' to store event information.
    Private logFilePath As String
    
    ' The current number of buffered messages 
    Private msgCounter As Integer
    
    ' The max number of messages to buffere.
    Private maxMsgNumber As Integer
    
    ' The message buffer.
    '  private System.Collections.Generic.Queue
    Private msgBuffer _
    As System.Collections.Generic.Queue( _
    Of System.Web.Management.WebBaseEvent) = _
    New System.Collections.Generic.Queue( _
    Of System.Web.Management.WebBaseEvent)


    ' Initializes the provider.
    Public Sub New() 
        
        ' Initialize the local path of the file 
        ' that holds event information.
        logFilePath = "C:/test/log.doc"
        
        ' Clear the message buffer.
        msgBuffer.Clear()
        
        ' Initialize the max number of messages
        ' to buffer.
        maxMsgNumber = 10
    
    End Sub
     
    ' More custom initialization goes here.
    
    ' Flush the input buffer if required.
    Public Overrides Sub Flush() 
        ' Create a string builder to 
        ' hold the event information.
        Dim reData As New StringBuilder()
        
        ' Store custom information.
        reData.Append( _
        "SampleEventProvider processing." + _
        Environment.NewLine)

        reData.Append( _
        "Flush done at: {0}" + _
        DateTime.Now.TimeOfDay.ToString() + _
        Environment.NewLine)
        
        Dim e As WebBaseEvent
        For Each e In  msgBuffer
            ' Store event data.
            reData.Append(e.ToString())
        Next e
        
        ' Store the information in the specified file.
        StoreToFile(reData, logFilePath, FileMode.Append)
        
        ' Reset the message counter.
        msgCounter = 0
        
        ' Clear the buffer.
        msgBuffer.Clear()
    
    End Sub
     
    ' Shutdown the provider.
    Public Overrides Sub Shutdown() 
        Flush()
    
    End Sub
    
    ' Process the event that has been raised.
    Public Overrides Sub ProcessEvent( _
    ByVal raisedEvent As WebBaseEvent)

        If msgCounter < maxMsgNumber Then
            ' Buffer the event information.
            msgBuffer.Enqueue(raisedEvent)
            ' Increment the message counter.
            msgCounter += 1
        Else
            ' Flush the buffer.
            Flush()
        End If

    End Sub
    
    
    ' Store event information in a local file.
    Private Sub StoreToFile( _
    ByVal [text] As StringBuilder, _
    ByVal filePath As String, _
    ByVal mode As FileMode)
        Dim writeBlock As Integer
        Dim startIndex As Integer

        Try

            writeBlock = 256
            startIndex = 0

            ' Open or create the local file 
            ' to store the event information.
            Dim fs As New FileStream( _
            filePath, mode, FileAccess.Write)

            ' Lock the file for writing.
            fs.Lock(startIndex, writeBlock)

            ' Create a stream writer
            Dim writer As New StreamWriter(fs)

            ' Set the file pointer to the current 
            ' position to keep adding data to it. 
            ' If you want to rewrite the file use 
            ' the(following) statement instead.
            ' writer.BaseStream.Seek (0, SeekOrigin.Begin);
            writer.BaseStream.Seek(0, SeekOrigin.Current)

            'If the file already exists it must 
            'not be write protected, otherwise  
            'the following write operation fails silently.
            writer.Write([text].ToString())

            ' Update the underlying file
            writer.Flush()

            ' Unlock the file for other processes.
            fs.Unlock(startIndex, writeBlock)

            ' Close the stream writer and the underlying file     
            writer.Close()

            fs.Close()
        Catch e As Exception
            Throw New Exception( _
            "SampleEventProvider.StoreToFile: " + _
            e.ToString())
        End Try

    End Sub
End Class


Comentarios

La supervisión de estado de ASP.NET permite al personal de producción y de operaciones administrar aplicaciones web implementadas.ASP.NET health monitoring allows production and operations staff to manage deployed Web applications. El System.Web.Management espacio de nombres contiene los tipos de evento de mantenimiento responsables de empaquetar los datos de estado de la aplicación y los tipos de proveedor responsables del procesamiento de estos datos.The System.Web.Management namespace contains the health event types responsible for packaging application health-status data and the provider types responsible for processing this data. También contiene tipos auxiliares que ayudan durante la administración de eventos de mantenimiento.It also contains supporting types that help during the management of health events.

Si desea personalizar el procesamiento de eventos de estado, puede derivar de la WebEventProvider clase para crear su propio proveedor personalizado.If you want to customize the health-event processing, you can derive from the WebEventProvider class to create your own custom provider.

Nota

En la mayoría de los casos, podrá usar los tipos de supervisión de estado de ASP.NET tal y como se implementan, y podrá controlar el sistema de supervisión de estado especificando los valores en la healthMonitoring sección de configuración.In most cases you will be able to use the ASP.NET health-monitoring types as implemented, and you will control the health-monitoring system by specifying values in the healthMonitoring configuration section. También puede derivar de los tipos de supervisión de estado para crear sus propios eventos y proveedores personalizados.You can also derive from the health-monitoring types to create your own custom events and providers. Para obtener un ejemplo de cómo derivar de la WebEventProvider clase, vea el ejemplo que se proporciona en este tema.For an example of deriving from the WebEventProvider class, see the example provided in this topic.

Constructores

WebEventProvider()

Inicializa una nueva instancia de la clase WebEventProvider.Initializes a new instance of the WebEventProvider class.

Propiedades

Description

Obtiene una descripción breve y fácil de comprender apropiada para mostrarla en las herramientas administrativas u otras interfaces de usuario.Gets a brief, friendly description suitable for display in administrative tools or other user interfaces (UIs).

(Heredado de ProviderBase)
Name

Obtiene el nombre descriptivo utilizado para hacer referencia al proveedor durante la configuración.Gets the friendly name used to refer to the provider during configuration.

(Heredado de ProviderBase)

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.Determines whether the specified object is equal to the current object.

(Heredado de Object)
Flush()

Pasa los eventos del búfer del proveedor al registro de eventos.Moves the events from the provider's buffer into the event log.

GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
Initialize(String, NameValueCollection)

Inicializa el generador de configuración.Initializes the configuration builder.

(Heredado de ProviderBase)
MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
ProcessEvent(WebBaseEvent)

Procesa el evento pasado al proveedor.Processes the event passed to the provider.

Shutdown()

Realiza tareas asociadas al cierre del proveedor.Performs tasks associated with shutting down the provider.

ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)

Se aplica a

Consulte también