Search

Get all roles assigned to a user in MSCRM 4.0

Hi this is a small function to get all the roles assigned to a particular user in Dynamics CRM 4.0 using the CRM SDK.
// Get all roles  assigned to a user 
private BusinessEntityCollection CurrentUserRoles(ICrmService service, Guid userId)
{
var queryForUserRole = new QueryExpression { 
EntityName = "role", 
ColumnSet = new AllColumns()
};

// Create the link entity from role to systemuserroles.
var linkEntityRole = new LinkEntity{
LinkFromEntityName = "role",
LinkFromAttributeName = "roleid",
LinkToEntityName = "systemuserroles",
LinkToAttributeName = "roleid"
};

var linkEntityUserRoles = new LinkEntity{
LinkFromEntityName = "systemuserroles",
LinkFromAttributeName = "systemuserid",
LinkToEntityName = "systemuser",
LinkToAttributeName = "systemuserid"
};

// Create the condition to test the user ID.
var conditionForUserRole = new ConditionExpression{
AttributeName = "systemuserid",
Operator = ConditionOperator.Equal,
Values = new object[] { userId }
};

// Add the condition to the link entity.
linkEntityUserRoles.LinkCriteria = new FilterExpression();
linkEntityUserRoles.LinkCriteria.Conditions.Add(conditionForUserRole);

// Add the from and to links to the query.
linkEntityRole.LinkEntities.Add(linkEntityUserRoles);
queryForUserRole.LinkEntities.Add(linkEntityRole);

// Retrieve the roles and write each one to the console.
BusinessEntityCollection currentUserRoles = service.RetrieveMultiple(queryForUserRole);
return currentUserRoles;
}