Share via


Interesting SharePoint Gotcha

 

As noted by Nishand in a blog posting several years ago, SharePoint 2007 had a number of peculiarities around when a instance of an object was needed versus when it wasn’t. In SharePoint 2010, this has not been changed.

I just had a client ask me about this specific example:

In order to change the default page of an SPWeb that is not a PublishingWeb, you have to set the WelcomePage property of the SPFolder class. In this case, that SPFolder class can be obtained via the RootFolder property.

As with most programming, the quickest route would seem to be the ideal choice to make; thus, the following should work like a champ:

 web.RootFolder.WelcomePage = “NewWelcomePage.aspx”;
web.RootFolder.Update();

And yet while stepping through the code, it was plain to see that this code was not working. It turns out that, due to some peculiarities of the code within the SPWeb and SPFolder classes, it is necessary to actually create and hold an instance of the SPFolder class whose WelcomePage value you want to change. Thus, this code does work:

 SPFolder folder = web.RootFolder;
folder.WelcomePage = “NewWelcomePage.aspx”;
folder.Update();

My guess is that this is due to the way the SPWeb object is getting at the SPFolder object represented by RootFolder. Namely, it isn’t unless that object is specifically requested. Thus, a call to web.RootFolder.WelcomePage would directly access the resource indicated by the WelcomePage property and allow the getter to retrieve the current value. Since, however, the SPFolder class is what actually handles updating this value, however, only after getting an instance of the SPFolder object represented by RootFolder will a process have the necessary means for updating the value of RootFolder.

And an SPFolder instance of RootFolder isn’t actually retrieved unless it’s specifically requested.

From a resource standpoint, it makes sense. From a usability standpoint, it leaves a lot to be desired.

HTH,

Chris