Company      |       Articles & Research      |      Services      |      Software      |      Contact

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:

C#:
  1. public static SPGroup GetGroupOrCreate(SPWeb web, string name, string description, SPUser owner, SPUser defaultUser, bool associate)
  2. {
  3. SPGroup groupToReturn = null;
  4. foreach (SPGroup group in web.SiteGroups)
  5. {
  6. if (!group.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) continue;
  7.  
  8. groupToReturn = group;
  9. break;
  10.  
  11. }
  12. if (groupToReturn == null)
  13. {
  14. web.SiteGroups.Add(name, owner, defaultUser, description);
  15. groupToReturn = web.SiteGroups[name];
  16. }
  17. if (associate && !web.AssociatedGroups.Contains(groupToReturn))
  18. {
  19. web.AssociatedGroups.Add(groupToReturn);
  20. web.Update();
  21. }
  22. return groupToReturn;
  23. }

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.

share save 171 16 Get SPGroup, If Not Available, Create!

Related posts:

  1. Test Whether SPUser Is In SPGroup
  2. SharePoint Security Tip: ExplicitlyContainsCurrentUser
  3. String.Compare for Performance And Readability
  4. SharePoint Security Helper Class
  5. Comparing SPPrincipal Objects To See If Same Member

2 Comments »

  1. [...] Get SPGroup, If Not Available, Create! [...]

    Pingback by Links (2/26/2009 « Steve Pietrek - Everything SharePoint) — February 26, 2009 @ 6:50 pm

  2. [...] 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

RSS feed for comments on this post. TrackBack URL

Leave a comment