Articles

SPContext.Current.Web or SPContext.Current.Site.OpenWeb()?

In SharePoint on September 21, 2009 by Harold

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.

Another example is reading the number of ViewFields of a list view:
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.

About these ads

One Response to “SPContext.Current.Web or SPContext.Current.Site.OpenWeb()?”

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: