Search code examples
c#sharepointsharepoint-clientobject

Client Object Model, cannot find site user?


I am getting ServerException when running the program. Here is my code:

 ClientContext context = new ClientContext("http://myRUL");
 Principal user = context.Web.SiteUsers.GetByLoginName(@"myRealAccoutLoginIn");
 RoleDefinition readDef = context.Web.RoleDefinitions.GetByName("Approve");//"Approve" is the permission I want to give to the user

 RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(context);
            roleDefCollection.Add(readDef);
 RoleAssignment newRoleAssignment = context.Web.RoleAssignments.Add(user, roleDefCollection);

 context.ExecuteQuery(); 

Here is enter image description herethe detail exception:

And I can assure you the SiteUsers exist from the website, the red circle from the below image is my sharepoint accout: enter image description here


Solution

  • Web.SiteUsers doesn`t exist in SharePoint 2010 and is not recomended in SharePoint 2013.

    Try using Web.EnsureUser("<username>") (documentation) to get the Principal.