dotnetnukedotnetnuke-8

Get RoleName from a RoleGroup by UserID


I have a RoleGroup with some Roles in it. A user can only belong to one of these roles. How would I get the RoleName based on the RoleGroup which the user belongs to? Any ideas?

Dim roleGroupOmniProfiles = RoleController.GetRoleGroupByName(PortalSettings.Current.PortalId, "OmniProfiles")

Problem is here

Dim omniProfile = roleGroupOmniProfiles.Roles.Any(Function(role) oUser.UserID)

Solution

  • roleGroupOmniProfiles contains a collection of KeyValuePair<string, RoleInfo>, so you can loop them as shown below.

    But I'm not sure you can get the RoleName from a RoleGroup by UserID since UserID has no direct link to RoleGroup. Shouldn't it be that you get all the Roles from a user based on UserID and check which RoleGroup the Roles belongs to, if any.

    C#

    var roleGroupOmniProfiles = RoleController.GetRoleGroupByName(PortalId, "OmniProfiles");
    
    if (roleGroupOmniProfiles != null)
    {
        foreach (KeyValuePair<string, RoleInfo> role in roleGroupOmniProfiles.Roles)
        {
            Label1.Text += role.Key + " | " + role.Value.RoleName + "<br>";
        }
    }
    

    Or as one-liner

    RoleInfo roleInfo = roleGroupOmniProfiles.Roles.Where(x => x.Value.RoleID == 15).FirstOrDefault().Value;
    

    VB

    If (Not (roleGroupOmniProfiles) Is Nothing) Then
        For Each role As KeyValuePair(Of String, RoleInfo) In roleGroupOmniProfiles.Roles
            Label1.Text += role.Key + " | " + role.Value.RoleName + "<br>"
        Next
    End If
    

    UPDATE

    To check if a user belongs to a group you can use this

    DotNetNuke.Entities.Users.UserInfo user = DotNetNuke.Entities.Users.UserController.GetUserByName("userName");
    bool isInGroup = roleGroupOmniProfiles.Roles.Keys.Any(role => user.IsInRole(role));