Here's code which will grant rights for a user to a specific list item in SharePoint 2007.
One thing you might notice - if you aren't already used to it - is the Contact object parameter. This is an AWSOME object from the Microsoft.Office.Workflow.Tasks assembly in the Microsoft.Office.Workflow.Utility namespace. I use it all the time in my SharePoint 2007 coding, as it really makes working with a user use so much easier.
/// <summary>
/// Grants access to a list item for a user.
/// If the user already can edit the item, the new role will not be applied.
/// </summary>
/// <param name="web">SPWeb object which contains the list item</param>
/// <param name="listItem">SPListItem to grant access to</param>
/// <param name="user">User to grant access to SPListItem</param>
/// <param name="roleType">Role to grant user</param>
/// <param name="overrideEditRights">If the user already has edit rights, this will </param>
public static void GrantListItemAccessToUser(SPWeb web, SPListItem listItem, Contact user,
SPRoleType roleType, bool overrideEditRights)
{
SPUser spuUser = null;//container for user when we check to see if they have rights
//if it is a SPUser object then we know we can populate the SPUser container object
if (user.IsSPUser)
{
try
{
spuUser = web.AllUsers[user.LoginName];
}
catch
{
spuUser = null;
}
}
bool grantAccess = true;//bool to check if they need to be provided access - default to true
//if we have the SPUser object, then we know they are already a member of the site,
//and we can check if they can edit the item already are the owner of the object
if (spuUser != null)
{
if (listItem.DoesUserHavePermissions(spuUser, SPBasePermissions.EditListItems))
grantAccess = false;
}
if (overrideEditRights)
grantAccess = true;
if (grantAccess)
{
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (web.Site)
{
try
{
web.AllowUnsafeUpdates = true;
SPRoleDefinition RoleDefinition =
web.RoleDefinitions.GetByType(roleType);
SPRoleAssignment RoleAssignment = new SPRoleAssignment(user.LoginName,
user.EmailAddress, user.DisplayName, string.Empty);
RoleAssignment.RoleDefinitionBindings.Add(RoleDefinition);
//Check for permission inheritance, and break if necessary
if (!listItem.HasUniqueRoleAssignments)
{
listItem.BreakRoleInheritance(true);
}
//Add Role Assignment to SPListItem's Role Assignment Collection
listItem.RoleAssignments.Add(RoleAssignment);
/*
* This block sucks, I know
* The only way around the dreaded 'Save Conflict' error is to wrap
* this up in a try/catch block
*/
try
{
listItem.Update();
}
catch (SPException ex) { }
}
catch (Exception ex)
{
throw ex;
}
}
}
);
}
}