Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharepoint Client Object Model setting ModifiedBy field

I am trying to update the "ModifiedBy" field in a Sharepoint discussion board using the Client Object Model. By changing the "Editor" and "Author" fields, I can change the "ModifiedBy" that appears on the list view. However, once you click on a discussion post, the "ModifiedBy" field that appears there (the one with the picture above it) does not reflect the changes. After experimenting, I discovered that the field I need to change to correct this is called "MyEditor". Unfortunately, this field is read-only.

In the code below, I try to change the read-only settings of the field to false. When I look at the MyEditor field in Visual Studio's debugger after the ExecuteQuery() line at the bottom of the first block, it shows that the ReadOnlyField value has in fact been set to false.

        sharepointContext.Load(discussionList);
        sharepointContext.ExecuteQuery();
        var fields = discussionList.Fields;
        sharepointContext.Load(fields);
        sharepointContext.ExecuteQuery();
        var field = fields.GetByInternalNameOrTitle("MyEditor");
        field.ReadOnlyField = false;
        field.Update();
        sharepointContext.Load(field);
        sharepointContext.ExecuteQuery();

The code above executes with no problems. The problem comes with this next block:

        //...Code to initialize discussionItem...
        discussionItem["MyEditor"] = 0;
        discussionItem["Editor"] = 0;
        discussionItem["Author"] = 0;
        discussionItem["Body"] = "Testing";
        discussionItem["Title"] = "Hello Worlds";
        discussionItem.Update();
        sharepointContext.Load(discussionItem);
        sharepointContext.ExecuteQuery();

When the code reaches the ExecuteQuery() at the bottom of the second block, it throws a ServerException with the following message:

        Invalid data has been used to update the list item. 
        The field you are trying to update may be read only.

To make sure that the MyEditor field was the one causing the exception to be thrown, I commented out the line where I set it and ran the code again. Everything worked fine. I don't understand what is wrong, can someone help me?

like image 941
nckbrzg Avatar asked Oct 08 '22 05:10

nckbrzg


1 Answers

In case someone needs to find the user by name, it goes like this:

    private static FieldUserValue GetUser(ClientContext clientContext, string userName)
    {
        var userValue = new FieldUserValue();
        var newUser = clientContext.Web.EnsureUser(userName);
        clientContext.Load(newUser);
        clientContext.ExecuteQuery();
        userValue.LookupId = newUser.Id;
        return userValue;
    }

The returned value can be set via item["Author"]

like image 121
Pawel Gorczynski Avatar answered Oct 12 '22 00:10

Pawel Gorczynski