Wednesday, August 24, 2011

SiteMap Providers static property issue


There is a time when we need to modify a sitemap provider object and then use it.

Scenario:
We need to build a sub navigation control but we don’t want to include pages

Example code:
PortalSiteMapProvider sitemapprovider =                    (PortalSiteMapProvider)SiteMap.Providers["CurrentNavSiteMapProvider"];
               
sitemapprovider.IncludePages = PortalSiteMapProvider.IncludeOption.Never;

The problem with the code above is:
1.       The SiteMap.Providers property is a static property. It returns the object reference to the single instance of the provider.
2.       Modifying the object permanently changes the value.

One way to avoid this issue is to save the value of the property temporarily and then rollback the value back.

Example code:
ortalSiteMapProvider sitemapprovider =
(PortalSiteMapProvider)SiteMap.Providers["CurrentNavSiteMapProvider"];
               
var tempIncludePages = sitemapprovider.IncludePages;

sitemapprovider.IncludePages = PortalSiteMapProvider.IncludeOption.Never;

sitemapprovider.IncludePages = tempIncludePages;

This simple workaround seems to work properly.

Hope this helps J