Create sharepoint group programmatically and assign permissions to new group.
private void CreateSharepointGroup()
{
ArrayList groupList = new ArrayList();
groupList.Add(” Home Owners”);
groupList.Add(” Home Members”);
groupList.Add(“Home Contribute”);
groupList.Add(” Home Visitors”);
using (SPWeb oWebsite = SPContext.Current.Site.OpenWeb(“Website_URL”)) eg: (site1/Subsite2)
{
SPUser sUser = oWebsite.CurrentUser;
foreach (string groupName in groupList)
{
if (!ContainsGroup(oWebsite.SiteGroups, groupName))
{
oWebsite.SiteGroups.Add(groupName, oWebsite.SiteUsers[sUser.LoginName],
oWebsite.SiteUsers[sUser.LoginName], “Use this group to give users to give permissions to the SharePoint site”);
if (groupName.Contains(“Owners”))
{
SetRoleDefinitionBinding(groupName, oWebsite, “Full Control”);
}
else if (groupName.Contains(“Members”))
{
SetRoleDefinitionBinding(groupName, oWebsite, “Limited Access”);
}
else if (groupName.Contains(“Contribute”))
{
SetRoleDefinitionBinding(groupName, oWebsite, “View Only”);
}
else if (groupName.Contains(“Visitors”))
{
SetRoleDefinitionBinding(groupName, oWebsite, “View Only”);
}
}
}
}
}
// Assign permissions
private void SetRoleDefinition(string groupName, SPWeb oWebsite, string permissionLevel)
{
// add the read role definition to the site group
SPRoleAssignment roleAssignment = new SPRoleAssignment(oWebsite.SiteGroups[groupName]);
roleAssignment.RoleDefinitionBindings.Add(oWebsite.RoleDefinitions[permissionLevel]);
oWebsite.RoleAssignments.Add(roleAssignment);
oWebsite.Update();
}
// check whether group exist or not
private bool ContainsGroup(SPGroupCollection groupCollection, string index)
{
try
{
SPGroup testGroup = groupCollection[index];
return true;
}
catch (SPException e)
{
return false;
}
}
No comments:
Post a Comment