CRM 2011 C#: Get List of User Security Roles

Hello guys,

Use below method to get the list of Security Roles that the logged in user belongs to.

A WhoAmIRequest and WhoAmIResponse messages are used to get the current logged in user’s GUID. I have used a FetchXml technique to get the Roles list. The primary entity role is used and a related entity systemuserroles is used to relate the records and a condition is given on the same entity to find the logged in user’s related records.

private List<string> RetrieveSecurityRoles()
{
	List<string> rolesList = new List<string>();
	string fetchXml = @"<fetch mapping=""logical"" count=""50"" version=""1.0"">
							<entity name=""role"">
								<attribute name=""name"" />
								<link-entity name=""systemuserroles"" from=""roleid"" to=""roleid"">
									<filter>
										<condition attribute=""systemuserid"" operator=""eq"" value=""{0}"" />
									</filter>
								</link-entity>
							</entity>
						</fetch>";
	fetchXml = string.Format(fetchXml, ((WhoAmIResponse)oHelper._crmservice.Execute(new WhoAmIRequest())).UserId);
	var result = oHelper._crmservice.RetrieveMultiple(new FetchExpression(fetchXml));

	foreach (var item in result.Entities)
	{
		rolesList.Add(item.Attributes["name"].ToString());
	}

	return rolesList;
}

Hope this helps!!

Leave a comment