kamagra how much to take

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:

  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;
  8. groupToReturn = group;
  9. break;
  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.


No Comments


  1. Links (2/26/2009) « Steve Pietrek - Everything SharePoint - [...] Get SPGroup, If Not Available, Create! [...]
  2. More SharePoint Higher-Order Functions « Solutionizing .NET - [...] Another use for this pattern is the creation of SharePoint groups, inspired by Adam Buenz’s recent post. His code …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>