Enable ratings in SharePoint with PowerShell and CSOM

In document libraries it is possible to enable ratings, both likes and average score (1-5). In this article I will cover how to enable “Likes” on the Pages library in a publishing site.

When configuring libraries manually, this is enabled from the “Rating settings” in the library:

enableratings

But when we follow the remote provisioning pattern to create new sites by using PowerShell and CSOM, there is currently no available function in the API for this. This pattern is the recommenced approach when working with SharePoint Online or SharePoint 2013/2016 without access to server side PowerShell or code.

To understand what is required to programmatic enable ratings I had to, as always with SharePoint, inspect the code behind with a reflection tool like DotPeek.

How to enable likes ratings

This show the procedure to enable ratings with Likes on a Pages library. To enable “Star rating” (1-5 average) this would be similar, but not covered in this post.

  1. Add the required fields to the library
    FieldName Guid
    AverageRating 5a14d1ab-1513-48c7-97b3-657a5ba6c742
    RatingCount b1996002-9167-45e5-a4df-b2c41c6723c7
    RatedBy 4D64B067-08C3-43DC-A87B-8B8E01673313
    Ratings 434F51FB-FFD2-4A0E-A03B-CA3131AC67BA
    LikesCount 6E4D832B-F610-41a8-B3E0-239608EFDA41
    LikedBy 2CDCD5EB-846D-4f4d-9AAF-73E8E73C7312
  2. Add “LikesCount” to default view
  3.  Add “Ratings_VotingExperience” to RootFolder’s property bag

Use PowerShell to enable ratings

Note: This function requires the Office Dev PnP PowerShell library to be installed and loaded in the current PowerShell session. I recommend using this library for working with PowerShell and SharePoint (both Online and On-Premises).

Example: How to use this function with a site

Using this with subsites within the Site Collection would require some extension to the function, as the Fields always are loaded form the RootWeb, but the library reside in the subsite.

When we have run the “Enable-CustomLikesRatingsOnLibrary” function on the desired library, we can see that Likes now are available:

ratings-library

Summary

Using this function it is now possible to provision new sites with PowerShell and CSOM and enable likes rating on libraries.

Add AD security group as Site Collection administrator with PowerShell in SharePoint

In provisioning solutions it can be a good practice to add a security group from Active Directory as an additional site collection owner. Unfortunately a security group is not accepted as either primary or secondary owner. So to set a group as site collection administrator, the easiest approach I could find was to set the “IsSiteAdmin” property on the User object.

Exporting XsltListViewWebPart in SharePoint 2013

By default the XsltListViewWebPart does not support export from the web user interface. I often build solutions by configuring the web parts in the browers, exporting and adjusting the defintions and then deploying them with PowerShell. With a few lines of PowerShell this capability can also be enabled for the Xslt List View Web Part.

Before enabling the Export Mode on the webpart:

XsltListViewWebPart-before

After running the PowerShell script and enabling the Export mode:

XsltListViewWebPart-after

PowerShell script

Using BCS from PowerShell with SharePoint 2013

Running data migrations with SharePoint 2013 often involves using BCS and PowerShell if you don’t have and third party tools at hand. This can be a bit tricky to set up, but once you are familiar the the BCS configuration, the PowerShell scripts are mostly straight forward.

From my experience there are a few differences when running against BCS lists vs. regular lists. I have now been able to find a good guide for this, so from my own trial and error I wanted to share a few tips.

Get the context straight: Accessing the list gives a weird error

Running this:


$Web = Get-SPWeb "http://mybcsweb/"

$Web.GetList("/Lists/MyBcsDataList")

Gives this error:

format-default : The shim execution failed unexpectedly – Proxy creation failed. Default context not found..    + CategoryInfo          : NotSpecified: (:) [format-default], BdcException   + FullyQualifiedErrorId : Microsoft.BusinessData.Infrastructure.BdcException,Microsoft.PowerShell.Commands.FormatDefaultComman

bcs-powershell-sp2013-1

The fix:


$Site = Get-SPSite "http://mybcsweb"

$ServiceContext = Get-SPServiceContext -Site $Site # Required when working with BCS
$ServiceScope = New-Object Microsoft.SharePoint.SPServiceContextScope $ServiceContext # Required when working with BCS

$Web = $Site.RootWeb
$Web.GetList("/Lists/MyBcsDataList")

A bit more wiring is required to get the context straight for BCS to work.

Make sure you are running with administrator privileges

I use PowerShell ISE when creating and running these scripts. From time to time I accidently forget to start this with Administrator privileges. This can fool you into weird errors like this one. Short minded one can try to start adding the missing assembly references, but the real reason is the missing privileges.

Running this:

$Web = Get-SPWeb "http://mybcsweb/"
$Web.GetList("/Lists/MyBcsDataList")

Gives this error:

format-default : The shim execution failed unexpectedly – Could not load file or assembly ‘System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ or one of its dependencies. Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542).    + CategoryInfo          : NotSpecified: (:) [format-default], BdcException  + FullyQualifiedErrorId : Microsoft.BusinessData.Infrastructure.BdcException,Microsoft.PowerShell.Commands.FormatDefaultCommand

bcs-powershell-sp2013-2

The fix:

Search for “PowerShell ISE”, right-click it and choose “Run as Administrator”.

bcs-powershell-sp2013-3

Include ViewFields in you CAML queries

Always remember to include the fields you are trying to query on in the “<Where>” statement within “<ViewFields>”. This isn’t required on regular lists, but to get any results in return, I experienced I was required to include them querying BCS lists.

Example of CAML query in PowerShell:


$Query= New-Object Microsoft.SharePoint.SPQuery 

$Query.ViewXml =
 "<View>
 <Method Name='Read List'/>
 <Query>
 <Where>
 <And>
 <Eq>
 <FieldRef Name='ProjectID' />
 <Value Type='Text'>100</Value>
 </Eq>
 <Eq>
 <FieldRef Name='Role' />
 <Value Type='Text'>Project Manager</Value>
 </Eq>
 </And>
 </Where>
 </Query>
 <ViewFields>
 <FieldRef Name='ProjectID'/>
 <FieldRef Name='Role'/>
 </ViewFields>
 </View>" 

 $Items = $List.GetItems($Query)

Summary

BCS has been around for a while and isn’t something very existing. But as mention in the introduction, using it for data migrations is very powerful, specially when you don’t have any 3. parts tools around. Doing this from PowerShell is pretty straight forward, but these three issues I experienced can be a headache if you get stuck with them. Hopefully this post can help others get quickly passed them!

Error: There is a compatibility range mismatch between the Web server and database

There is a compatibility range mismatch between the Web server and database “SP2013_Content_InsertDatabaseNameHere”, and connections to the data have been blocked to due to this incompatibility. This can happen when a content database has not been upgraded to be within the compatibility range of the Web server, or if the database has been upgraded to a higher level than the web server. The Web server and the database must be upgraded to the same version and build level to return to compatibility range.

error-after-sp1-upgrade

 

Cause

Discovered the error the first time I tried to upgrade a sandboxed solution within the selected database using PowerShell after upgrading to SP1. The error message appears the script output, Event Viewer and ULS. All databases had “No action required” as upgrade status, so this wasn’t the problem in my case. Hidden behind this error it appeared that insufficient database permissions was the cause.

Solution

It turned out that the logged in users’ permissions for this database had been lost after upgrading SharePoint 2013 from March PU to SP1 for some reason.

Fixed this was easy by adding the “SPDataAccess” role back to the user for the content database that was failing.

Adding comments, likes and follow from Yammer into you own SharePoint solutions

With the Yammer Embed API adding comments, likes and follow content is quite easy to achieve. Using this embed API has a great benefit as it is developed and maintained by Yammer, and will require very little effort to integrate. Features beyond the actions (like and follow) and the feed (comments) can be accomplished with either the REST or JavaScript API, but this will require more effort (reference: https://developer.yammer.com/yammer-sdks/). Integrating Yammer requires an external JavaScript file to be referenced, one or more placeholders (HTML div-tags) and local JavaScript function call to the API to initialize the integration.

Example of a news article based on a Page Layout in SharePoint Online with like, follow and comments from Yammer:

yammer-sp2013-onpremises-1

Embed API reference

</p>
<script type="text/javascript" src="https://assets.yammer.com/assets/platform_embed.js"></script></p>

Comments Feed

Comments can be made for many types of activities, in this example “page”. Yammer can maintain the relationship between the article and the feed either automatic by the URL in the browser, or it can be set explicit to ensure that the ID is unique. The first event on this article will trigger Yammer to create a activity page. This page can be enhanced with further metadata like a description and an image.

Example how this is displayed in SharePoint:

yammer-sp2013-onpremises-2

  Example how this is displayed in the  Yammer feed: yammer-sp2013-onpremises-3

Example on a activity page in Yammer:

yammer-sp2013-onpremises-4

Example code


<div id="yammer-page-feed" style="height:400px;width:500px;"></div>

<script>

yam.connect.embedFeed({

container: '#yammer-page-feed'

, network: 'o365.areflyen.no'

, feedType: 'open-graph'

, feedId: ''

, config: {

use_sso: true

, header: false

, footer: false

, showOpenGraphPreview: false

, defaultToCanonical: false

, hideNetworkName: false

, promptText: 'Comment on this article'




}

, objectProperties: {

url: ''

, type: 'page'

}

});

</script>

Like button

The practical effect of the “Like” action is limited. The button only shows the state for the current user (Like/Liked) and generates an activity. No total count of likes is available. When a user likes a page, it will also automatically be followed.

yammer-sp2013-onpremises-5

Example code


<div id="yammer-like"></div>

<script>

yam.connect.actionButton({

container: "#yammer-like",

network: "o365.areflyen.no",

action: "like"

});

</script>

Follow button

When following a page, you will subscribe to the activities on the current page. If you make a comment you will automatically follow the page.

yammer-sp2013-onpremises-6

Example code


<div id="yammer-like"></div>

<script>

yam.connect.actionButton({

container: "#yammer-follow",

network: "o365.areflyen.no",

action: "follow"

});

</script>

Summary

Yammer gives us easy to use API to make the switch from SharePoint Social to Yammer possible. Even if these examples are demonstrated in SharePoint Online, the same solution can be applied to On-Premises. Gaining the best user experience On-Premises will be by implementing a Single Sign-On (SSO) solution between you local network and Yammer. Disclaimer: Both SharePoint and Yammer is in continuous development, and the API and user interface shown in the screenshots have changed from the time this post was written.