It is a common task in enterprise social scenarios to retrieve all followed documents for an user. This code snipped shows how to achieve that, plus, how to check if an user actually should have right at all to follow that particular document, since following documents is not security trimmed.
{
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[] documents = followingManager.GetFollowed(SPSocialActorTypes.Documents);
Console.WriteLine("Followed documents:");
foreach (SPSocialActor actor in documents)
{
Console.WriteLine(string.Format("Name: {0} Uri: {1}", actor.Name, actor.Uri));
//now, get the SPSite and the SPWeb of the followed document
string[] parts = actor.Id.Split('.');
Guid siteId = new Guid(parts[1]);
Guid webId = new Guid(parts[2]);
//for a test, check if the user should actually be allowed to follow the document at all
using (SPSite lsite = new SPSite(siteId))
{
using (SPWeb lweb = site.OpenWeb(webId))
{
SPListItem itm = lweb.GetListItem(actor.Uri.ToString());
SPUser targetUser = lweb.EnsureUser(userProfile.AccountName);
bool canRead = itm.DoesUserHavePermissions(targetUser, SPBasePermissions.ViewListItems);
if (canRead)
{
Console.WriteLine("Allowed to follow");
}
else
{
Console.WriteLine("NOT allowed to follow");
}
};
};
}
}
else
{
Console.WriteLine(string.Format("User Profile for user {0} does not exist", username));
}
}