SharePoint 2010 change list permission - sharepoint

I have a list contained in an SPWeb and when the web is provisioned an event receiver change the list permissions by using this code:
[...]
SPList theList = web.Lists[listName];
theList.BreakRoleInheritance(false);
SPGroup group = web.Groups["MyGroup"];
SPRoleAssignment ra = new SPRoleAssignment(group);
SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
ra.RoleDefinitionBindings.Add(roleDef);
list.RoleAssignments.Add(ra);
list.Update();
Later in the workflow I need to change the permission for the group to be Reader instead of Contributor. I have used the following code
SPList theList = web.Lists[listName];
foreach (SPRoleAssignment assignment in theList.RoleAssignments) {
if (assignment.Member.Name == "MyGroup") {
assignment.RoleDefinitionBindings.RemoveAll();
SPRoleDefinition rda = web.RoleDefinitions.GetByType(SPRoleType.Reader);
assignment.RoleDefinitionBindings.Add(rda);
}
}
However this code is not working and does not change the permission on the list.
Could anybody help on understanding which is the right method to change permission for an existing principal?
Thanks

You need to do a theList.Update() after your foreach statement.

Related

CSOM give edit permissions to group on SharePoint list

I'm creating a new list in CSOM for SharePoint Online, but I'm very new to this so I'm stuck on changing the permissions.
There are 3 user groups, owners, visitors and members. I'd like to give the visitors editing rights on this list.
I've managed to break inheritance and get all the visitors with the following code, but I'm stuck on how to give them new permissions
newList.BreakRoleInheritance(false, true);
var visitors = ctx.Web.SiteGroups;
ctx.Load(visitors, groupitems => groupitems.Include(groupitem => groupitem.Title,
groupitem => groupitem.LoginName).Where(groupitem=> groupitem.Title == visitorsGroupName));
You can do something similar to this one:
foreach(var grpUser in grpUsers)
{
Principal user = ctx.Web.SiteUsers.GetByLoginName(grpUser);
RoleDefinition writeDefinition = ctx.Web.RoleDefinitions.GetByName("Edit");
RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(ctx);
roleDefCollection.Add(writeDefinition);
RoleAssignment newRoleAssignment = ctx.Web.RoleAssignments.Add(grpUser, roleDefCollection);
}
ctx.ExecuteQuery();
This assumes that there is an "Edit" permission level which is available by default in SharePoint. Let me know if it works.
You could try this
var EditRole= new RoleDefinitionBindingCollection(ctx);
EditRole.Add(ctx.Web.RoleDefinitions.GetByType(RoleType.Editor));
Microsoft.SharePoint.Client.Group visitors= ctx.Web.SiteGroups.GetByName("visitors");
ctx.Load(visitors);
newList.RoleAssignments.Add(visitors, EditRole);
ctx.ExecuteQuery()

Read items from list in host-web from provider-hosted app

I have a provider hosted app. and I'm trying to get to the listitems in a list that is on my host-web.
I can get a list of all the lists I have. But when I try to get to the listitems, it's always empty.
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
ListCollection lists = clientContext.Web.Lists;
List list = lists.GetByTitle("TestList");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><RowLimit>100</RowLimit></View>";
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(camlQuery);
clientContext.Load<ListCollection>(lists);
clientContext.Load<List>(list);
clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(items);
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
Response.Write("<br />" + item.FieldValues["Title"]);
}
}
In the AppManifest.xml i added a 'full control' permission for list
In the AppManifest.xml add a READ permission for list and Web
Apparently I did everything correct. When installing I still had to say which lists it had full control on.
Your code is perfectly fine ....
Just you have to make change in "AppManifest.xml" file permission give site collection as full control as you are using host web .

Set permission for user programmatically? (sharepoint)

I am using the following code to set permission for groups when I create a site:
// Assign Site Owner role to the selected users
string siteOwnerGroup = null;
string siteOwnerRole = null;
foreach (ListItem item in lbSiteOwner.Items)
{
siteOwnerGroup = item.Text.ToString();
siteOwnerRole = "Full Control";
SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteGroups[siteOwnerGroup]);
SPRoleDefinitionBindingCollection roleDefinition = roleAssignment.RoleDefinitionBindings;
roleDefinition.Add(web.RoleDefinitions[siteOwnerRole]);
web.RoleAssignments.Add(roleAssignment);
web.Properties[siteOwnerGroup] = siteOwnerRole;
web.Properties.Update();
}
Shouldn't it be easy to change this to set permission for users in the lbSiteOwner listbox instead?
I tried
SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteUsers[siteOwnerGroup]);
But it doesn't work, any ideas?
Thanks in advance.
following solution will hold true in your case as well in place of list use web
Programatically add user permission to a list in Sharepoint

SharePoint permissions for a specific group

I'm trying to establish whether a specific group has Read access to a particular site collection.
I have been trying for a day and a half but feel as if I have found three halves of different solutions!
The code fragments I have so far are:
using (SPSite site = new SPSite(this.GenerateAbsoluteUri(moduleCode, academicYear)))
{
using (SPWeb web = site.OpenWeb())
{
for (int i = web.SiteGroups.Count - 1; i >= 0; i--)
{
SPGroup group = web.SiteGroups[i];
if (Regex.IsMatch(group.Name, theGroupImLookingFor))
{
but then what?!
Most of my Google results tell me about roles but I don't know how to tie a role to a group.
Please help!
To assign permission to a user (account) or a SharePoint group there are some objects that we need to look at in a certain order. The first thing we need to do is get the the security principal that we want to assign the role to (SPUser or SPGroup). The next thing we need to do it get the actual permission (role) that we want to assign (ex: Read, Full Control etc…). Then we need to create a SPRoleAssignment object and on the constructor pass it in the SPUser or SPGroup (security principal) that we want to assign the permissions to. Now we need to add the role definition to the RoleDefinitionBindings collection of the role assignment object. Then we need to add the actual role assignment to the web (site) and update the web. Below is the full code lisitng.
// Create the site that contains our list
using(SPSite oSite = new SPSite("<<my site url>>"))
{
// Open the web object
using(SPWeb oWeb = oSite.OpenWeb())
{
// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];
// Get the role definition we want to assign ex: Full Control
SPRoleDefinition oRole = oWeb.RoleDefinitions["<< role name>>"];
// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);
// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(oRole);
// Now we need to add the role assignment to the web
oWeb.RoleAssignments.Add(oRoleAssignment);
// Now update the web
oWeb.Update();
}
}
Heres snippets from my own code (Sharepoint 2010).
Creating a role:
SPRoleDefinition network_role = new SPRoleDefinition();
network_role.BasePermissions = SPBasePermissions.AddListItems |
SPBasePermissions.BrowseDirectories |
SPBasePermissions.EditListItems |
SPBasePermissions.DeleteListItems;
network_role.Name = "Network - Project Member";
network_role.Description = "Provides permissions required for a member of a project.";
web.RoleDefinitions.Add(network_role);
Adding a role to a group:
var assign = new SPRoleAssignment(oweb.SiteGroups["Network Project - " + item.Code]);
assign.RoleDefinitionBindings.Add(network_role);

How to define specific permissions?

on the project i'm working we have a site (the front office) which is accessible by anonymous users, and a subsite (the back office) which access is restricted. In the back office, i want to restrict the access of one specific page (e.g, /Pages/specificpage.aspx) to only users who are members of a certain group.
How can i do that programmatically?
Thanks.
First you create a group for this permission type. You do that from the "People and Groups" page.
Then you go to your Pages list by browsing to the http:/Pages.
Click on the drop down menu on the page/item in question and select "manage permissions".
On the Actions menu, select "Edit permissions" and click Ok to break inheritance.
Remove the default (inherited) permissions (user/groups) by put a check mark in them and select Action-s>Remove User Permissions.
On the New menu, select "Add users", enter the name of your group , select the desired permissions and click Ok.
And here's how to do it programmatically:
using (SPSite site = new SPSite("<YOUR URL>"))
{
using (SPWeb web = site.OpenWeb())
{
// Get the group you want to assign to the item
SPGroup group = web.Groups["<YOUR GROUP NAME>"];
SPPrincipal principal = group as SPPrincipal;
// Define the role definitions
SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;
SPRoleDefinition[] rolesToApply = new SPRoleDefinition[1] { roleDefinitions["Contribute"] };
// Or whatever role definition you want to assign
SPRoleAssignment newRoleAssignmentToAdd = new SPRoleAssignment(principal);
foreach (SPRoleDefinition roleDefinition in rolesToApply)
{
if (roleDefinition != null)
{
newRoleAssignmentToAdd.RoleDefinitionBindings.Add(roleDefinition);
}
}
// Choose your list
SPList list = web.Lists["Pages"];
// Query for the item/file/page
SPQuery query = new SPQuery();
query.RowLimit = 2000;
query.ViewFields = "<FieldRef Name='Title' />";
query.Query = string.Format(#"<OrderBy><FieldRef Name='ID'/></OrderBy>
<Where>
<Eq>
<FieldRef Name='FileLeafRef'/>
<Value Type='Text'>{0}</Value>
</Eq>
</Where>", "<YOUR PAGE NAME>");
// Get the list item
SPListItemCollection items = list.GetItems(query);
if (items.Count > 0)
{
SPListItem item = items[0];
// If the item doesn't have unique permissions, set it to have that
if (!item.HasUniqueRoleAssignments)
{
item.BreakRoleInheritance(false);
}
// Add your role definition
item.RoleAssignments.Add(newRoleAssignmentToAdd);
}
}
}
To set the permissions pragmatically you need to do the following.
1) Break Role Inheritance of the item
2) Add the new role assignment
To break the Break Role Inheritance of an item you call the BreakRoleInheritance method on the item, passing true will copy the current permissions for the list to the item.
item.BreakRoleInheritance(false);
You then need to get the items Role Assignments collection and add a new role assignment to it. The role assignment is created for a SPPrincipal and has a SPRoleDefinition bound to it.
SPRoleAssignmentCollection rolesAssignments = item.RoleAssignments;
SPRoleAssignment userRoleAssignment = new SPRoleAssignment(principal);
userRoleAssignment.RoleDefinitionBindings.Add(roleDefinition);
rolesAssignments.Add(userRoleAssignment);
To fetch a Role Definition you can go to the current SPWeb’s FirstUniqueRoleDefinitionWeb property so you keep any customisations that have been made to your sites permissions and then use the SPWeb’s Role Definitions Collection. (I am not too sure of the disposal pattern for the FirstUniqueRoleDefinitionWeb property, if you are using SPContext Dont dispose it)
if (web.FirstUniqueRoleDefinitionWeb != null)
{
using (SPWeb firstUniqueRoleDefinitionWeb = web.FirstUniqueRoleDefinitionWeb)
{
return firstUniqueRoleDefinitionWeb.RoleDefinitions[roleName];
}
}
return web.RoleDefinitions[roleName];
Hope this helps you in the right direction

Resources