Fixing MVC Sitemap Errors

When attempting to manually test a .NET MVC application, I got the following exception from Visual Studio:
MvcSiteMapException

Looking at the inner exception revealed this message:

An item with the same key has already been added.

The sitemap file for our application is pretty long (over 1300 lines of XML), but a co-worker pointed me to the potential culprit right away. There was a sitemap node near the end of the file that had empty strings for its controller and action attributes. As far as I can tell, this generates the default url for the site’s home page. Since it already exists, this results in the exception that’s thrown. Removing the sitemap node resolved our issue.  A couple of threads that I checked on stackoverflow (here and here) provide other possible causes for the error.

Identifying All Bad Mappings with AutoMapper

One of the long-running annoyances we’ve had with our test of AutoMapper configuration validity on my current project is that a test failure only revealed the first mapping that was wrong. I haven’t figured out why this is the case, but I’ve come up with a work-around that displays all the necessary information.

Because the exception thrown if one or more incorrect mappings is found is AutoMapperConfigurationException, my revised test catches that exception in order to print the source type, destination type, and the list of unmapped property names. Re-throwing the exception at the end ensures that the test still reports a failure. The XUnit test which demonstrates this is available as a GitHub gist. If you’re using NUnit or MSTest in your application, minor revisions to this test will give you the same results.