Hi,

Below is the sample code to fetch the User’s security roles based on the “User Id” in the Plug-in’s using Linq

        /// <summary>

/// Returns the list of User security role names

/// </summary>

private List<string> GetUserRoles(IOrganizationService service, Guid userId) {

// Create Query Expression to fetch Role Entity

var query = new QueryExpression

{

// Setting the link entity condition and filter condition criteria/

LinkEntities =

{

new LinkEntity

{

LinkFromEntityName = “role”,

LinkFromAttributeName = “roleid”,

LinkToEntityName = “systemuserroles”,

LinkToAttributeName = “roleid”,

LinkCriteria = new FilterExpression

{

FilterOperator =

LogicalOperator.And,

Conditions =

{

new ConditionExpression

{

AttributeName =  “systemuserid”,

Operator =    ConditionOperator.Equal,

Values =

{

userId

}

}

}

}

}

},

ColumnSet = new ColumnSet(true),

EntityName = “role”

};

// Obtain results from the query expression.

var userRoles = service.RetrieveMultiple(query);

// Get the usre role names collection

var roleNames = new List<string>();

if (userRoles != null)   {

roleNames.AddRange(

from entrole in userRoles.Entities

select entrole as Role

into role

where role != null && role.RoleId != null

select role.Name);

}

return roleNames;

}

How do I call this method :-

  • In your plug-in, pass the service and User Id as parameters to this method

public void Execute(IServiceProvider serviceProvider) {

context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

var service = serviceFactory.CreateOrganizationService(context.UserId);

// Get the current users Security Roles Name’s

Var roleNames = GetUserRoles(service, this.context.UserId);

}

Hope it helps 🙂

Advertisements
Advertisements

5 responses to “Fetching user security roles using Linq in CRM 2011 Plug-in’s”

  1. dpantara Avatar
    dpantara

    hi,

    I got error in this code “from entrole in userRoles.Entities”

    could you give advise how to fix it?

    thanks.

  2. Rajeev Pentyala Avatar

    Hello,
    Can you please post the error details.

    1. dpantara Avatar
      dpantara

      hi..
      I have fix it, that’s the simple issue, I haven’t add reference from system.linq

      sorry its my bad 🙂

      btw thanks for your article its very helpfully for my new snipped code

  3. Kirk Covert Avatar

    This routine isn’t bringing back all the known roles for a user

  4. Kirk Covert Avatar

    My bad, works find, here’s the LinQ join to make up for it…

    from r in RoleSet
    join s in SystemUserRolesSet on r.RoleId equals s.RoleId
    where s.SystemUserId == Guid.Parse(“933a9592-93a1-df11-8770-0050568f359c”)
    select r

Leave a reply to dpantara Cancel reply