I've been facing a very strange problem lately while working with Sharepoint Permissions using C#.
The Scenario:
What I want to achieve is to add a Read permission to an item (pdf document) in a sharepoint list only for a specific user. And this user is not supposed to have access to the site or the list, he should only be able to access the specified item.
Now, when I run my code, the user gets added successfully to that item and shows it in the item's permissions list inside Sharepoint.
However, when I try to open the document by logging in with that user, it shows the error, "Sorry, you do not have access to this page", which is not supposed to show, because I'm trying to open the document.
The strange part happens now. When I remove and re-add this same user in the permissions from within Sharepoint itself (not via code), the user is able to access the item correctly, as intended.
To Summarize:
So what's happening here is that when the permission is created via code, it does not work. And when it's added manually from Sharepoint, it works. And so far my code seems to be correct as well. It's written below:
private void Addpermissions(SPWeb _spWeb, int id, SPUser _user)
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var spSite = new SPSite(_spWeb.Url))
{
spSite.AllowUnsafeUpdates = true;
using (var currentWeb = spSite.OpenWeb())
{
currentWeb.AllowUnsafeUpdates = true;
SPRoleDefinition roleDefinition;
var spList = currentWeb.Lists["PDF(s)"];
var item = spList.GetItemById(id);
if (!item.HasUniqueRoleAssignments)
{
item.BreakRoleInheritance(true);
item.Web.AllowUnsafeUpdates = true;
spSite.AllowUnsafeUpdates = true;
}
spSite.AllowUnsafeUpdates = true;
roleDefinition = currentWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
var roleAssignment = new SPRoleAssignment(_user.LoginName, _user.Email, _user.Name,
_user.Notes);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
item.RoleAssignments.Add(roleAssignment);
item.Update();
currentWeb.AllowUnsafeUpdates = false;
spSite.AllowUnsafeUpdates = false;
currentWeb.Dispose();
spSite.Dispose();
}
}
});
}
Any help would be really appreciated! As I've been stuck on this issue since the past whole week.
Thanks in advnace!