SendMailErrorEventHandler Delegat

Definicja

Reprezentuje metodę, która obsługuje SendMailError zdarzenie kontrolek, takich jak ChangePassword kontrolka, kontrolka CreateUserWizard i kontrolka 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)

Parametry

sender
Object

Źródło zdarzenia.

e
SendMailErrorEventArgs

SendMailErrorEventArgs Obiekt zawierający dane zdarzenia.

Przykłady

Poniższy przykład kodu przedstawia stronę ASP.NET, która używa kontrolki sieci Web i zawiera procedurę ChangePassword obsługi zdarzeń dla SendMailError zdarzenia o nazwie SendMailError. W przykładzie kodu przyjęto założenie, że witryna sieci Web ASP.NET została skonfigurowana do używania ASP.NET członkostwa i uwierzytelniania formularzy oraz że użytkownik został utworzony, którego nazwa i hasło są dla Ciebie znane. Aby uzyskać więcej informacji, zobacz Instrukcje: implementowanie uwierzytelniania prostych formularzy.

Jeśli zmiana hasła powiedzie się, kod próbuje użyć protokołu SMTP, aby wysłać wiadomość e-mail do użytkownika w celu potwierdzenia zmiany. Odbywa się to w procedurze obsługi zdarzeń SendingMail . Aby uzyskać informacje o sposobie konfigurowania serwera SMTP, zobacz How to: Install and Configure SMTP Virtual Servers in IIS 6.0 (Instrukcje: instalowanie i konfigurowanie serwerów wirtualnych SMTP w usługach IIS 6.0). Na potrzeby tego przykładu nie jest konieczne skonfigurowanie serwera SMTP; przykład jest skonstruowany w celu przetestowania błędu wysyłania wiadomości e-mail.

Jeśli serwer poczty nie jest poprawnie skonfigurowany lub wystąpi inny błąd i nie można wysłać wiadomości e-mail, funkcja jest wywoływana SendMailError . Użytkownikowi zostanie wyświetlony komunikat. Ponadto zdarzenie jest rejestrowane w dzienniku zdarzeń aplikacji systemu Windows z założeniem, że źródło zdarzeń o nazwie MySamplesSite już istnieje. Zobacz poniższy przykład kodu, aby utworzyć określone źródło zdarzeń. Aby uzyskać więcej informacji na temat tworzenia źródła zdarzeń, zobacz Obsługa zdarzeń serwera w ASP.NET Web Forms Pages. Właściwość HandledSendMailErrorEventArgs obiektu jest ustawiona na wartość , aby wskazać true , że błąd został obsłużony.

<%@ 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>

Użyj poniższego przykładu kodu, jeśli musisz programowo dodać źródło zdarzeń o nazwie MySamplesSite do dziennika aplikacji. To źródło zdarzeń musi istnieć, aby pierwszy przykład kodu działał poprawnie. Poniższy przykład kodu wymaga uprawnień administratora.

#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

Uwagi

Podczas tworzenia delegata należy zidentyfikować metodę SendMailErrorEventHandler , która będzie obsługiwać zdarzenie. Aby skojarzyć zdarzenie z programem obsługi zdarzeń, dodaj wystąpienie delegata do zdarzenia. Procedura obsługi zdarzeń jest wywoływana za każdym razem, gdy wystąpi zdarzenie, chyba że delegat zostanie usunięty z zdarzenia. Aby uzyskać więcej informacji na temat delegatów programu obsługi zdarzeń, zobacz Obsługa zdarzeń serwera w ASP.NET Web Forms Pages.

Obsługa zdarzenia SendMailError umożliwia aplikacji internetowej kontynuowanie działania, nawet jeśli wystąpi wyjątek podczas próby wysłania wiadomości e-mail. Na przykład jest to przydatne, jeśli wyjątek występuje, gdy użytkownik pracuje za pomocą kreatora wieloetapowego. Zaleca się zarejestrowanie błędu, wyświetlenie komunikatu informacyjnego dla użytkownika i zezwolenie użytkownikowi na ukończenie pracy kreatora, a nie zakończenie działania aplikacji.

Jeśli nie utworzysz procedury obsługi zdarzeń dla SendMailError zdarzenia lub utworzysz program obsługi zdarzeń, ale pozostaw Handled właściwość ustawioną na falsewartość , aplikacja internetowa przestanie działać, jeśli wystąpi błąd podczas wysyłania wiadomości e-mail, a ASP.NET wyświetli komunikat o błędzie.

Metoda OnSendMailError umożliwia również klasom pochodnym obsługę zdarzenia zamiast SendMailErrorEventHandlerklasy . Jest to preferowana technika obsługi zdarzenia w klasie pochodzącej z ChangePassword klasy lub CreateUserWizard.

Aby uzyskać więcej informacji na temat obsługi zdarzeń, zobacz Obsługa zdarzeń serwera w ASP.NET Web Forms Pages.

Metody rozszerzania

GetMethodInfo(Delegate)

Pobiera obiekt reprezentujący metodę reprezentowaną przez określonego delegata.

Dotyczy

Zobacz też