by Chris
Sunday, July 19 2009
I noticed we were getting a few keyword hits on error/exception report generation and sending error reports via email, so I have decided that today's entry will be just that. Below, you will find the code necessary for generating an email containing an error (exception) report using global.asax.
Firstly, enter this code in to the appropriate area, within global.asax file:
NOTE: Sorry about the poor formating.
void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError().GetBaseException();
System.Text.StringBuilder sbMessage = new System.Text.StringBuilder();
sbMessage.Append("<dl style=\"font-face: Arial; font-weight: normal; font-size: 13px; line-height: 16px;\">");
sbMessage.Append("<dt style=\"font-weight: bold;\">Source:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", exception.Source);
sbMessage.Append("<dt style=\"font-weight: bold;\">Date and Time:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", DateTime.Now.ToString("MM/dd/yyyy h:mm tt"));
sbMessage.Append("<dt style=\"font-weight: bold;\">Message:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", exception.Message);
sbMessage.Append("<dt style=\"font-weight: bold;\">Stack Trace:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", exception.StackTrace);
sbMessage.Append("</dl>");
using (System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage())
{
mailMessage.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["emailWebsite"].ToString());
mailMessage.To.Add(new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["emailInformation"].ToString()));
mailMessage.Subject = "[ERROR] Unhandled Exception from the Website";
mailMessage.Body = sbMessage.ToString();
mailMessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.Host = ConfigurationManager.AppSettings["mailServerOutgoing"].ToString());
smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["emailWebsite"].ToString(), ConfigurationManager.AppSettings["emailWebsitePassword"].ToString());
smtpClient.Send(mailMessage);
}
}
Once this is completed, and modified to specification, we must add the following definitions to the web.config (in the appSettings element):
<appsettings>
<add key="mailServerOutgoing" value="mail.your-server-address.com">
<add key="emailWebsite" value="mailer@your-server-address.com">
<add key="emailWebsitePassword" value="your-mailer-password">
<add key="emailInformation" value="receiving@your-server-address.com">
</appsettings>
This allows us to keep important information, such as email accounts and passwords, separate from the codebehind file, and is thus moderately more secure.
And that is all there is to it! All we ask is that if you use our code, just take a few moments and digg this entry.
by Chris
Sunday, July 19 2009
Here is nice little piece of code for issuing an internal domain redirect. Simply insert the code into the global.asax file, which should be found in the root web (www) directory. A commented line explanation is included within. ...and please excuse the improper code structuring.
In this case, we are setting up a redirect from abwebsitedesign.com to www.abwebsitedesign.com in order to ensure proper indexing by search engines.
void Application_BeginRequest(object sender, EventArgs e)
{
//if the requested domain contains this
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://abwebsitedesign.com"))
{
//then return this header response
HttpContext.Current.Response.Status = "301 Moved Permanently";
//and then replace the requested address with the newly defined address
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://abwebsitedesign.com", "http://www.abwebsitedesign.com"));
}
This also works nicely for telling search engines where a new page can be found (in case you change files, paths, or page names).
void Application_BeginRequest(object sender, EventArgs e)
{
//if the requested address contains this
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://www.abwebsitedesign.com/oldpage.aspx"))
{
//then return this header response
HttpContext.Current.Response.Status = "301 Moved Permanently";
//and then replace the requested address with the newly defined address
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://www.abwebsitedesign.com/oldpage.aspx", "http://www.abwebsitedesign.com/newpage.aspx"));
}
Pretty simple, yet very necessary for properly, and effectively maintaining SEO.
by Chris
Sunday, July 19 2009
There are several methods being used to provide users with helpful 404 error pages, but just because it looks helpful to the user, doesn't mean that it is benefiting your SEO. It is essential, for the prosperity of your website, to be certain that proper server header responses are being sent.
We have taken a somewhat different approach to implementing error handling. We have included a "switch" statement in order to provide multiple errors and server header responses through one page.
Here is a sample from our "errorhandler" codebehind file:
protected override void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["m"] != null)
{
switch (Request.QueryString["m"].ToString())
{
case "404":
Response.Status = "404 Not Found";
this.Page.Title = "404 Error: File Not Found | AB Web Design";
mvError.SetActiveView(viewNotFound);
break;
case "500":
Response.Status = "500 Internal Server Error";
this.Page.Title = "500 Error: Internal Server Error | AB Web Design";
mvError.SetActiveView(viewInternalError);
break;
default:
Response.Status = "404 Not Found";
this.Page.Title = "404 Error: File Not Found | AB Web Design";
mvError.SetActiveView(viewNotFound);
break;
}
}
else
{
Response.Status = "404 Not Found";
this.Page.Title = "404 Error: File Not Found | AB Web Design";
mvError.SetActiveView(viewNotFound);
}
}
In the .aspx file:
<asp:Literal ID="ltrError" runat="server" />
<asp:MultiView ID="mvError" runat="server">
<asp:View ID="viewNotFound" runat="server">
<br />
<h1>404 Error: File Not Found</h1>
<br />
<p>We're sorry, that page was not found on this server.</p>
</asp:View>
<asp:View ID="viewInternalError" runat="server">
<br />
<h1>500 Error: Internal Server Error</h1>
<br />
<p>We're sorry, our site has experienced an error. The site administrators have been informed.</p>
</asp:View>
</asp:MultiView>
We have removed some of the other server header responses such as 401, 400, etc..., but as you can see, it is a simple way of covering all of your errors in one page. Plus, it will return the proper response, and prevent unwanted indexing by search engines.
We also tied in an error (exception) reporting feature using global.asax, which we will cover in an upcoming blog entry. It basically generates and sends us a detailed report email every time an error message is displayed to a user.
I hope you found this useful! If you like it, digg it!