Here I am going to write a extension method which will send errors in email. From asp.net 3.5 or higher version of .NET framework its provides a unique way to extend your classes. Here you can fine more information about extension method. So lets create extension method via implementing a static class like following. I am going to use same code for sending email via my Gmail account from here. Following is code for that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
namespace Experiement
{
public static class MyExtension
{
public static void SendErrorEmail(this Exception ex)
{
MailMessage mailMessage = new MailMessage(new MailAddress("from@gmail.com")
, new MailAddress("to@gmail.com"));
mailMessage.Subject = "Exception Occured in your site";
mailMessage.IsBodyHtml = true;
System.Text.StringBuilder errorMessage = new System.Text.StringBuilder();
errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}","Exception",ex.Message));
errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}", "Stack Trace", ex.StackTrace));
if (ex.InnerException != null)
{
errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}", " Inner Exception", ex.InnerException.Message));
errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}", "Inner Stack Trace", ex.InnerException.StackTrace));
}
mailMessage.Body = errorMessage.ToString();
System.Net.NetworkCredential networkCredentials = new
System.Net.NetworkCredential("youraccount@gmail.com", "password");
SmtpClient smtpClient = new SmtpClient();
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = networkCredentials;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Send(mailMessage);
}
}
}
using System;
namespace Experiement
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender,System.EventArgs e)
{
try
{
throw new Exception("My custom Exception");
}
catch (Exception ex)
{
ex.SendErrorEmail();
Response.Write(ex.Message);
}
}
}
}
No comments:
Post a Comment