Follow SharePoint sites on behalf of someone in SharePoint 2013 social

Following sites on behalf of users in a common and obligatory task in enterprise social scenarios. Think of onboarding procedures: everyone from HR must follow a HR team site, for example.

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.Site;
        actor.ContentUri = new Uri(tofollow);


        //to stop following a site, you would do something like:
        bool stoppedFollowing = followingManager.StopFollowing(actor);

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


Following sites is not security trimmed! That means, if the user from your context does not have permissions on the site, you can still follow the site. It does not make much sense, since the feed is security trimmed, so the user won’t get anything from the site in her feed, but it is still “unpleasant” to see the site title among the list of the followed sites. Please use the search to security trim the site before following it.