How to Get/Set Ratings in SharePoint Office 365 Item Programmatically using Client Side Object Model (CSOM)

Sathish Nadarajan
 
Solution Architect
August 28, 2016
 
Rate this article
 
Views
6876

In the earlier article, we saw how to enable Rating in Office 365 environment. In this article, as a continuation, we need to set the rating or get the rating value of an Item using CSOM. i.e., I am going to Like or UnLike an Item in the document library using CSOM. Again, these piece of codes are very straight forward and as part of a bigger requirement, these are small function points, which I used to create it as a separate console and integrate later to the actual project code.

Basically, the operations I am performing is as follows.

1. Get the List Item

2. Get the Current Liked Users

3. Get the Current Liked Count

4. Increment the Count

5. Add the new users to the existing list.

6. Update the list Item with new values.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 
 using Microsoft.SharePoint.Client;
 using System.Security;
 using Microsoft.Online.SharePoint.TenantAdministration;
 
 namespace Console.Office365
 {
     class Program
     {
         static void Main(string[] args)
         {
             LikeUnLikeCSOM();
         }
 
 
         public static void LikeUnLikeCSOM()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://*******.sharepoint.com/sites/DeveloperSite/";
             string userName = "Sathish@*****.onmicrosoft.com";
             string password = "***********";
             string listTitle = "MyDocLib";
 
             using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 ctx.Load(ctx.Web);
                 ctx.ExecuteQuery();
 
                 List filesLibrary = null;
 
                 filesLibrary = ctx.Web.GetListByTitle(listTitle);
 
                 ctx.Load(filesLibrary);
                 ctx.ExecuteQuery();
 
                 ListItem item = filesLibrary.GetItemById(1);
 
                 ctx.Load(item);
                 ctx.ExecuteQuery();
 
                 List<FieldUserValue> newLikedBy = new List<FieldUserValue>();
 
                 var likedBy = item["LikedBy"] as FieldUserValue[];
 
                 if (likedBy != null)
                 {
                     foreach (var liked in likedBy)
                     {
                         newLikedBy.Add(liked);
                     }
                 }
                 newLikedBy.Add(FieldUserValue.FromUser("sathish@sppalsmvp.onmicrosoft.com"));
 
                 item["LikedBy"] = newLikedBy;
                 item["LikesCount"] = Convert.ToInt32(item["LikesCount"]) + 1;
                 item.Update();
 
                 ctx.Load(item);
                 ctx.ExecuteQuery();
  
             }
         }
     }
     
 }
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

“EnsureScriptFunc is Undefined” – How to Handle Javascript this exception in SharePoint 2013.

Sathish Nadarajan
 
Solution Architect
November 28, 2013
 
Rate this article
 
Views
22148

Some time back, we saw how to do the SetRating using the Reputation.js File here. As a Recap, let us have a look into the code snippet.

 function SetRating() {
 
         itemID = 4;
 listID = “0F4BA645-5753-4526-A978-6BF2C0A2E654”
 RatingValue = 1;
 
         EnsureScriptFunc('reputation.js',
                 'Microsoft.Office.Server.ReputationModel.Reputation',
                 function () {
                     var ctx = new SP.ClientContext(“http://sathishserver:20000/sites/PublishingSite/”);
                     rating = Microsoft.Office.Server.ReputationModel.Reputation.setRating(ctx, listID, itemID, RatingValue);
 
                     ctx.executeQueryAsync(Function.createDelegate(this, this.RatingSuccess), Function.createDelegate(this, this.RatingFailure));
                 });
 
     }
 

On the above method, you can see a function named EnsureScriptFunc. When I added this in to a Script editor Web Part on any of the Site Pages, it worked perfectly. But, in one of our scenario, we were not using any of the MasterPages. The requirement is something like, we need to create an application page, that should not contain the default master page. Moreover, it should not contain any master page. We did that. Am planning to describe about that some time later.

On the blank Application Page, I wrote this method and deployed. When I was trying to do the actual rating, I was getting an exception like “EnsureScriptFunc is undefined”. While surfing, I could not find enough information regarding this. As a last option, I tried to find it out myself J.

By using the IE Developer tool, opened all the script files loaded along with the master page and searched for the Keyword EnsureScriptFunc. Atlast I found this on the Init.debug.JS. After adding that to the blank application page, it started working.

Hence, the conclusion here is, EnsureScriptFunc is declared in the Init.Debug.JS file. If we experience the exception again, we need to check for the Init.Debug.JS.

Happy Coding.

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

SetRating in Reputation Class in SharePoint 2013 using Javascript and C# CSOM

Sathish Nadarajan
 
Solution Architect
November 16, 2013
 
Rate this article
 
Views
25844

Some time back, we saw how to do the SetRating using the SocialRatingManager class here. But it requires modifications on the List Permission Settings, and moreover it has a dependency of the Social Rating Synchronization timer Job. Now, let us see an alternative option for this. By using the Class Reputation on the namespace Microsoft.Office.Server.ReputationModel, we can achieve this. Let us see, how easy this is.

First let us see, how to use this class in C#. The biggest advantage of this class is, this is part of our CSOM functionality. Hence, there is no dependency on the Microsoft.SharePoint.dll.

Implementing SetRating by Reputation on C# CSOM.

try

{

// Get the Client Context

using (ClientContext ctx = new ClientContext("http://sathishserver:20000/sites/VHS/"))

{

//Get the Web Object

Web w = ctx.Web;

List l = w.Lists.GetByTitle("SocialRating");

ctx.Load(l, info => info.Id);

ctx.ExecuteQuery();

string ListID = l.Id.ToString();

int ItemID = 2;

int RatingValue = 4;

//Call the SetRating methohd

Microsoft.Office.Server.ReputationModel.Reputation.SetRating(ctx, ListID, ItemID, RatingValue);

ctx.ExecuteQuery();

}

}

catch (Exception ex)

{

}

 try
             {
 // Get the Client Context
                 using (ClientContext ctx = new ClientContext("http://sathishserver:20000/sites/VHS/"))
                 {
 //Get the Web Object
                     Web w = ctx.Web;
                     List l = w.Lists.GetByTitle("SocialRating");
                     ctx.Load(l, info => info.Id);
                     ctx.ExecuteQuery();
 
 
 
                     string ListID = l.Id.ToString();
                     int ItemID = 2;
                     int RatingValue = 4;
 //Call the SetRating methohd
                     Microsoft.Office.Server.ReputationModel.Reputation.SetRating(ctx, ListID, ItemID, RatingValue);
                     ctx.ExecuteQuery();
                 }
             }
             catch (Exception ex)
             {
  
             }
 

The code snippet is somewhat straight forward. Only thing, is the parameters for SetRating method. Even the method is not overloaded. Only 4 parameters are required.

Ctx – Client Context

ListID – String (GUID of the List)

Item ID – Int (List Item ID)

RatingValue – Int (Value ranging from 0 to 5)

 

Implementing SetRating by Reputation on Javascript.

Nowadays javascripts become more powerful. Through which we are able to call any method, access any objects from any dll. Let us see, how we can use Javascript for calling the SetRating method and how we are utilizing them.

 

 function SetRating() {
 
         itemID = 4;
 listID = “0F4BA645-5753-4526-A978-6BF2C0A2E654”
 RatingValue = 1;
 
         EnsureScriptFunc('reputation.js',
                 'Microsoft.Office.Server.ReputationModel.Reputation',
                 function () {
                     var ctx = new SP.ClientContext(“http://sathishserver:20000/sites/PublishingSite/”);
                     rating = Microsoft.Office.Server.ReputationModel.Reputation.setRating(ctx, listID, itemID, RatingValue);
 
                     ctx.executeQueryAsync(Function.createDelegate(this, this.RatingSuccess), Function.createDelegate(this, this.RatingFailure));
                 });
 
     }
 
 
     function RatingSuccess(sender, args) {
         alert('Rating Done Successfully');
     }
 
 
 
     function RatingFailure(sender, args) {
         alert(‘SetRating failed:' + args.get_message());
     }
 

But there is no other straight forward method to fetch the Rating. For that, we need to go with the normal list item itself. Let us see that how to fetch from Javascript.

 function GetRating(sender, args) {
 
                
         var ctx = new SP.ClientContext(“http://sathishserver:20000/sites/VHS/”);
         var web = ctx.get_web();
         this.list = web.get_lists().getByTitle(ListName);
         this.listItems = list.getItemsByID(ItemID);
 
         ctx.load(listItems, 'Include(ID, AverageRating)');
         ctx.executeQueryAsync(Function.createDelegate(this, GetRatingSuccess), Function.createDelegate(this, GetRatingFailure));
 
     }
 
 function GetRatingSuccess (sender, args) {
 
         RatingValue = listItems.itemAt(0).get_item("AverageRating");
         
 
     }
 
     function GetRatingFailure (sender, args) {
 
         alert(‘GetRating():' + args.get_message());
 
     }
 
 

 

In the same manner, by C# also, there is no direct method. We need to use the client context to fetch the item and the property “AverageRating” will give you the Rating Value.

That’s all. It is very simple when comparing with the SocialRating Manager.

 

Happy Coding..

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment