When programming with SharePoint I usually try to use the SPContext as much as possible in stead of opening a new Web. I assume that opening a new Web will cost more resources then reusing an existing one.
But the Web object from the context has some weird behavior. For example adding a property to the property bag doesn’t always succeed:
SPContext.Current.Web.Properties.Add["MyKey"] = "MyValue"; SPContext.Current.Web.Properties.Update(); SPContext.Current.Web.Update(); // just to be sure ;-)
This code will execute successfully and for the lifecycle of the program the property is available but when a new instance tries to access the property it isn’t there anymore.
int count = SPContext.Current.Web.Lists["MyList"].Views["All Items"].ViewFields.Count;
This line of code will work on some sites but not on all sites… On some sites it will show the actual number of fields while other sites have a count of 2 and only the fields Attachments and Title.
Changing the code will always return the correct fields:
using (SPWeb spWeb = SPContext.Current.Site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl))
{
SPList myList = spWeb.Lists["MyList"];
int count = myList.Views["All Items"].ViewFields.Count;
}
Strange… after three years of SharePoint programming I have never encountered this issue. And now I have solved two issues with it on the same day.


[...] SPContext.Current.Web or SPContext.Current.Site.OpenWeb()? September [...]