Search code examples
dotnetnukedotnetnuke-8

Getting all friends in DNN programmatically


I am trying to retrieve all the friends of a particular user. From the DNN RelationshipController I can only find the way to get the relationship between two users. Is it possible to get all the friends of a user?

'Get the relationship between two users:

DotNetNuke.Entities.Users.Social.RelationshipController.Instance.GetFriendRelationship(Me.UserInfo)

Solution

  • I had this code lying around. I get the current user, then get all relationships userIds that are friends (vs. follower) and are 'Accepted'. Using that list, I join back to the Users list to get the friend's user attributes and return as a new object.

    Hope this helps.

    private const int DNNSOCIAL_RELATIONSHIPTYPE_FRIEND = 1;
    private const int DNNSOCIAL_RELATIONSHIPTYPE_FOLLOWER = 2;
    
    public List<UserFriend> GetUserFriends(int portalid, int userid)
    {
        UserInfo currentUser = UserController.GetUserById(portalid, userid);
    
        var friends = currentUser.Social.UserRelationships
                        .Where(r => r.RelationshipId == DNNSOCIAL_RELATIONSHIPTYPE_FRIEND 
                            && r.Status == RelationshipStatus.Accepted);
    
        return (from f in friends
                join u in UserController.GetUsers(portalid).Cast<UserInfo>()
                on f.RelatedUserId equals u.UserID
                select new UserFriend { UserId = u.UserID,  DisplayName = u.DisplayName, ProfilePicUrl = u.Profile.PhotoURL }).ToList();
    }
    

    ...

    public class UserFriend
    {
        public int UserId { get; set; }
        public string DisplayName { get; set; }
        public string ProfilePicUrl { get; set; }
    }
    

    VB.NET version

    Public Function GetUserFriends(portalid As Integer, userid As Integer) As List(Of UserFriend)
        Dim currentUser As UserInfo = UserController.GetUserById(portalid, userid)
    
    Dim friends = currentUser.Social.UserRelationships.Where(Function(r) r.RelationshipId = DNNSOCIAL_RELATIONSHIPTYPE_FRIEND AndAlso r.Status = Social.RelationshipStatus.Accepted)
    
    Return (From f In friends
            Join u In UserController.GetUsers(portalid).Cast(Of UserInfo)()
            On f.RelatedUserId Equals u.UserID
            Select New UserFriend With {.UserId = u.UserID, .DisplayName = u.DisplayName, .ProfilePicUrl = u.Profile.PhotoURL}).ToList()
     End Function