Adding ELMAH to your ASP.NET Web Site

January 29, 2010 09:59

There's already a lot of posts out there on how to set up ELMAH (see References below). Still, as I went through the process of adding ELMAH to my own site, I found myself pulling information from multiple posts and even ran into a couple of surprises during deployment. So, in an effort to consolidate the information I needed and post solutions to the issues I had, I give you this post on the unhandled exception and error handling utility that is ELMAH.

What is ELMAH?

From the Google Code ELMAH home page:

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

In short, ELMAH is a utility that reports unhandled errors and exceptions. Looked at another way, ELMAH will display problems with your site that you might not otherwise see.

Adding ELMAH to an ASP.NET Web Site

1.) Get ELMAH

The first step is to actually get ELMAH. You can download from the Google Code page. Once you've got it, copy the file "Elmah.dll" into your site's bin folder.

2.) Modifying your web.config

There are a couple of initial modifications you'll have to make to your web.config:

a.) Add the following to the <httpModules> section:

<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>

b.) Add the following to the <httpHandlers> section:

<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />

3.) Deployment and dealing with initial issues

For the most basic ELMAH setup, that's it. You should be able to access your site's ELMAH logs by accessing http://yoursite/elmah.axd.

However, once you've deployed you might run into this error:

You are attempting to access ELMAH from a remote machine whereas it is currently configured not to allow remote access.

image

Fortunately, getting around this is pretty easy.

a.) Like it says, add a new <sectionGroup>:

<sectionGroup name="elmah">
    <section name="security" type="Elmah.SecuritySectionHandler, Elmah" />
</sectionGroup>

b.) Also, add the <elmah> section. I added it right underneath my <configSection> closing tag.

<elmah>
    <security allowRemoteAccess="yes" />
</elmah>

Again, redeploy the web.config file and we're done.

Except that, now, everyone in the world can view your ELMAH logs. Not good.

Securing ELMAH against unwanted eyes

Allowing everyone to view your ELMAH logs is generally not a good thing because an astute hacker could easily glean information from those logs and potentially exploit your site. So, we'll add some basic security.

1.) Include the admin path

Include the admin path in the httpHandler "add" so it looks like:

<add verb="POST,GET,HEAD" path="/admin/elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />

2.) Add a <location> section

This stands as it's own sub-section beneath the main <configuration> tag:

<location path="admin">
    <system.web>
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</location>

Now, we're done. When you access http://yoursite/admin/elmah.axd, you should be prompted for your credentials (assuming you're using ASP.NET's built-in security; see Phil Haack's post for more info).

If you're using BlogEngine.NET, add ELMAH to your admin menu

This is just an ease-of-access thing. If you add ELMAH to your web.sitemap, BlogEngine.NET will automatically pick it up and display in your admin menu.

Just add this to your sitemap file:

<siteMapNode url="~/admin/elmah.axd" title="ELMAH" description="" roles="administrators"/>

Conclusion

This concludes our discussion on how to add ELMAH to an ASP.NET web site.

References

 

[ Get 2GB of free online storage from Dropbox ]


The IIS SEO Toolkit

December 27, 2009 16:09

Scott Guthrie recently gave a shout-out to the IIS SEO Toolkit on his blog. I don't know about you, but something about SEO always brings up thoughts of greasy salesmen and used cars. Best purge those preconceptions from your mind, though, cause SEO is important.

Even excepting SEO, the SEO Toolkit is a great way to find other issues with a web site. For example, large content files (such as images, which can probably be shrunk down), duplicate keywords, missing meta information, missing content, and other information will all be revealed once you run the Toolkit against your site.

Scott gives a nice overview of the tool; I'll let his discussion get you started and jump right into what the tool showed me.

SEO Toolkit Analysis

Upon running your first analysis you'll get something like this (I ran the analysis against my fiction site, scottmarlowe.com):

image

The statistic I'm most concerned with is the "Number of Violations". I've got over 37,000 of them!

Turns out it's not as bad as it may seem, or not as difficult to whittle that number down anyway. Here is the breakdown of violations:

image

Let's take a look at the big ones (the ones with the highest counts).

1. The page contains unnecessary redirects

Turns out most of these are of this variety:

image

The first link it is indicating is a permalink for a blog post that looks like this:

<a rel="bookmark" href="http://www.scottmarlowe.com/post.aspx? id=f3dc138a-e948-4613-b546-d805fb2703c5">Permalink</a>

This forum post suggests a quick fix for this:

For this particular URL I would consider adding a "nofollow" to the link…

I use BlogEngine.NET; the permalinks were created with "rel=bookmark" already. I couldn't find a whole lot more than this as far as what "bookmark" buys me:

 

Bookmark Refers to a bookmark. A bookmark is a link to a key entry point within an extended document. The title attribute may be used, for example, to label the bookmark. Note that several bookmarks may be defined in each document.

 

But just in case, I also learned that you can specify multiple "rel" tokens just by putting some whitespace between them:

<a rel="bookmark nofollow" href="http://www.scottmarlowe.com/post.aspx? id=f3dc138a-e948-4613-b546-d805fb2703c5">Permalink</a>

That should do it for that violation.

2. The title begins with a brand name

Here are the details:

Search engines often parse text so that words that appear earlier in a sentence are weighted higher than words that appear near the end of a sentence.  Page relevancy is calculated by the use of important keywords that describe the page content. A page about a specific topic should use a keyword related to that topic at the beginning of the <title> tag instead of using a site name or brand name ("scottmarlowe"), because those do not describe the contents on the page.

This one was easy to fix. I'd been using the format "scottmarlowe.com - <page name>" as the title of my document (web page), so based on the recommendation I simply flipped the title so it reads "<page name> – scottmarlowe.com".

3. The page contains multiple canonical formats

A good discussion of this particular violation can be found on the CarlosAg Blog in the post Canonical Formats and Query Strings - IIS SEO Toolkit. The details for one of the violations of this type from my Toolkit analysis reads:

The page with URL "http://www.scottmarlowe.com/category/Book-Reviews.aspx" can also be accessed by using URL "http://www.scottmarlowe.com/category/Book-Reviews.aspx?page=1".
Search engines identify unique pages by using URLs.  When a single page can be accessed by using any one of multiple URLs, a search engine assumes that there are multiple unique pages. Use a single URL to reference a page to prevent dilution of page relevance. You can prevent dilution by following a standard URL format.

I saw two ways of dealing with this violation:

a. Add a Disallow in robots.txt

Add the following to your robots.txt:

Disallow: /*?

This will prevent search bots from using other avenues to access a page they would have already indexed via the main url. This is the approach I took.

b. Add a <link> with rel="canonical"

Add the following for each link:

<link rel="canonical" href="http://www.my-site.com/my-canonical-url" />

Note that this is new and may not be supported by all search engines.

4. The request is disallowed by a Robots.txt rule

This one was informational, and, in fact, was a non-issue as the pages excluded from crawling by my robots.txt were not supposed to be crawled.

5. Large Content Files

The SEO Toolkit does a nice job of displaying your largest files:

image

In my case, I had a few image files that were part of different blog posts that were shrunk when displayed but were, in fact, quite large. A lot of bandwidth was being wasted downloading the oversized images before they were scaled down and rendered on the client machine. Identifying the pages where those images were being used was pretty easy. Just right-click on the image in question and select "View Pages Linking to this Page":

image

I realized I could live without the images on those particular posts so I simply deleted them from the pages where they were being used.

6. Duplicate Description

This turned out to be a programming problem where many pages were having the meta description set twice. I corrected the code and hope to not see the violation again the next time I run the analysis.

Some oddities

The SEO Toolkit does have some known problems. After running my fifth or so analysis I all of a sudden starting seeing the error "Invalid name character… The ':' character, hexadecimal value 0x3A, cannot be included in a name":

image

Turns out this is a known mishandling of meta information by the Toolkit and that there should be a fix released sometime soon. I'll update this post once they do.

Unfortunately this error prevented me from running any more analysis of my site, so I'll have to wait until the fix is released to verify if I've fixed the major violations.

Conclusion

SEO is an often mal-used term, but that doesn't change the fact that it is important if you want to make your site as search engine friendly as possible. The SEO Toolkit is a fast, easy way to help out with this.


Visual Studio Code Analysis vs. FxCop vs. StyleCop… what's the diff?

October 9, 2009 16:23

Since I started using the StyleCop for ReSharper add-on I've been delving a bit further into the other tools out there for doing code analysis: StyleCop, FxCop, and Visual Studio Code Analysis. Even only considering those three, it's a bit confusing. This post is my attempt to sort out, for my own benefit if nothing else, the differences between them.

Visual Studio Code Analysis

This code analysis tool is built into Visual Studio. It is performed as an after-build step (not to be confused with an actual post-build step). The description MSDN gives is this:

[The] code analysis for managed code tool analyzes managed assemblies and reports information about the assemblies, such as violations of the programming and design rules set forth in the Microsoft .NET Framework Design Guidelines.

Also, in a C++ project, we get this little bit of useful description information when enabling VS Code Analysis:

clip_image002

You enable VS Code Analysis for each project in the project's properties:

image

Enabling Code Analysis yields such warnings during build-time as:

image

Visual Studio Code Analysis is very similar to FxCop. In fact, the two share some common assemblies. There was some timing differences on when each product was released, and for some reason the two have grown-up next to each other rather than being merged. Code Analysis is not built into all versions of Visual Studio, which is probably why. In any case, the rule sets are very similar, though from what I can tell only FxCop allows you to customize your own rule sets.

FxCop

Here's the official description from MSDN for FxCop:

FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. Many of the issues concern violations of the programming and design rules set forth in the Design Guidelines for Class Library Developers, which are the Microsoft guidelines for writing robust and easily maintainable code by using the .NET Framework.

FxCop is very similar to Visual Studio Code Analysis, though it might be described as containing a super-set of the latter's rules. A little more about the difference in rule sets can be found here.

FxCop can be run as either a Windows application or at the command line. Use the latter as a post-build step for better integration with your build.

StyleCop

StyleCop is similar to FxCop, but it provides a different function and is, in fact, complementary to either FxCop or Code Analysis. (Note that it only works on C# source files.) It is mostly concerned with coding style and formatting. As such, it is run against source files, not assemblies like the other two analysis tools. It can be run from inside Visual Studio:

image

Or as a step in your build process. I haven't looked into CI integration yet, but I'll update when I've got those steps down. For right now, I'm making great use of the ReSharper add-on, which provides real-time StyleCop analysis as you code. It's good stuff.

Conclusion

So, what we have here is that FxCop/Code Analysis are practically one in the same, leaving StyleCop as the odd man out.

Personally, I don't see any reason to use FxCop. I've already got Visual Studio Code Analysis as part of Visual Studio, so throw in StyleCop and the StyleCop for ReSharper add-on and I'm good to go.

References

stackoverflow: Visual Studio Code Analysis vs StyleCop + FxCop

Code Analysis and Code Metrics: The VS Code Analysis Team Blog

bharry's WebLog: Clearing Up Confusion


C# Code Analysis with StyleCop for ReSharper

October 4, 2009 17:14

I'm always looking for new tools to add to my developer's toolbox. One such tool I recently came across is StyleCop for ReSharper.

StyleCop for ReSharper is a ReSharper add-on that enables real-time syntax highlighting of StyleCop rules. Normally, you run StyleCop by selecting "Run StyleCop" from the Tools menu:

image

The StyleCop for ReSharper takes it one step further by providing the same analysis, but in real-time and with squigglies:

image

The first thing you'll notice is that every single line has been flagged for violations! That's kind of ridiculous. Fortunately, there's a quick way to reduce that count by loosening up the rules a bit.

Prerequisites

Of course, to use the StyleCop for ReSharper add-on you'll need to have ReSharper. Also, if you attempt to install the add-on without first having installed StyleCop, you'll see this dialog:image

The latest version of StyleCop can be downloaded here.

Loosening up StyleCop's Rules

Before we start modifying the default rules, let's learn how to share a single StyleCop settings file across multiple solutions or projects.

StyleCop starts looking for a Settings.StyleCop rules or settings file in the project's local folder first. Regardless of whether it finds one or not, it works up the folder tree, looking for other copies of the file. Once it reaches the top of the chain, it goes back to the default install folder where there should always be a the global version of the file. It is possible to override the global settings by placing a copy of Settings.StyleCop in the local solution or project file. Also, you can have global settings which are overridden by solution-level settings which in turn might be overridden by project-level settings. All depends on how granular you want to get with your rules.

Personally, I only maintain a single Settings.StyleCop file for all of my projects and solutions by putting the file at the development root (d:\dev).

You'll find the global copy of Settings.StyleCop here:

image

Copy that into your development tree, then double-click on it. That will bring up the StyleCop Project Settings editor:

image

If you expand the "Enabled rules" nodes you'll see all sorts of rules that you can turn off.

Rules I Can Live Without

Here is the list of rules that I operate without. I'll add to this list as I get further into StyleCop's rule set. In general, I'm trying to adhere to the rules as given, but some of them are just a bit too nitpicky for my tastes.

 

StyleCop Rule Definition Why I Turned It Off
SA1000 KeywordsMustBeSpacedCorrectly This rule is telling me my choice of spacing around, for example, the keyword 'typeof' is not right. "Not right", in this case, is in conflict to my standard formatting rules, so this one is out.
SA1008 OpeningParenthesisMustBeSpacedCorrectly This rule seems to dictate no spaces between, say, a method name and an opening parenthesis. I like have a single space between such things, so this one stays off.
SA1027 TabsMustNotBeUsed Ah, yeah. I don't like spaces. I use tabs.
SA1101 PrefixLocalCallsWithThis In my mind, the "this" keyword is implied by its absence, and I generally do not use it unless there is some naming conflict present otherwise.
SA1117 ParametersMustBeOnSameLineOrSeparateLines  
SA1309 FieldNamesMustNotBeginWithUnderscore This is in exact conflict with the style guide I use, which advocates using an underscore as the prefix on private variables.
SA1502 ElementMustNotBeOnSingleLine There are times, for example for a getter/setter property definition, where you might want everyting on one line, including the curly braces. This ones gets turned off.
SA1503 CurlyBracketsMustNotBeOmitted I think this goes a bit too far. There are times where, for readability if nothing else, it's OK to omit the curly braces.
SA1512 SingleLineCommentMustNotBeFollowedByBlankLine Another one that is a bit too nitpicky. I'm happy just having comments in the code. Who cares about blank lines?
SA1515 SingleLineCommentMustBePrecededByBlankLine Same reasoning as SA1512.

Rules Off By Default That I Use

The other side of turning off default rules is turning on some that are off by default. Here are those:

 

StyleCop Rule Definition Why I Turned It Off
SA1124 DoNotUseRegions I hate regions. Nuff' said.

Conclusion

If we take a look at the code snippet from above we'll see that the squiggly-indicated violations have gone way down:

image

Still have some work to do, but at least it's a bit more manageable and realistic.