Sunday, September 30, 2007

SPWeb.Groups vs. SPWeb.SiteGroups

Here's a weird one that maybe someone will help me out with some day (you know once people actually start subscribing/reading to this blog). I'm working with the SharePoint Object model and I want to get at all the Groups within a given Site. So we write some code that looks a little like this:

using (SPSite topLevelSite = new SPSite(ConfigurationManager.AppSettings["ForumSharepointInstanceUrl"]))
{
using (SPWeb rootWeb = topLevelSite.OpenWeb())
{
foreach (SPGroup group in rootWeb.Groups)
{
//go do something clever...
}
}
}


If you've run code that's similar and you've found that certain groups are missing from the SPWeb.Groups collection don't feel like you're alone. As it turns out (at least from what I can discern) the SPWeb.Groups returns all the groups within the web that have at least one permission set. The SPWeb.SiteGroups however will return ALL groups. I have no idea why. I also couldn't find anything of use about the topic on the MSDN. I've also found blog entries from people who couldn't find specific SPUser objects when digging in the SPWeb.Users vs SPWeb.SiteUsers collections. Their complaint was similar that the SPWeb.Users collection would only find users who had already logged into the site.

Summing it up: Use SPWeb.SiteGroups, SPWeb.SiteUsers etc... and ask someone who has some real SharePoint chops.

Still Confused,
Tyler

6 comments:

tony said...

Certainly dated here, but to help you out a bit, SiteGroups returns ALL the groups at the site collection level. SPSite is higher in the object model hierarchy than SPWeb. SPWeb.Groups returns all the groups at the web site level.

So depending on what you want to do, say get all the groups for the current web site your in, use SPWeb.Groups, but if you want all the groups that have access to the entire site collection, use SPWeb.SiteGroups.

Clear anything up a bit?

Tyler Holmes said...

It does Tony thank you. I've spent a lot more time in SharePoint since I wrote this and have since then done 3 WSS Certs. Over the last year I've developed a little more clarity w.r.t. WSS! I wish you'd been around a year ago, I sure could have used your input. Thanks for the comment.

Best,
Tyler

Anonymous said...

You can't find mention in the API docs because these themselves are inferior and a sham. The company is relying on blogs to fill in the blanks on this overprices product.

Bruno Coelho said...

Thank you for this!!!

Lars Nielsen said...

Thanks for this - we had some code that has an Owners group as part of the site. The code used SPWeb.Groups and worked fine until the site was changed to inherit permissions from its parent. Suddenly the Owners group lost its permissions on the site, and the code threw an exception when trying to find the group in SPWeb.Groups

Anonymous said...

Thanks for the tip..saved me a lot of hair pulling :)