Get followed sites for an user in SharePoint 2013 social

Getting the sites that a specific user follows in SharePoint 2013 enterprise social scenarios is a common requirement.

Here is the code snipped which does the job 😉

using (SPWeb web = site.OpenWeb())
{
    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);

        SPSocialActor[] followedSites = followingManager.GetFollowed(SPSocialActorTypes.Sites);

        Console.WriteLine("Followed sites:");
        foreach (var actor in followedSites)
        {
            Console.WriteLine(string.Format("Name: {0} Uri: {1}", actor.Name, actor.Uri));
        }
    }
    else
    {
        Console.WriteLine(string.Format("User Profile for user {0} does not exist", username));
    }
}