1

Is it possible to programmatically add a comment to a SharePoint Online modern site page using Office Dev PnP? I am not able to find any resources on this.

  • you want add a comment via javascript or CSOM C# ? – Gautam Sheth Sep 12 '18 at 7:23
  • I want to add the comment using CSOM C# – Gabriel Sep 12 '18 at 7:49
0

AFAIK, there is no native CSOM method as yet using which we can add a comment. Since PnP is a wrapper which extends CSOM, it also doesnt have a method of add comment to the Modern Site Page.

Secondly, the comments are stored in an external data store. So, its not stored as property or hidden column of the Site page. So, normal CRUD operations on List Items wont work.

But we do have a REST endpoint, using which we can post comment. Now, the challenge is to use that endpoint in CSOM. Based on the implementation done in @pnp/sp package which is the new pnpjs library, we can post a comment on the modern site page in CSOM C#.

You can take a look at the below implementation and modify it as per your environment:

string siteUrl = "https://tenant.sharepoint.com/sites/test";
string userName = "user.name@tenant.onmicrosoft.com";
string password = "password";

using (ClientContext clientContext = new ClientContext(siteUrl))
{
    SecureString securePassword = new SecureString();
    foreach (char c in password.ToCharArray())
    {
        securePassword.AppendChar(c);
    }

    clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
    clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);
    var credentials = new SharePointOnlineCredentials(userName, securePassword);

    var uri = new Uri(siteUrl);

    var authCookie = credentials.GetAuthenticationCookie(uri);
    var cookieContainer = new CookieContainer();
    cookieContainer.SetCookies(uri, authCookie);

    HttpClientHandler clientHandler = new HttpClientHandler();
    clientHandler.CookieContainer = cookieContainer;

    using (HttpClient client = new HttpClient(clientHandler))
    {
        client.BaseAddress = uri;
        client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

        var requestDigestEndPoint = $"{uri}/_api/contextinfo";      

        // Make POST call to get the request digest
        var requestDigestResponse = client.PostAsync(requestDigestEndPoint, null).Result;

        if (requestDigestResponse.IsSuccessStatusCode)
        {
            var requestDigestResponseContent = requestDigestResponse.Content.ReadAsStringAsync().Result;

            var requestDigestJson = JObject.Parse(requestDigestResponseContent);

            // read the request digest value and then use it to post a comment
            var digestValue = requestDigestJson["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();

            // your Modern Site Pages list  
            var listTitle = "Site Pages";

            // the comment to be created, i.e JSON body
            var commentPayload = new { __metadata = new { type = "Microsoft.SharePoint.Comments.comment" }, text = "Added via CSOM" /* actual comments content */ };

            // get the Modern Sitepage
            var modernPage = clientContext.Web.LoadClientSidePage("ModernSitePage.aspx");

            // ID of the page 
            var itemId = modernPage.PageListItem.Id;            

            // endpoint of the page where you want to post comment
            var commentEndpoint = $"{uri}/_api/web/lists/getByTitle('{listTitle}')/items({itemId})/Comments";

            var commentRequest = new StringContent(JsonConvert.SerializeObject(commentPayload));
            commentRequest.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            commentRequest.Headers.Add("X-RequestDigest", digestValue);

            var data = client.PostAsync(commentEndpoint, commentRequest).Result;

            Console.WriteLine("comment created");
        }
    }
}

The above code first gets the RequestDigest of the site and then using that we are creating a comment. Have added comments in the code, let me know if you need more details.

Reference - @pnp/sp Comments Implementation

Necessary reading - Vardhaman's blog on working with Modern Page comments

Packages used - NewtonSoft.JSON, NewtonSoft.JSON.Linq and Office Dev PnP Core

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.