Follow a document on behalf of an user in SharePoint 2013 social

Following documents on behalf of users in a common and obligatory task in enterprise social scenarios. Think of onboarding procedures: each employee must follow the “company rules” document, and get notified when this document periodically updates.

This is not possible with SharePoint Client Object Model, bit it is an easy exercise with SharePoint Server Object Model.

using (SPSite site = new SPSite(siteName))
{
    SPServiceContext context = SPServiceContext.GetContext(site);

    UserProfileManager profileManager = new UserProfileManager(context);

    if (profileManager.UserExists(username))
    {
        UserProfile userProfile = profileManager.GetUserProfile(username);

        //get the Social Feed Manager of the current user
        SPSocialFeedManager feedManager = new SPSocialFeedManager(userProfile, context);

        //But, since the FollowingManager property of the feedManager is not aware of the user context, feed manager is in THIS scenario useless
        //we need to create SPSocialFollowingManager object in user context, and to use that for the following purposes
        SPSocialFollowingManager followingManager = new SPSocialFollowingManager(userProfile, context);

        SPSocialActorInfo actor = new SPSocialActorInfo();
        actor.ActorType = SPSocialActorType.Document;
        actor.ContentUri = new Uri(tofollow);

        followingManager.Follow(actor);

    }
    else
    {
        Console.WriteLine(string.Format("User Profile for user {0} does not exist", username));
    }
}

BE AWARE:

Following documents is not security trimmed! That means, if the user from your context does not have permissions on a document, you can still make him following it! It does not make much sense, since the feed is security trimmed, so the user won’t get anything from the document in her feed, but it is still “unpleasant” to see the document title among the list of the followed sites. Especially if it is called something like “List of the employees who are going to be fired in August 2013.docx”. Please use the search to security trim the documentbefore following it.