How to get current user groups in moss?
I hope you can solve my problem.
I am trying to set item level pemrissions for sharepoint list and document libraraies using event handler ,but i couldn't do it.please help me this is my code.I need to assign permissions to the item based on login user .to which group he belongs to.I can't retrieve the currentuser groups. this is my code.
public override void ItemAdded(SPItemEventProperties properties)
{
开发者_开发百科 using (SPSite _site = new SPSite(properties.WebUrl))
{
using (SPWeb spWeb = _site.OpenWeb(properties.RelativeWebUrl))
{
SPUser currentUser = spWeb.CurrentUser;
SPListItem listItem = properties.ListItem;
listItem.BreakRoleInheritance(true);
SPGroupCollection spgroup = currentUser.Groups;
foreach (SPGroup group in spgroup)
{
SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);
SPRoleDefinition roleDefinition = spWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
listItem.RoleAssignments.Add(roleAssignment);
spWeb.AllowUnsafeUpdates = true;
listItem.Update();
spWeb.AllowUnsafeUpdates = false;
}
}
}
}
Try this:
public override void ItemAdded(SPItemEventProperties properties)
{
// run the code impersonating the web application account, this works better than the regular RunWithElevatedPrivileges
using (var site = new SPSite(properties.SiteId, properties.ListItem.ParentList.ParentWeb.Site.SystemAccount.UserToken))
{
using (var web = site.OpenWeb(properties.RelativeWebUrl))
{
web.AllowUnsafeUpdates = true;
var item = web.Lists[properties.ListId].GetItemById(properties.ListItemId);
item.BreakRoleInheritance(false);
foreach (SPGroup group in web.CurrentUser.Groups)
{
var assignment = item.Web.RoleAssignments.GetAssignmentByPrincipal(group);
var roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
assignment.RoleDefinitionBindings.Add(roleDefinition);
item.RoleAssignments.Add(assignment);
}
DisableEventFiring();
item.SystemUpdate(false);
EnableEventFiring();
web.AllowUnsafeUpdates = false;
}
}
}
精彩评论