In this article, let us see, how to LIKE a Document in SharePoint Office 365 Programmatically by C# CSOM.
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
namespace Office365.Console
{
class Program
{
static void Main(string[] args)
{
LikeADocument();
}
public static void LikeADocument()
{
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
//Site URL
string siteUrl = "https://******.sharepoint.com/sites/communitysite";
// UserName
string userName = "sathish@******.onmicrosoft.com";
//Password
string password = "******";
using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
try
{
Site site = clientContext.Site;
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.Load(web.Lists);
clientContext.ExecuteQuery();
//Get the Tasks List
List list = web.Lists.GetByTitle("MyDocumentsLibrary");
//Get the Child Item - The IDs were Hard coded for the demo purpose
ListItem listItem = list.GetItemById(20);
clientContext.Load(listItem);
clientContext.ExecuteQuery();
List<FieldUserValue> newLikedBy = new List<FieldUserValue>();
FieldUserValue uservalue = new FieldUserValue();
var Likeduser = web.EnsureUser("sathish@******.onmicrosoft.com");
clientContext.Load(Likeduser);
clientContext.ExecuteQuery();
if (Likeduser != null)
{
FieldUserValue userValue = FieldUserValue.FromUser(Likeduser.Title);
userValue.LookupId = Likeduser.Id;
if (!string.IsNullOrEmpty(userValue.LookupValue))
{
newLikedBy.Add(userValue); // We can add a lot of Users in this Generic List in a single shot.
// I have added only one User for the demo purpose.
}
}
if (newLikedBy.Count > 0)
{
listItem["LikesCount"] = newLikedBy.Count;
listItem["LikedBy"] = newLikedBy;
}
listItem.Update();
clientContext.ExecuteQuery();
}
catch (Exception ex)
{
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("Exception Occured : " + ex.Message);
System.IO.File.AppendAllText("C:\Temp\Exception.txt", ex.Message + " - " + siteUrl + Environment.NewLine);
}
}
System.Console.WriteLine("Completed....");
System.Console.WriteLine("Press Any Key to Exit ....");
System.Console.ReadLine();
}
}
}
The Output will be something like
Happy Coding,
Sathish Nadarajan.
Leave a comment