SendMailErrorEventHandler Delegato

Definizione

Rappresenta il metodo che gestisce l'evento SendMailError di controlli quali ChangePassword, CreateUserWizard e PasswordRecovery.

public delegate void SendMailErrorEventHandler(System::Object ^ sender, SendMailErrorEventArgs ^ e);
public delegate void SendMailErrorEventHandler(object sender, SendMailErrorEventArgs e);
type SendMailErrorEventHandler = delegate of obj * SendMailErrorEventArgs -> unit
Public Delegate Sub SendMailErrorEventHandler(sender As Object, e As SendMailErrorEventArgs)

Parametri

sender
Object

Origine dell'evento.

e
SendMailErrorEventArgs

Oggetto SendMailErrorEventArgs contenente i dati dell'evento.

Esempio

Nell'esempio di codice seguente viene illustrata una pagina di ASP.NET che usa un ChangePassword controllo Web e include un gestore eventi per l'evento SendMailError denominato SendMailError. Nell'esempio di codice si presuppone che il sito Web ASP.NET sia stato configurato per l'uso ASP.NET'appartenenza e l'autenticazione basata su form e che sia stato creato un utente il cui nome e la password sono noti all'utente. Per altre informazioni, vedere Procedura: Implementare l'autenticazione basata su moduli semplici.

Se la modifica della password ha esito positivo, il codice tenta di usare SMTP per inviare un messaggio di posta elettronica all'utente per confermare la modifica. Questa operazione viene eseguita nel SendingMail gestore eventi. Per informazioni su come configurare un server SMTP, vedere Procedura: Installare e configurare server virtuali SMTP in IIS 6.0. Ai fini di questo esempio, non è necessario configurare un server SMTP; l'esempio viene costruito per verificare se non è possibile inviare un messaggio di posta elettronica.

Se un server di posta elettronica non è configurato correttamente o si verifica un altro errore e non è possibile inviare il messaggio di posta elettronica, viene chiamata la SendMailError funzione . Viene visualizzato un messaggio all'utente. Inoltre, un evento viene registrato nel registro eventi dell'applicazione Windows presupponendo che esista già un'origine evento denominata MySamplesSite. Vedere l'esempio di codice seguente per creare l'origine evento specificata. Per altre informazioni sulla creazione di un'origine evento, vedere Gestione degli eventi del server in Web Forms ASP.NET Pages. La Handled proprietà dell'oggetto SendMailErrorEventArgs è impostata su true per indicare che l'errore è stato gestito.

<%@ Page Language="C#" AutoEventWireup="True" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void MySendingMail(object sender, MailMessageEventArgs e)
  {
    Message1.Text = "Sent mail to you to confirm the password change.";
  }

  void MySendMailError(object sender, SendMailErrorEventArgs e)
  {
    Message1.Text = "Could not send email to confirm password change.";

    // The MySamplesSite event source has already been created by an administrator.
    System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
    myLog.Log = "Application";
    myLog.Source = "MySamplesSite";
    myLog.WriteEntry(
        "Sending mail via SMTP failed with the following error: " + 
        e.Exception.Message.ToString(), 
        System.Diagnostics.EventLogEntryType.Error);

    e.Handled = true;
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>ChangePassword including a SendMailError Event</title>
</head>
<body>
  <form id="form1" runat="server">
  <div style="text-align:center">

    <h1>ChangePassword</h1>
    
    <asp:LoginView ID="LoginView1" Runat="server" 
      Visible="true">
      <LoggedInTemplate>
        <asp:LoginName ID="LoginName1" Runat="server" FormatString="You are logged in as {0}." />
        <br />
      </LoggedInTemplate>
      <AnonymousTemplate>
        You are not logged in
      </AnonymousTemplate>
    </asp:LoginView><br />
    
    <asp:ChangePassword ID="ChangePassword1" Runat="server"
      BorderStyle="Solid" 
      BorderWidth="1" 
      CancelDestinationPageUrl="~/Default.aspx" 
      DisplayUserName="true"
      OnSendingMail="MySendingMail" 
      OnSendMailError="MySendMailError" 
      ContinueDestinationPageUrl="~/Default.aspx" >
      <MailDefinition 
        BodyFileName="~\MailFiles\ChangePasswordMail.htm" 
        Subject="Activity information for you">
        <EmbeddedObjects>
          <asp:EmbeddedMailObject Name="LoginGif" Path="~\MailFiles\Login.gif" />
          <asp:EmbeddedMailObject Name="PrivacyNoticeTxt" Path="~\MailFiles\PrivacyNotice.txt" />
        </EmbeddedObjects>
      </MailDefinition>
    </asp:ChangePassword><br />
  
    <asp:Label ID="Message1" Runat="server" ForeColor="Red" /><br />

    <asp:HyperLink ID="HyperLink1" Runat="server" 
      NavigateUrl="~/Default.aspx">
      Home
    </asp:HyperLink>
    
  </div>
  </form>
</body>
</html>
<%@ Page Language="VB" AutoEventWireup="True" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  Public Sub MySendingMail(ByVal Sender As Object, ByVal e As MailMessageEventArgs)
    Message1.Text = "Sent mail to you to confirm the password change."
  End Sub

  Public Sub MySendMailError(ByVal Sender As Object, ByVal e As SendMailErrorEventArgs)
    Message1.Text = "Could not send mail to confirm the password change."
    
    ' The MySamplesSite event source has already been created by an administrator.
    Dim myLog As System.Diagnostics.EventLog
    myLog = new System.Diagnostics.EventLog
    myLog.Log = "Application"
    myLog.Source = "MySamplesSite"
    myLog.WriteEntry("Sending mail via SMTP failed with the following error: " & e.Exception.Message.ToString(), System.Diagnostics.EventLogEntryType.Error)

    e.Handled = True
    
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>ChangePassword including a SendMailError Event</title>
</head>
<body>
  <form id="form1" runat="server">
  <div style="text-align:center">

    <h1>ChangePassword</h1>
    
    <asp:LoginView ID="LoginView1" Runat="server" 
      Visible="true">
      <LoggedInTemplate>
        <asp:LoginName ID="LoginName1" Runat="server" FormatString="You are logged in as {0}." />
        <br />
      </LoggedInTemplate>
      <AnonymousTemplate>
        You are not logged in
      </AnonymousTemplate>
    </asp:LoginView><br />
    
    <asp:ChangePassword ID="ChangePassword1" Runat="server"
      BorderStyle="Solid" 
      BorderWidth="1" 
      CancelDestinationPageUrl="~/Default.aspx" 
      DisplayUserName="true"
      OnSendingMail="MySendingMail" 
      OnSendMailError="MySendMailError" 
      ContinueDestinationPageUrl="~/Default.aspx" >
      <MailDefinition 
        BodyFileName="~\MailFiles\ChangePasswordMail.htm" 
        Subject="Activity information for you">
        <EmbeddedObjects>
          <asp:EmbeddedMailObject Name="LoginGif" Path="~\MailFiles\Login.gif" />
          <asp:EmbeddedMailObject Name="PrivacyNoticeTxt" Path="~\MailFiles\PrivacyNotice.txt" />
        </EmbeddedObjects>
      </MailDefinition>
    </asp:ChangePassword><br />
  
    <asp:Label ID="Message1" Runat="server" ForeColor="Red" /><br />

    <asp:HyperLink ID="HyperLink1" Runat="server" 
      NavigateUrl="~/Default.aspx">
      Home
    </asp:HyperLink>
    
  </div>
  </form>
</body>
</html>

Usare l'esempio di codice seguente se è necessario aggiungere a livello di codice l'origine evento denominata MySamplesSite al registro applicazioni. L'origine evento deve esistere affinché il primo esempio di codice funzioni correttamente. L'esempio di codice seguente richiede privilegi di amministratore.

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

#endregion

namespace CreateEventSource
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                // Create the source, if it does not already exist.
                if (!EventLog.SourceExists("MySamplesSite"))
                {
                    EventLog.CreateEventSource("MySamplesSite", "Application");
                    Console.WriteLine("Creating Event Source");
                }

                // Create an EventLog instance and assign its source.
                EventLog myLog = new EventLog();
                myLog.Source = "MySamplesSite";

                // Write an informational entry to the event log.    
                myLog.WriteEntry("Testing writing to event log.");

                Console.WriteLine("Message written to event log.");
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception:");
                Console.WriteLine("{0}", e.ToString());
            }
        }
    }
}
Imports System.Collections.Generic
Imports System.Text
Imports System.Diagnostics


Namespace CreateEventSource
  Class Program
    Sub Main()

        Try
            ' Create the source, if it does not already exist.
            If Not (EventLog.SourceExists("MySamplesSite")) Then
                EventLog.CreateEventSource("MySamplesSite", "Application")
                Console.WriteLine("Creating Event Source")
            End If

            ' Create an EventLog instance and assign its source.
            Dim myLog As New EventLog
            myLog.Source = "MySamplesSite"

            ' Write an informational entry to the event log.
            myLog.WriteEntry("Testing writing to event log.")

            Console.WriteLine("Message written to event log.")
        Catch e As Exception
            Console.WriteLine("Exception:")
            Console.WriteLine(e.ToString)
        End Try

    End Sub
  End Class
End Namespace

Commenti

Quando si crea un delegato SendMailErrorEventHandler, si identifica il metodo che gestirà l'evento. Per associare l'evento al gestore eventi, aggiungere un'istanza del delegato all'evento . Il gestore eventi viene chiamato ogni volta che si verifica l'evento, a meno che non si rimuova il delegato dall'evento. Per altre informazioni sui delegati del gestore eventi, vedere Gestione degli eventi del server in Web Forms ASP.NET Pages.

La gestione dell'evento SendMailError consente all'applicazione Web di continuare l'esecuzione, anche se si verifica un'eccezione quando si tenta di inviare un messaggio di posta elettronica. Ad esempio, ciò è utile se l'eccezione si verifica quando un utente utilizza una procedura guidata in più passaggi. È preferibile registrare l'errore, visualizzare un messaggio informativo all'utente e consentire all'utente di completare la procedura guidata anziché terminare l'applicazione.

Se non si crea un gestore eventi per l'evento o se si crea un gestore eventi ma si lascia la proprietà impostata su false, l'applicazione Handled Web verrà arrestata se si verifica un errore durante l'invio SendMailError di un messaggio di posta elettronica e ASP.NET visualizzerà un messaggio di errore.

Il OnSendMailError metodo consente inoltre alle classi derivate di gestire l'evento anziché .SendMailErrorEventHandler Si tratta della tecnica preferita per la gestione dell'evento in una classe derivata da ChangePassword o CreateUserWizard.

Per altre informazioni sulla gestione degli eventi, vedere Gestione degli eventi del server in Web Forms ASP.NET Pages.

Metodi di estensione

GetMethodInfo(Delegate)

Ottiene un oggetto che rappresenta il metodo rappresentato dal delegato specificato.

Si applica a

Vedi anche