2009-12-15 60 views
0

我希望你能解決我的問題。如何獲得苔蘚中的當前用戶組?

我正在嘗試使用事件處理函數爲Sharepoint列表和文檔libraraies設置項目級pemrissions,但我做不到。請幫助我這是我的代碼。我需要根據登錄用戶爲項目分配權限他屬於哪個組。我無法檢索當前用戶組。這是我的代碼。

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; 
     } 
    } 
    } 
} 

回答

0

試試這個:

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; 
    } 
    } 
}