Thursday, 21 July 2016

Check/Get user security role in CRM using C# Code

Hi,

Sometimes, we get the requirement to check the security role of the user in code and doing some business operation.

Here is the C# code for getting security role of the user.

QueryExpression queryExpression = new QueryExpression();
queryExpression.EntityName = "role"; //role entity name
ColumnSet cols = new ColumnSet();
cols.AddColumn("name"); //We only need role name
queryExpression.ColumnSet = cols;
ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "systemuserid";
ce.Operator = ConditionOperator.Equal;
ce.Values.Add(userID);
//system roles
LinkEntity lnkEntityRole = new LinkEntity();
lnkEntityRole.LinkFromAttributeName = "roleid";
lnkEntityRole.LinkFromEntityName = "role"; //FROM
lnkEntityRole.LinkToEntityName = "systemuserroles";
lnkEntityRole.LinkToAttributeName = "roleid";
//system users
LinkEntity lnkEntitySystemusers = new LinkEntity();
lnkEntitySystemusers.LinkFromEntityName = "systemuserroles";
lnkEntitySystemusers.LinkFromAttributeName = "systemuserid";
lnkEntitySystemusers.LinkToEntityName = "systemuser";
lnkEntitySystemusers.LinkToAttributeName = "systemuserid";
lnkEntitySystemusers.LinkCriteria = new FilterExpression();
lnkEntitySystemusers.LinkCriteria.Conditions.Add(ce);
lnkEntityRole.LinkEntities.Add(lnkEntitySystemusers);
queryExpression.LinkEntities.Add(lnkEntityRole);
EntityCollection entColRoles = service.RetrieveMultiple(queryExpression);
if (entColRoles != null && entColRoles.Entities.Count > 0)
{
     foreach (Entity entRole in entColRoles.Entities)
     {
         if (entRole.Attributes["name"].ToString().ToLower() == "<Your rolename>")
         {
 
         }
     }
}

Hope this helps.

--
Happy CRM'ing
Gopinath

2 comments:

  1. Also please take a look at Suti CRM. It’s simple and quick.

    Sage CRM
    DB Computer Solutions

    ReplyDelete
  2. HI,

    i get an error that says the limit for the maximum number of entities to query has exceeded when I put the code in a foreach loop and pass values dynamically of userid from an array

    ReplyDelete