Monday, October 13, 2008

Get User Roles from User ID Using C# in Microsoft CRM 4.0

It is fairly easy to use the web service to get the roles for a particular user based on their GUID.
This methodology is based on a post by Jim Wang at in client-side jscript ; there isn’t much good information out on the web on how to do this in C#, and it is a bit more difficult than a normal retrievemultiple call considering it is a many-to-many relationship, so… here it is!

On a side note, congratulations Jim on getting awarded with the honor of CRM MVP.

public BusinessEntityCollection GetUserRoles(Guid guidUserID, ICrmService serv)
QueryExpression qe = new QueryExpression();
qe.EntityName = "role";
qe.ColumnSet = new AllColumns();

LinkEntity le = new LinkEntity();
le.LinkFromEntityName = "role";
le.LinkFromAttributeName = "roleid";
le.LinkToEntityName = "systemuserroles";
le.LinkToAttributeName = "roleid";

ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "systemuserid";
ce.Operator = ConditionOperator.Equal;
ce.Values = new object[] { guidUserID };

LinkEntity le2 = new LinkEntity();
le2.LinkFromEntityName = "systemuserroles";
le2.LinkFromAttributeName = "systemuserid";
le2.LinkToEntityName = "systemuser";
le2.LinkToAttributeName = "systemuserid";

le2.LinkCriteria = new FilterExpression();


RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest();
rmRequest.ReturnDynamicEntities = true;
rmRequest.Query = qe;

RetrieveMultipleResponse response = (RetrieveMultipleResponse)serv.Execute(rmRequest);

if (response.BusinessEntityCollection.BusinessEntities.Count > 0)
return response.BusinessEntityCollection;
return null;
catch (Exception ex)

WriteToFile("error: " + ex.ToString());

return null;


This post is provided as-is and implies no warranty; Jamie Miley does not assume any responsibility for problems arising from the use of this information.

No comments:

Post a Comment