Assign Group permission to list item using client object model
Hi,
I am trying to add the list item and assign the permission to the list item by using SP 2010 client object model. The problem which i am facing that when i assign the group as a permission to the item, by automatically the limited access permission
is added to the group. Please find the steps which i have followed,
Step-1: Break role inheritance.
foreach (var item in _listItemCollection)
if (item["FileLeafRef"].ToString().ToLower() == "xxx")
item.BreakRoleInheritance(true, false);
_clientContext.Load(item.RoleAssignments);
_folderItem = item;
_clientContext.ExecuteQuery();
Step 2: Remove all permissions of the list item.
foreach (var assignment in _folderItem.RoleAssignments)
assignment.RoleDefinitionBindings.RemoveAll();
assignment.Update();
_clientContext.ExecuteQuery();
Step 3:
Add Group as a permission to the list item.
var role = _web.RoleDefinitions.GetByType(RoleType.Contributor);
var collRdb = new RoleDefinitionBindingCollection(_clientContext) { role };
Principal principal = _grp;
_folderItem.RoleAssignments.Add(principal, collRdb);
_folderItem.Update();
_clientContext.ExecuteQuery();
After adding the group successfully to the list item, i checked the group permission and it contains the value as "Contribute,Limited Access" to the site level and "Contribute" to the list item. Please guide me how to avoid to create Contribute,Limited
Access role.
Balaji
Hi Dmitry,
When I create the group and assign contribute permission, the group has the permission at the site level(to see the permission, click group and click view Group Permission). I have added the list item and break the role inheritance permission
and given the unique permission by providing group as a permission to the list item. After providing the permission, the group permission at the site level changed to "Contribute, Limited Access". I dont know how contribute permission changed to contribute,
limited access.
I found the workaround to fix this issue. I created the group and create the folder in the shared document library by using client object model. Due to facing some issue by providing the permission using client object model, i have created the event receiver
to the document library and using server object model, i can able to assign the approprate group permission.
Balaji
Similar Messages
-
How to update list item using client object model without changing created/modified dates?
Hello All,
I want to update list item using the SharePoint Client Object
Model without updating the created / modified date. Is it possible?
Please help.
Thanks.Using the SystemUpdate method should do the trick, according
to its literature.
Additionally, would something like this be of any use for you? Taken from this
Stack Exchange thread: -
public static class SPListItemExtensions
/// <summary>
/// Provides ability to update list item without firing event receiver.
/// </summary>
/// <param name="item"></param>
/// <param name="doNotFireEvents">Disables firing event receiver while updating item.</param>
public static void Update(this SPListItem item, bool doNotFireEvents)
SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();
if (doNotFireEvents)
try
rh.DisableEventFiring();
item.Update();
finally
rh.EnableEventFiring();
else
item.Update();
/// <summary>
/// Provides ability to update list item without firing event receiver.
/// </summary>
/// <param name="item"></param>
/// <param name="incrementListItemVersion"></param>
/// <param name="doNotFireEvents">Disables firing event receiver while updating item.</param>
public static void SystemUpdate(this SPListItem item, bool incrementListItemVersion, bool doNotFireEvents)
SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();
if (doNotFireEvents)
try
rh.DisableEventFiring();
item.SystemUpdate(incrementListItemVersion);
finally
rh.EnableEventFiring();
else
item.SystemUpdate(incrementListItemVersion);
/// <summary>
/// Provides ability to update list item without firing event receiver.
/// </summary>
/// <param name="item"></param>
/// <param name="doNotFireEvents">Disables firing event receiver while updating item.</param>
public static void SystemUpdate(this SPListItem item, bool doNotFireEvents)
SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();
if (doNotFireEvents)
try
rh.DisableEventFiring();
item.SystemUpdate();
finally
rh.EnableEventFiring();
else
item.SystemUpdate();
private class SPItemEventReceiverHandling : SPItemEventReceiver
public SPItemEventReceiverHandling() { }
new public void DisableEventFiring()
base.DisableEventFiring();
new public void EnableEventFiring()
base.EnableEventFiring();
Steven Andrews
SharePoint Business Analyst: LiveNation Entertainment
Blog: baron72.wordpress.com
Twitter: Follow @backpackerd00d
My Wiki Articles:
CodePlex Corner Series
Please remember to mark your question as "answered" if this solves (or helps) your problem. -
Unable to get the SharePoint 2013 List names using Client object model for the input URL
Please can you help with this issue.
We are not able to get the SharePoint 2013 List names using Client object model for the input URL.
What we need is to use default credentials to authenticate user to get only those list which he has access to.
clientContext.Credentials = Net.CredentialCache.DefaultCredentials
But in this case we are getting error saying ‘The remote server returned an error: (401) Unauthorized.’
Instead of passing Default Credentials, if we pass the User credentials using:
clientContext.Credentials = New Net.NetworkCredential("Administrator", "password", "contoso")
It authenticates the user and works fine. Since we are developing a web part, it would not be possible to pass the user credentials. Also, the sample source code works perfectly fine on the SharePoint 2010 environment. We need to get the same functionality
working for SharePoint 2013.
We are also facing the same issue while authenticating PSI(Project Server Interface) Web services for Project Server 2013.
Can you please let us know how we can overcome the above issue? Please let us know if you need any further information from our end on the same.
Sample code is here: http://www.projectsolution.com/Data/Support/MS/SharePointTestApplication.zip
Regards, PJ Mistry (Email: [email protected] | Web: http://www.projectsolution.co.uk | Blog: EPMGuy.com)Hi Mistry,
I sure that CSOM will authenticate without passing the
"clientContext.Credentials = Net.CredentialCache.DefaultCredentials" by default. It will take the current login user credentials by default. For more details about the CSOM operations refer the below link.
http://msdn.microsoft.com/en-us/library/office/fp179912.aspx
-- Vadivelu B Life with SharePoint -
Hi,
I want to fetch the list of users who all are having full access to the sharepoint list using client object model with .Net
Please let me know if any property for the user object or any other way to get it.
Thanks in advance.Here you are complete code i created from some years it lists all groups and users, you can just add a check in the permissions loop to see if it is equal to Full Control.
Private void GetData(object obj)
MyArgs args = obj as MyArgs;
try
if (args == null)
return; // called without parameters or invalid type
using (ClientContext clientContext = new ClientContext(args.URL))
// clientContext.AuthenticationMode = ClientAuthenticationMode.;
NetworkCredential credentials = new NetworkCredential(args.UserName, args.Password, args.Domain);
clientContext.Credentials = credentials;
RoleAssignmentCollection roles = clientContext.Web.RoleAssignments;
ListViewItem lvi;
ListViewItem.ListViewSubItem lvsi;
ListViewItem lvigroup;
ListViewItem.ListViewSubItem lvsigroup;
clientContext.Load(roles);
clientContext.ExecuteQuery();
foreach (RoleAssignment orole in roles)
clientContext.Load(orole.Member);
clientContext.ExecuteQuery();
//name
//MessageBox.Show(orole.Member.LoginName);
lvi = new ListViewItem();
lvi.Text = orole.Member.LoginName;
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = orole.Member.PrincipalType.ToString();
lvi.SubItems.Add(lvsi);
//get the type group or user
// MessageBox.Show(orole.Member.PrincipalType.ToString());
if (orole.Member.PrincipalType.ToString() == "SharePointGroup")
lvigroup = new ListViewItem();
lvigroup.Text = orole.Member.LoginName;
// args.GroupsList.Items.Add(lvigroup);
DoUpdate1(lvigroup);
Group group = clientContext.Web.SiteGroups.GetById(orole.Member.Id);
UserCollection collUser = group.Users;
clientContext.Load(collUser);
clientContext.ExecuteQuery();
foreach (User oUser in collUser)
lvigroup = new ListViewItem();
lvigroup.Text = "";
lvsigroup = new ListViewItem.ListViewSubItem();
lvsigroup.Text = oUser.LoginName;
lvigroup.SubItems.Add(lvsigroup);
//args.GroupsList.Items.Add(lvigroup);
DoUpdate1(lvigroup);
// MessageBox.Show(oUser.LoginName);
RoleDefinitionBindingCollection roleDefsbindings = null;
roleDefsbindings = orole.RoleDefinitionBindings;
clientContext.Load(roleDefsbindings);
clientContext.ExecuteQuery();
//permission level
lvsi = new ListViewItem.ListViewSubItem();
string permissionsstr = string.Empty;
for (int i = 0; i < roleDefsbindings.Count; i++)
if (i == roleDefsbindings.Count - 1)
permissionsstr = permissionsstr += roleDefsbindings[i].Name;
else
permissionsstr = permissionsstr += roleDefsbindings[i].Name + ", ";
lvsi.Text = permissionsstr;
lvi.SubItems.Add(lvsi);
// args.PermissionsList.Items.Add(lvi);
DoUpdate2(lvi);
catch (Exception ex)
MessageBox.Show(ex.Message);
finally
DoUpdate3();
Kind Regards, John Naguib Technical Consultant/Architect MCITP, MCPD, MCTS, MCT, TOGAF 9 Foundation -
How to Enable Ratings on SharePoint List using Client Object Model code for Office 365 SharePoint Site.
Thanks in Advance
Rajendra KHi Rajendra,
here you are the code and the blog, let me know if this helps
using (ClientContext ctx = new ClientContext(https://yourSiteUrl))
Web w = ctx.Web;
List l = w.Lists.GetByTitle("yourListName");
ctx.Load(l, info => info.Id);
ctx.ExecuteQuery();
string ListID = l.Id.ToString();
Microsoft.Office.Server.ReputationModel.Reputation.SetRating(ctx, ListID, 1, 5);
ctx.ExecuteQuery();
http://blogs.technet.com/b/speschka/archive/2013/07/08/how-to-use-csom-with-ratings-in-sharepoint-2013.aspx
Kind Regards, John Naguib Technical Consultant/Architect MCITP, MCPD, MCTS, MCT, TOGAF 9 Foundation -
Quering the database using Client Object Model
Hi,
I have to fetch the list items from a list named "Project Status" and display it in a table using
Client Object model.
The equivalent server side code is:
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["Project Status"];
DataTable dt1 = new DataTable();
try
if (list.ItemCount > 0)
DataColumn dc;
DataColumn dc1;
dc = new DataColumn("ProjectId", Type.GetType("System.String"));
dc1 = new DataColumn("Project Name", Type.GetType("System.String"));
dt1.Columns.Add(dc);
dt1.Columns.Add(dc1);
DataRow dr;
foreach (SPListItem item in list.Items)
dr = dt1.NewRow();
dr["ProjectId"] = item["ProjectId"];
dr["Project Name"] = item["Project Name"];
dt1.Rows.Add(dr);
Repeater1.DataSource = dt1;
Repeater1.DataBind();
catch (Exception Ex)
throw Ex;
1 more issue what i face is providing two links in the Visual WebPart and their navigate url is based on a condition that is fetched from the database. This corresponding code has to be converted to
Client Object Model.
string user = web.CurrentUser.LoginName;
string userID = user.Split(new char[] { '\\' })[1];
string connString = @"Data Source=NorthWind;Initial Catalog=EmployeeDB;User ID=sa;Password=Newuser123";
string query = "select * from EMPLOYEE_PROFILE";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
try
conn.Open();
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
a.Fill(t1);
DataRow[] dr = t1.Select("PsNo = '" + userID + "'"); //This will select all rows where the Name Column has current user
foreach (DataRow r in dr)
string bU = r["DeputedBU"].ToString();
if (bU == "INS" || bU == "BFS")
lnkPM.NavigateUrl = web.Site.WebApplication.Sites[0].Url + "/Dashboard.aspx";
lnkSummary.NavigateUrl = web.Site.WebApplication.Sites[0].Url + "/DashboardWithHyperlinks.aspx";
else
lnkPM.Visible = false;
lnkSummary.Visible = false;
catch (Exception)
throw;
finally
conn.Close();
Any help would be appreciated.Hi,
According to your post, there would be two questions in this single thread.
It is recommended to post one question in one single thread which will make others easier to focus on one question in one thread.
For the first question, you want to fetch list items and put into a DataTable object using Client Object Model.
To fetch list items from a list using Client Object Model, you can take a look at the code snippet below from MSDN:
http://msdn.microsoft.com/en-us/library/office/ee534956(v=office.14).aspx
For the second question, you might need to retrieve the User object and site collections object using Client Object Model.
However, if you can develop a Visual Web Part for your site, it means that you will be able to access the SharePoint Object Model which has more powerful APIs, so there is no
need to use Client Object Model in a Visual Web Part.
Best regards
Patrick Liang
TechNet Community Support -
I want to change 'Modified By' column value of a file that is being uploaded using Client Object Model in SharePoint 2013. The problem is that the version of the file is changing. Kindly help me. The code that I am using is:
using (System.IO.Stream fileStream = System.IO.File.OpenRead(m_strFilePath))
Microsoft.SharePoint.Client.File.SaveBinaryDirect(m_clientContext, str_URLOfFile, fileStream, true);
Microsoft.SharePoint.Client.File fileUploaded = m_List.RootFolder.Files.GetByUrl(str_URLOfFile);
m_clientContext.Load(fileUploaded);
m_clientContext.ExecuteQuery();
User user1 = m_Web.EnsureUser("User1");
User user2 = m_Web.EnsureUser("User2");
ListItem item = fileUploaded.ListItemAllFields;
fileUploaded.CheckOut();
item["UserDefinedColumn"] = "UserDefinedValue1";
item["Title"] = "UserDefinedValue2";
item["Editor"] = user1;
item["Author"] = user2;
item.Update();
fileUploaded.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
m_clientContext.ExecuteQuery();Hi talib2608,
Chris is correct for this issue, when calling update using ListItem.update method, it will increase item versions, using SystemUpdate and UpdateOverwriteVersion will update the list item overwrite version.
these two methods are not available in CSOM/REST, only server object model is available for this.
Thanks,
Qiao Wei
TechNet Community Support -
Setting the default value to taxonomy column in sharepoint 2010 using client object model
I am creating a metadata column and I want to set its default value in sharepoint 2010 using client object model. Can anyone help me?
My code for creating metadata column is as below:
ClientContext clientContext = new ClientContext(siteUrl);
Web site = clientContext.Web;
List list = site.Lists.GetByTitle("LibraryName");
FieldCollection collField = list.Fields;
string fieldSchema = "<Field Type='TaxonomyFieldType' DisplayName='SoftwareColumn' Name='SoftwareColumn' />";
collField.AddFieldAsXml(fieldSchema, true, AddFieldOptions.DefaultValue);
//oneField.DefaultValue = "ASP.NET|4c984b91-b308-4884-b1f1-aee5d7ed58b2"; // wssId[0].ToString() + ";#" + term.Name + "|" + term.Id.ToString().ToLower();
clientContext.Load(collField);
clientContext.ExecuteQuery();Hi,
Please try the code like this:
ClientContext clientContext = new ClientContext("http://yoursite/");
List list = clientContext.Web.Lists.GetByTitle("List1_mmsfield");
clientContext.Load(list);
clientContext.ExecuteQuery();
FieldCollection fields = list.Fields;
clientContext.Load(fields);
clientContext.ExecuteQuery();
Field f = fields.GetByTitle("mms");
clientContext.Load(f);
clientContext.ExecuteQuery();
Console.WriteLine(f.Title + "---" + f.DefaultValue);
//2;#A2|a0a95267-b758-4e4d-8c39-067069fd2eef
//1;#A1|641f5726-992c-41c8-9ddc-204a60b88584
f.DefaultValue = "1;#A1|641f5726-992c-41c8-9ddc-204a60b88584";
f.Update();
clientContext.Load(f);
clientContext.ExecuteQuery();
Console.WriteLine(f.Title + "---" + f.DefaultValue);
Best regards
Patrick Liang
TechNet Community Support -
Updation of List Settings through Client object model
Hi all,Is there any way to update List settings through Client object model.
I want to work with all the list settings programmaticaly using client object model.
Is there any way???Hi,
Handful operations you can do it with client object model as certain limitations are there, which are not in server object model. Sharepoint Client obejct model comes with 3 APIs .i.e .Net managed code, javascript api and silverlight
object model .
For reference , i implemented test code to add list on the Quick launch.
ClientContext clientContext = new ClientContext("Web FullUrl");
Web web = clientContext.Web;
List list = web.Lists.GetByTitle("Test");
list.OnQuickLaunch = true;
list.Update();
clientContext.Load(list);
clientContext.ExecuteQuery();
Regards,
Milan Chauhan
LinkedIn
|
Twitter | Blog
| Email -
How to activate Custom Feature in SharePoint 2010 using Client Object model
I am trying to Activate a custom feature using Client Object Model in SharePoint 2010. Here is the code I used. When I execute the code, I got the error "Feature with Id 'xx' is not installed in this farm, and cannot be added to this scope while
creating site collection". Can anyone help?
ClientContext clientContext = new ClientContext(spURL);
//GUID of the custom feature
Guid districtFeatureId = new Guid("5b3529de-5045-46da-af87-8d2e32c121a7");
Site clientSite = clientContext.Site;
FeatureCollection clientSiteFeatures = clientSite.Features;
clientContext.Load(clientSiteFeatures);
clientContext.ExecuteQuery();
//Activate the feature
clientSiteFeatures.Add(districtFeatureId, false, FeatureDefinitionScope.Site);
clientContext.ExecuteQuery();Hi shil chan,
When you activate a feature on the site collection, the feature should be scoped to site or farm, the error message shows it cannot find the specific feature, this will happen when you have a feature in web
scope or the feature isn’t installed.
So, to troubleshooting this issue:
Verify whether the feature is scoped to web. Please go to
Site Setting->Site Features . If the feature is a web scope feature, then add the feature to webfeatures.
Make sure the feature is installed correctly.
Please inform me freely if you have any questions.
Thanks -
Not able to use Client Object Model in Visual Webpart SandBox Solution?
Hi,
I am trying to use client object model in visual webpart in sandbox solution but i am getting unexpected error but if i remove client object model code webpart works fine?
any help is appreciated.
Regards,
Gaurav VermaCheck this article for your answer
How to leverage the Client Object Model in a Sandbox Visual Web Part
Mark ANSWER if this reply resolves your query, If helpful then VOTE HELPFUL
INSQLSERVER.COM
Mohammad Nizamuddin -
Parsing Query string using Client Object model [ECMA]
hello
i want to access querystring using client object model using ECMA script.
for eg http://localhost:80/demopage.aspx?test=123
can we read value of test using ECMA script
regards
Manishthanks ...
i did that...using
<script type="text/javascript">
function queryString(parameter) {
var loc = location.search.substring(1, location.search.length);
var param_value = false;
var params = loc.split("&");
for (i=0; i<params.length;i++) {
param_name = params[i].substring(0,params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=')+1)
if (param_value) {
return param_value;
else {
return false; //Here determine return if no parameter is found -
Delete site collection using Client object model
Is it possible to delete a site collection using Client object model?
-PrashantI don't think you can create or delete a site-collection using SharePoint Client Object Model. You'd need to leverage admin web services (
http://Site/_vti_adm/Admin.asmx) (or) server-side object model (or) powershell for this task.
Please mark the replies as answers if they help or unmark if not. -
To extract the users permission on files and folders in sharepoint 2010 using client object model
To extract the users permission on files and folders in sharepoint 2010 using client object model
Hello,
This is sample code to get item level permisison: (Just written in notepad so it is not tested)
public void ItemLevelPermission()
SecurableObject curObj = null;
ListItem curItem = ctx.Web.Lists.GetByTitle("LibraryName").GetItemById(ItemId); -> Use Id of file or folder.
IEnumerable roles = null;
roles = ctx.LoadQuery(
curObj.RoleAssignments.Include(
roleAsg => roleAsg.Member,
roleAsg => roleAsg.RoleDefinitionBindings.Include(
roleDef => roleDef.Name, // for each role definition, include roleDef’s Name
roleDef => roleDef.Description)));
ctx.ExecuteQuery();
Hope it could help
Hemendra:Yesterday is just a memory,Tomorrow we may never see
Please remember to mark the replies as answers if they help and unmark them if they provide no help -
Assigning External content type field column value using Client Object Model
I have a problem assinging External column value to ListItem object with client object model-based application I'm developing. To be precise, I am able to retrieve data related to external content type by reading external list created from this content type
but I don't know how to properly use it to assign value to this field. By doing some research on my own I concluded that BDC ID column from external list is the way to go since it uniquely defines selected row from external list but that doesn't
tell me much since I don't know what to do with it. Currently I ended up with partial solution - to assign plain string value of picker column but that makes this value visible only in "View Properties" option on Sharepoint and not in "Edit Properties"
which pritty much makes sence since it isn't properly related to rest of the data in specific row. Does someone have a better solution for this?
Igor S.I think I understand your problem.
In my example I have an external data column "Beneficiary Name", using a Beneficiary external content type (accessing a table of beneficiaries in a SQL table).
I want to set the "Beneficiary Name" property using the client object model. I know the name of the beneficiary but not the ID value.
It is a fairly simple solution. You just need to identify the name of the property SharePoint assigns to the ID field, in my case it is called "Beneficiary_ID". Then set the two properties as follows:
thisItem["Beneficiary_Name"] = "Charitable Trust";
thisItem["Beneficiary_ID"] = -1;
thisItem.Update();
Setting the ID property to -1 causes the server to do an automatic lookup for the ID from the value assigned to the item.
Maybe you are looking for
-
How to do autoprovisioning to a custom connector based on jobcodes?
Hi, I have developed a custom connector which has 50 job codes. Based on the job codes we need to do autoprovisioning. How this is possible? do we need to create rule for each job? Thanks in advance
-
Is there a way to view the calendar with the All Day Events and regular meetings within a portrait view. Thanks, BKLYN215
-
I'm looking to get a new macbook pro but I need to know if it will work oversea's. Is there wireless internet in Kusami, Ghana for instance? Or will my Modem adaptor work over there? How about the world traveler AC adapters, I know it doesnt specific
-
Formatting in an interactive PDF
Hi, I have a form that has a section that needs to be able to go into auto numbering/sub bullets,etc as needed (like an outline format). Is this possible? Also, within that same section, there are cases where the user wants to copy from a Word docum
-
Does the N96 support 32GB microSD card?
Can this phone support SDHC cards with >8GB of space? If not do you know of a phone that does have large capacity (or upgradable) for music, and supports tethering in addiiton?