Friday, 21 April 2017

How to Expose Sharepoint Rating Feature as Service

Problem Statement:

Recently, I came across a situation where SharePoint List was used as the repository and application was built in other technologies. We wanted to expose SharePoint Rating feature as service and we encountered that rating was done in the context of the service account/App pool account contrary to it should be in current user’s context.


We exposed the Web API service as Provider hosted App and consumed Token Helper’s  GetS2SClientContextWithWindowsIdentity  method to create client context.

Code Snippet:

        public string SetRating([FromBody]RatingDetails folderDetails)
               //Site Collection/Web URL
                Uri hostWeb = new Uri(“”);

                //Item Id for which user want’s to rate     
                int itemID = Convert.ToInt32(folderDetails.ItemId);
                int rating = Convert.ToInt32(folderDetails.Rating);

  using (var clientContext =   TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb,   HttpContext.Current.Request.LogonUserIdentity))
                    clientContext.Load(clientContext.Web, web => web.Title);
                    Web w = clientContext.Web;
                    clientContext.Load(w, cw => cw.CurrentUser);
                    List curentList = w.Lists.GetByTitle("MyListName");
                    clientContext.Load(curentList, cl => cl.Id);
                    string ListID = curentList.Id.ToString();
                    Reputation.SetRating(clientContext, ListID, itemID, rating);

                    ListItem ratedItem = curentList.GetItemById(itemID);
                    clientContext.Load(ratedItem, item => item.Id, item =>                                       item["AverageRating"], item => item["RatingCount"], item =>                                   item["Ratings"]);
                    return Convert.ToString(ratedItem["AverageRating"]);

            catch (Exception ex)
                return ex.Message;

Web Config Changes:

key="ClientId" value="689c2335-715b-4c50-969b-2d19f520adf7"
key="ClientSigningCertificatePath" value="D:\Cert\HighTrustCertOS.pfx"
key="ClientSigningCertificatePassword" value="Password123"

key="IssuerId" value="b7e4be28-8baa-4c18-83c9-73130305cb7a"

Note: You have to give permission on the SharePoint Site Collection for this App


No comments:

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...