Below is the sample code to associate a security role on user creation in CRM 2011. Register the plugin on Post Create of systemuser entity and select execution mode as Asynchronous
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context =
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Get a reference to the organization service.
IOrganizationServiceFactory factory =
(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains(“Target”) &&
context.InputParameters[“Target”] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters[“Target”];
// Verify that the target entity represents a systemuser.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != “systemuser”)
return;
try
{
// get user entity record id
Guid userId=(Guid)context.OutputParameters[“id”];
//Get Id of Security Role
Guid securityRoleId=new Guid(“<enter guid here>”)
// Create the request object
// systemusersroles_association relationship.
AssociateRequest addRolesToUser = new AssociateRequest
{
Target = new EntityReference(“systemuser”, userId),
RelatedEntities = new EntityReferenceCollection
{
new EntityReference(“role”, securityRoleId)
},
Relationship = new Relationship(“systemuserroles_association”)
};
// Execute the request.
service.Execute(addRolesToUser);
}
catch (FaultException<OrganizationServiceFault> ex)
{
// Handle the exception.
}
}
}
hope it will help u !