Back to Insights

Enabing SharePoint 2010 list rating programatically

If you're reading this post you probably already know about SharePoint 2010's rating functionality and how to enable it through the GUI. In this post I discuss enabling ratings on a list using a SharePoint 2010 Feature which can be automatically activated in your deployment script. This approach will greatly reduce manual configuration steps for your clients as well as configuration in multiple other (QA / UAT) environments.

  1. Start by creating an empty SharePoint 2010 Solution in Visual Studio 2010 and add a new feature to it
  2. Add a feature receiver to your feature and uncomment the "FeatureActivated" section
  3. Paste the code below into your "FeatureActivated"
string listName = string.Empty;
string averageRatingId = string.Empty;
string ratingCountId = string.Empty;
try
            {
                // use any list name here that you want to enable rating on
                listName = "Posts";
                // those are reserved column IDs
                averageRatingId = "5a14d1ab-1513-48c7-97b3-657a5ba6c742"; 
                ratingCountId = "b1996002-9167-45e5-a4df-b2c41c6723c7";
                SPList list = ((SPWeb)properties.Feature.Parent).Lists[listName];
              
                SPField fieldByField = GetFieldById(new Guid(averageRatingId), list.ParentWeb.AvailableFields);
                if (fieldByField != null && !list.Fields.ContainsField(fieldByField.StaticName))
                {
                    list.Fields.AddFieldAsXml(fieldByField.SchemaXml, true, SPAddFieldOptions.AddFieldToDefaultView | SPAddFieldOptions.AddToAllContentTypes);
                }
               
                SPField ratingCountField = GetFieldById(new Guid(ratingCountId), list.ParentWeb.AvailableFields);
                if (ratingCountField != null && !list.Fields.ContainsField(ratingCountField.StaticName))
                {
                    list.Fields.AddFieldAsXml(ratingCountField.SchemaXml, false, SPAddFieldOptions.AddToAllContentTypes);
                }
                list.Update();
                Repropagate(list);
            }
            catch { } 

The above code creates two fields in the Posts list, you can have any list name you like. Two fields I'm referring to are: "Average Rating" and "Number of Raters". Those have their corresponding types.

Now, you'll notice I used two helper functions:

  1. GetFieldById — which will get a field name by guid passed
  2. Repropagate — will propagate rating functionality to list items (otherwise they won't get a rating beside them)

The following code for those two functions in a helpers region of your code:

#region Helpers 
        private static void Repropagate(SPList list)
        {
            SocialRatingManager ratingManager = new SocialRatingManager(SPServiceContext.Current);
            string baseUrl = list.ParentWeb.Url;
            if (baseUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                baseUrl = baseUrl.TrimEnd(new char[] { '/' });
            }
            foreach (SPListItem item in list.Items)
            {
                string itemUrl = item.Url;
                if (itemUrl.StartsWith("/", StringComparison.OrdinalIgnoreCase))
                {
                    itemUrl = itemUrl.TrimStart(new char[] { '/' });
                }
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    ratingManager.PropagateRating(new Uri(baseUrl + "/" + itemUrl));
                });
            }
        }
        private static SPField GetFieldById(Guid id, SPFieldCollection fieldArray)
        {
            try
            {
                return fieldArray[id];
            }
            catch
            {
                return null;
            }
        }
        #endregion

Note: You will need to add "using Microsoft.Office.Server.SocialData;" to your Feature. This using statement will require you to add the following assembly:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll

This assembly depends on the correct version of Microsoft Chart Controls for Microsoft .NET Framework 3.5 DLL installed. You can reference the DLL directly in your solution by extracting it from you GAC. The assembly is called "System.Web.DataVisualization"

Now, the last part is to handle the feature being deactivated; all we need to do in this case is delete the two columns we have added. We can reuse the same code to get a hold of the list but instead of adding items we delete them:

if (fieldByField != null && list.Fields.ContainsField(fieldByField.StaticName))
                {
                    list.Fields.Delete(fieldByField.StaticName);
                }

That's it! Now when you deploy your solution and the Feature is installed and activated, ratings will be enabled on the Posts list in our case. Note that we executed "AddFieldToDefaultView" in our "Feature Activated" meaning that our rating stars will be displayed only on that view. If you want them to appear on any other view — you can just add the Rating (0-5) column to the view. The rating column is like any other column and you can sort and filter by it.

Share