Stack Overflow when building up SiteMap structure

In iteration 10, we wrote HierarchicalConfigSiteMapProvider that builds up a tree of sitemap nodes based on xml retrieved from the hierarchical ConfigManager. Being a newbie with SiteMapProviders, I overwrote BuildSiteMap calling a simple recursive method that traverses the xml and builds corresponding sitemap nodes. All of a sudden I get a stack overflow exception. No problem, I thought. Probably a bug in my recursive method. Hmmm… Looks fine. :|

Turns out, I was calling siteMapNode.ChildNodes.Add(myNewSiteMapNode). This didn’t seem so crazy at the time. The problem is that the ChildNodes property actually calls GetChildNodes, which calls BuildSiteMap… They tell two friends, and they tell two friends. Boom. Stack Overflow. Tess Ferrandez blogs about this also but this issue it is worth mentioning again since I’m sure lots more people will run into this.

The solution: Instead of using the ChildNodes property, you should use SiteMapProvider.AddNode. This is also documented in this article on SiteMapProviders.