iPhone Detected, site running in minimal mode.
Home     Tags/Archives     Tweets     About Kevin

SPWeb PropertyBag

If you need to stash some information for later use (for example, by a web part) in a SharePoint (MOSS or WSS) site a great place to do it is the SPWeb PropertyBag.  However, I recently ran into some quirks with this so I thought I'd share my lessons learned:
 
The PropertyBag object is accessed via the .Properties property of an SPWeb object and it's a StringDictionary.  However, know that this property is readonly (the property itself, not the PropertyBag object).  This means that to make any changes to it you need to first get a reference pointer to it.  Put another way, this code will not work:
 
SPWeb web = site.RootWeb;
web.Properties["SomeProp"]="SomeValue";
web.Properties["SomeProp"].Update();
 
However, this code will:
 
SPWeb web = site.RootWeb;
SPPropertyBag prop = web.Properties;
prop["SomeProp"]="SomeValue";
prop["SomeProp"].Update()
 
Also, don't forget to call .Update() or it won't persist to the database.  When you are just reading data out, you don't need to worry about the above subtlety of getting a reference first.
 
There isn't a PropertyBag on the SPSite object, but don't worry... if you need to stash data at the site collection level, just use the RootWeb object (as I did in the above example).  You may want to preface the StringDictionary key with s_ or site_ in these cases to avoid collisions with data intended to be "virtually" scoped at the web level.
 
Where are some places it may make sense to store data here?
  • When activating a feature, use a FeatureReceiver class to populate needed inital data.
  • Update the data via a web part or a _layouts application page (don't forget to write a feature to add a link somewhere to the app page).
  • Consume this data from webparts, app pages, workflows, list event handlers, etc...

Obviously you can also store this type of data in a list, however, often this is not desired because a) requires more overhead in the actual reads/writes, b) can be more easily messed up by users, c) is messier, and d) is a bit overkill if you just need a simple key/value string pair or a few of them.  Of course if you need dimmensional flexibility, then the list is better since you can add columns and can store multiple values (rows).


Comments

 

RSS FeedBack to the HomepageMy Twitter Feed and More!Video Chat Now!

Tags

Hide Low Frequency Tags

Archives

Recent Posts