Follow SharePoint document programmatically

25/02/2016 11:46

Function bellow sets 'Follow' for document with 'itemId' within sharepoint list at 'listUrl' for user 'user'. 

Setting HttpContext to null is because of error:

The operation failed because an internal error occurred. Internal type name: Microsoft.Office.Server.UserProfiles.FollowedContentException. Internal error code: 11.


Code to check if item is already followed is available on link Check if SharePoint item is followed programmatically


public static void ToggleFollowItem(SPWeb web, SPUser user, string listUrl, int itemId, bool follow)
{
 HttpContext currentContext = HttpContext.Current;
 HttpContext.Current = null;
 try
 {
  SPSecurity.RunWithElevatedPrivileges(delegate
  {
   using (SPSite site = new SPSite(web.Site.ID))
   {
    using (SPWeb adminWeb = site.OpenWeb(web.ID))
    {
     var list = adminWeb.GetList(listUrl);
     var item = list.GetItemById(itemId);

     if (item.File != null)
     {
      var serviceContext = SPServiceContext.GetContext(site);
      var userProfileManager = new UserProfileManager(serviceContext);
      
      var userProfile = userProfileManager.GetUserProfile(user.LoginName);

      SPSocialFollowingManager socialManager = new SPSocialFollowingManager(userProfile, serviceContext);
            
      string documentUrl = item.File.Url;
      string documentAbsoluteUrl = SPUrlUtility.CombineUrl(item.Web.Url, documentUrl);

      var actor = new SPSocialActorInfo();

      actor.ContentUri = new Uri(documentAbsoluteUrl);
      actor.ActorType = SPSocialActorType.Document;
      actor.AccountName = user.LoginName;

      if (follow)
      {
       socialManager.Follow(actor);
      }
      else
      {
       socialManager.StopFollowing(actor);
      }
     }
    }
   }
  });
 }
 catch (Exception ex)
 {
 //do handling
 }
 finally
 {
    HttpContext.Current = currentContext;
 }
}