SharePoint – Setting users or groups for a membership webpart through code

This is a rather simple thing… well once you have cracked it :).

 

There are two properties which need to be set:

And that is it. To find the “main” associated groups to your site you could use these properties:

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedownergroup.aspx

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedmembergroup.aspx

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedvisitorgroup.aspx

https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.spweb.associatedgroups.aspx


using (SPSite site = new SPSite(wsSite.ID))
{
using (SPWeb web2 = site.OpenWeb(wsSite.RootWeb.ID))
{
var pubWeb = PublishingWeb.GetPublishingWeb(web2);

using (var wpm = pubWeb.DefaultPage.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
// Search for the right webpart(you could use LINQ instead of a foreach)
int memberShipWebPartsCount = 0;
for (int x = wpm.WebParts.Count - 1; x >= 0; x--)
{
var membersWebPart = wpm.WebParts[x] as Microsoft.SharePoint.WebPartPages.MembersWebPart;
if (membersWebPart != null)
{

// There are only two members webparts which are needed to be processed, at the moment
if (memberShipWebPartsCount < 2)
{
if (memberShipWebPartsCount == 0)
membersWebPart.MembershipGroupId = wsSite.RootWeb.AssociatedOwnerGroup.ID;
else if (memberShipWebPartsCount == 1)
membersWebPart.MembershipGroupId = wsSite.RootWeb.AssociatedMemberGroup.ID;

membersWebPart.DisplayType = Microsoft.SharePoint.WebPartPages.MembersWebPartDisplayType.GroupMembership;
wpm.SaveChanges(membersWebPart);

pubWeb.DefaultPage.Update();
if (pubWeb.DefaultPage.CheckOutType != SPFile.SPCheckOutType.None)
pubWeb.DefaultPage.CheckIn("");

if (pubWeb.DefaultPage.ParentFolder.DocumentLibrary.EnableVersioning && pubWeb.DefaultPage.ParentFolder.DocumentLibrary.EnableMinorVersions)
pubWeb.DefaultPage.Publish("");
}
memberShipWebPartsCount++;
}
}

}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s