a web design blog.

Friday, September 5, 2008

Sending Error/Exception Reports via Email in ASP.net and C# (C-sharp)

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 (Blogger doesn't seem to handle code very well).


void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();

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 using the addThis panel below. Thank you.

...

Thursday, September 4, 2008

Google Chrome: A few thoughts, and maybe a rant or two

I have read many blog posts and news entries on the topic of Google's new web browser, Chrome, and much to my surprise -- the majority of them were quite negative. Google, the company that has brought so much innovation and so many extremely useful products to the world, is now being shunned for it's attempt to offer a FREE alternative to the clutches of Microsoft and its web browser, Internet Explorer.

Now, don't get me wrong, I do not detest Microsoft at all. However, in recent years IE has not really been what I would consider, a "Top Performer." IE is characteristically slower than most browsers, largely cumbersome, and plagued with frequent crashes which leave users with no way to resume their previous musings.

I must also note that I am a big fan of Mozilla's newest version of Firefox (version 3), Opera's latest release (version 9.5), and even Apple's Safari (version 3.1). I have installed all of them because they each offer something a little different. Heck, I have even installed IE8 (beta 2), though I'm not impressed with it, thus far.

It is true that Internet Explorer continues to dominate browser usage, with IE 6 and 7 combined topping the 50% mark, but with Firefox coming in second at a little over 43% (source: w3schools.com)

A side note: Many people have screamed MONOPOLY since IE was included as the default browser in the Windows operating system, but I can certainly guarantee that any other company would do the same thing. Furthermore, there is absolutely nothing wrong with a company trying to offer a complete solution to the end-user.

Now where was I, ah yes...
So why has Firefox been able to gain so much ground in this "Browser Battle?" Simple. By offering better features, faster loading, quicker HTML and Javascript rendering, etc, etc. Likewise, if Google Chrome offers advantages over other browsers, why not use it? If Chrome has a quicker Javascript engine, has better support for the latest web technologies, prevents total loss of progress during crashes, and is stable to the point where crashes are unlikely to occur anyway, what's the downside?

Well, some critics seem to think that Google (with it's eyes set on global domination) has already crossed over to the "dark side," and is secretly tracking EVERYONE; reading their emails, and logging all of their movements. Though that may be true to a fraction of a degree (but strictly for personalized advertising), this new browser is a good thing.

From a web design and developer's perspective: As tedious as it may be to test sites with yet another browser in order ensure cross-browser compatibility, it seems like a small price to pay for better web standards. Plus, a move like this will certainly push competing web browser developers to adopt better standards.

Any new browsers that promote strict standards, increase efficiencies, and force competition to adopt better practices...has my vote! It is also certainly worth mentioning that Chrome is also 100% open-source, which will undoubtedly promote new feature developments.

So, my initial inspection of Google Chrome yields very positive results: quick, clean, and intuitive is a great way to go. Now, let us see what becomes of it.

Labels: , ,

Wednesday, September 3, 2008

Internal Domain Redirects with ASP.net and C# (C-sharp)

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.

...

Custom Error Handling in ASP.net C# (C-Sharp)

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!



Tuesday, September 2, 2008

Mobile Web Browser Detection and Redirection in C# for ASP.net (server-side)

Adding server-side browser detection and redirection to your website using the ASP.net platform and C# (C-Sharp) is actually quite easy. Below, you will see the code which we have implemented on our site. Though it may not catch ALL browsers (because there are a heck of a lot of them), it will catch most.

This code should be inserted into the Page_Load event of the codebehind file (e.g., samplepage.aspx.cs). To enable this site-wide, just add it to the Page_Load event of the Master Page file.

if (Request.Headers["User-Agent"] != null && (Request.Browser["IsMobileDevice"] == "true" || Request.Browser["BlackBerry"] == "true" || Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC")) || Request.UserAgent.ToLower().Contains("iphone"))
{
Response.Redirect("http://mobile.abwebsitedesign.com");
}

The preceding code will allow you to add as many User Agents as you wish by just adding additional Request.UserAgent properties. The else statement is not necessary in this case, because we want the page to load normally, unless the UserAgent is not a standard browser.

If you wanted to redirect to a certain page for either case, you can do something similar to the following as well:

if (Request.Headers["User-Agent"] != null && (Request.Browser["IsMobileDevice"] == "true" || Request.Browser["BlackBerry"] == "true" || Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC")) || Request.UserAgent.ToLower().Contains("iphone"))
{
Response.Redirect("http://
www.abwebsitedesign.com/mobile.html");
}
else
{

Response.Redirect("http://www.abwebsitedesign.com/standard.aspx");
}

Labels: , ,

Saturday, August 16, 2008

AddThis: An All-in-one Solution For Social Bookmarking

If you have tried to add different social bookmarking links to your website or blog, you surely aware of how painful it can be. In order to avoid some of the stresses that may occur, I strongly suggest trying out AddThis. Their little widget offers a very clean, simple, and unique alternative. At the bottom of this blog entry you will see a little toolbar that says "BOOKMARK," and when you cursor over it a small menu pops up, which displays different bookmarking tools such as digg, Reddit, Technorati, del.icio.us, etc. As of right now, 8/16/2008, it contains about 30 different bookmarking options -- and you can view them all by clicking on "more" in the menu, or if you just click on the toolbar itself.

If you do not use Blogger, you need not fret, AddThis is compatible with nearly all blogging software. Just go their website and get the code that you need.

If you want to use AddThis in your Google Blog (Blogger), use the following code:

NOTE: This method will only work if you are using the remote hosting option (remote FTP).


< type="'text/javascript'">addthis_url='< $BlogItemPermalinkURL$ >'; addthis_title='< $BlogItemTitle$ >">'; addthis_pub='yourusername';< /script >
< src="'http://s7.addthis.com/js/addthis_widget.php?v=" type="'text/javascript'">< /script >

  1. First, remove the extra spaces from the tags.

  2. Switch out "yourusername" with your AddThis account username.

  3. Add it to your page template. (It is probably best to put it right after the <$BlogItemControl$> tag.)

  4. Save & Republish

  5. All done!


If you have any questions or comments about this article, either post it on here, or email me at: blog[at]abwebsitedesign[dot]com.


Labels: , ,

Monday, August 11, 2008

Today's Websites: Clean, Clear, Simple

Today's websites are a clear indication of what one should expect to see as the web progresses. Most modern websites have a clean, simple layout. They are almost elegant. Careful contrasts, crisp colors, and content-concentric -- these new, shiny breed of websites are catching the eyes of their visitors. A fine example is the SEOmoz.org website. Personally, I love the color palette, the layout, the styling -- it's flawless.

Below is a list of features or layout and styling guidelines one should strive to follow in order to achieve Website Feng Shui.

  • Nice color scheme
  • Clean, scalable (and centered) layout
  • Prominent, intuitive navigation
  • Large, easy-to-read text
  • Good HTML structure
    (and semantically-correct markup)
  • Content served using text, not images
  • NO IMAGEMAPS
  • Use of alt and title attributes
  • No reliance on flash or javascript to display
    important aspects such as content, navigation,
    or internal/external links.
  • Cross-browser compatibility
  • Touch of creativity
I could certainly go on for days, but I think these are the main objectives to consider. If there is something you would like to see added to this list, email us at: blog[at]abwebsitedesign[dot]com

Labels: ,