# Friday, May 29, 2009

Getting errors nicely via email from your website the c# version

For the vb.net version - go here -> http://www.myfriedmind.com/techBlog/2009/05/29/GettingErrorsNicelyViaEmailFromYourWebsiteTheVbnetVersion.aspx

It is always nice to get notified that there is an error on your website in some other way than a user on the other end of the phone.

One of the nicest ways I know of in .net is to use the Application_Error portion of Global.asax to shoot me an email listing the information that is needed. I have included some basic code below but you can feel free to modify it as you choose. For example you may prefer to include the System.Net.Mail info on the SmtpServer in the web.config so you can use it on other portions of the site rather than repeat it.

In the code I use reflection to roll through both the Request object and the Exception that is passed. You can modify it if you want to display more (such as innerexceptions, etc) or to exclude, but Reflection can be nice in pulling up all the data quickly.

=================
In c#

In Web.Config
        <customErrors mode="On" defaultRedirect="~/ErrorOnWebsite.aspx"/>

In Global.asax (don't do this and you get an endless loop!)
    void Application_Error(object sender, EventArgs e)
    {
        Server.Transfer("~/ErrorOnWebsite.aspx");
    }

On ErrorOnWebsite.aspx (you don't actually have to use a label, you can provide some other means of apology)
        <asp:Label runat="server" ID="lblApology"></asp:Label>

This is Error.OnWebsite.aspx.cs (I like code-behinds) - note the use of the HtmlTextWriter and Reflection!

using System;
using System.IO;
using System.Net.Mail;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ErrorOnWebsite : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Exception exc = Server.GetLastError();

        if (exc != null)
        {
            SendNotificationEmail(exc);
            WriteApology();
            Server.ClearError();
        }
        else
        {
            // if there is no error, why are they here?
            Response.Redirect("~/", true);
        }
    }

    private void WriteApology()
    {
        lblApology.Text = "Oops, sorry, the master of light and sound has been notified...";
    }

    private void SendNotificationEmail(Exception exc)
    {
        // Create the format holder for the data, I like tables...
        Table _infoTable = new Table();
        _infoTable.Attributes.Add("border", "1");
        _infoTable.Attributes.Add("cellpadding", "3");

        TableRow _infoRow;
        TableCell _infoNameCell;
        TableCell _infoDataCell;

        _infoRow = new TableRow();
        _infoNameCell = new TableCell();
        _infoNameCell.Text = "Server Request Properties";
        _infoNameCell.BackColor = System.Drawing.Color.Gray;
        _infoNameCell.ColumnSpan = 2;
        _infoRow.Cells.Add(_infoNameCell);
        _infoTable.Rows.Add(_infoRow);

        // I like to use reflection because I hate to type...
        Type _requestType = Request.GetType();
        foreach (PropertyInfo _pInfo in _requestType.GetProperties())
        {
            if (_pInfo.Name != "Item")
            {
                _infoRow = new TableRow();

                _infoNameCell = new TableCell();
                _infoNameCell.Text = _pInfo.Name;
                _infoRow.Cells.Add(_infoNameCell);

                _infoDataCell = new TableCell();
                object _value = _pInfo.GetValue(Request, null);
                if (_value != null)
                {
                    _infoDataCell.Text = Server.HtmlEncode(_value.ToString());
                }
                else
                {
                    _infoDataCell.Text = "";
                }
                _infoRow.Cells.Add(_infoDataCell);

                _infoTable.Rows.Add(_infoRow);
            }
        }

        _infoRow = new TableRow();
        _infoNameCell = new TableCell();
        _infoNameCell.Text = "Exception Properties";
        _infoNameCell.BackColor = System.Drawing.Color.Gray;
        _infoNameCell.ColumnSpan = 2;
        _infoRow.Cells.Add(_infoNameCell);
        _infoTable.Rows.Add(_infoRow);

        Type _exceptionType = exc.GetType();
        foreach (PropertyInfo _pInfo in _exceptionType.GetProperties())
        {
            _infoRow = new TableRow();

            _infoNameCell = new TableCell();
            _infoNameCell.Text = _pInfo.Name;
            _infoRow.Cells.Add(_infoNameCell);

            _infoDataCell = new TableCell();
            object _value = _pInfo.GetValue(exc, null);
            if (_value != null)
            {
                _infoDataCell.Text = Server.HtmlEncode(_value.ToString());
            }
            else
            {
                _infoDataCell.Text = "";
            }
            _infoRow.Cells.Add(_infoDataCell);

            _infoTable.Rows.Add(_infoRow);
        }

        // note the use of the HtmlTextWriter to render the table
        // into a string
        StringWriter _bodyWriter = new StringWriter();
        HtmlTextWriter _writeToBody = new HtmlTextWriter(_bodyWriter);
        _infoTable.RenderControl(_writeToBody);

        MailMessage _message = new MailMessage("error@mysite.com", "myemail@mysite.com");
        _message.Subject = String.Format("Error on website - {0}", exc.Message);
        _message.Body = _bodyWriter.ToString();
        _message.IsBodyHtml = true;

        lblApology.Text = _bodyWriter.ToString();

        SmtpClient _mailClient = new SmtpClient("mymailserver");
        _mailClient.Send(_message);
    }

Comments are closed.