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 !


You must be logged in to post a comment.