Use site properties to speed up your SharePoint web parts
Posted on Wednesday, 05 November 2008 08:36In the SharePoint implementation I'm working on, we have a site collection for each department. Each department has variables such as an ID and other information that other webparts require.
Previously, I'd just provided the option to specify these variables in the webpart controls. This worked but was very time consuming to populate when creating a new department.
I then came across away to add new properties to the site collection that can be called from any webpart. In my example, I'm submitting a form containing the values I want to set. In this case it's just a textbox with a department ID in it.
try
{
SPContext.Current.Site.RootWeb.Properties.Add("CurrentDeptID", _currentDeptID.Text);
SPContext.Current.Site.RootWeb.Properties.Update();
}
catch (Exception ex)
{
SPContext.Current.Site.RootWeb.Properties["CurrentDeptID"] = _currentDeptID.Text;
SPContext.Current.Site.RootWeb.Properties.Update();
}
Now I know what your thinking, why have I called the SPContext class on each line instead of creating an object. Well, there is a good answer. When working with the contextual site in the "correct" manner, I had an error each time about trying to use an SPWeb object that had been disposed of. This was not the case and after digging around found that this is a known issue, so adjusted my code to suit.
Anyone who reads my posts will see that I'm struggling by in asp.net, having had no formal training I need to fall back on logic in the face of more efficient code, so if there is a better way to do this, please let me know.
The try{} catch{} are used to trap whether an add event fails. You can only add a property once, so if it fails just try to update it.
Properties are retrieved in the same way.
_currentDeptID.Text = SPContext.Current.Site.RootWeb.Properties["CurrentDeptID"];
This makes a huge difference to productivity, saving us hours a week, give it a go!