Archive

Posts Tagged ‘security roles’

Fetching user security roles using Linq in CRM 2011 Plug-in’s

January 17, 2012 5 comments

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 🙂