Get SPGroup, If Not Available, Create!
When developing for calls to SPGroup objects in SharePoint, often times it is best to guarantee that the group exists by placing a creation guard clause in that will create the SPGroup if it is not available off the SPWeb from the initial query.
The GetGroupOrCreate method provided below does just that:
-
public static SPGroup GetGroupOrCreate(SPWeb web, string name, string description, SPUser owner, SPUser defaultUser, bool associate)
-
{
-
SPGroup groupToReturn = null;
-
foreach (SPGroup group in web.SiteGroups)
-
{
-
if (!group.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) continue;
-
-
groupToReturn = group;
-
break;
-
-
}
-
if (groupToReturn == null)
-
{
-
web.SiteGroups.Add(name, owner, defaultUser, description);
-
groupToReturn = web.SiteGroups[name];
-
}
-
if (associate && !web.AssociatedGroups.Contains(groupToReturn))
-
{
-
web.AssociatedGroups.Add(groupToReturn);
-
web.Update();
-
}
-
return groupToReturn;
-
}
The SPWeb parameter is the web associated with the SPGroup you wish to query or create
The name parameter represents the name of the group to query or create
The description parameter provides a description for the SPGroup if creation is required
The owner parameter is the owner of the SPGroup represented by an SPUser object
The defaultUser parameter is the first SPUser to be put into the SPGroup
The boolean associated defines whether the SPGroup should be added to the SPWeb.AssociatedGroups collection
It is important to note that I am using InvariantCultureIgnoreCase to perform a case-insensitive string comparison using the word comparison rules of the invariant culture.
2 Comments »
RSS feed for comments on this post. TrackBack URL























Articles & Research
SharePoint Architecture
Personal/Off-Topic
Article Or Research Filed Under 

[...] Get SPGroup, If Not Available, Create! [...]
Pingback by Links (2/26/2009 « Steve Pietrek - Everything SharePoint) — February 26, 2009 @ 6:50 pm
[...] Another use for this pattern is the creation of SharePoint groups, inspired by Adam Buenz’s recent post. His code is correct (though I believe an ordinal comparison is more appropriate than invariant culture), but it can’t easily handle scenarios requiring elevation, AllowUnsafeUpdates, etc. Instead, we can define a higher-order function like this: [...]
Pingback by More SharePoint Higher-Order Functions « Solutionizing .NET — March 19, 2009 @ 12:49 am