Get followed users, and get followers, in SharePoint 2013 social

A common and important task in SharePoint 2013 social scenarios is to get followed users for an user, or to get user’s followers programmatically.

Here are the necessary code snippets, they are pretty self-explanatory 😉

To get followed users:

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);

      SPSocialActor[] followed = followingManager.GetFollowed(SPSocialActorTypes.Users);

      Console.WriteLine("Followng:");
      foreach (var actor in followed)
      {
          Console.WriteLine(actor.AccountName);
      }

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

To get the followers:

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);

        SPSocialActor[] followers = followingManager.GetFollowers();

        Console.WriteLine("Followers:");
        foreach (var actor in followers)
        {
            Console.WriteLine(actor.AccountName);
        }

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