Monday, 4 November 2013

Trigger plugin on assignment of security role mscrm

Triggering a plugin on adding of security role
if xyz security role is assigned to user then add user to a team.

step 1: Register a plugin  on message Associate , primary and secondary entity as none
step2:   AssignUserRoles as a message and primary entity as a Role

public void Execute(IServiceProvider serviceProvider)
        {
            // Extract the tracing service for use in debugging sandboxed plug-ins.
            // If you are not registering the plug-in in the sandbox, then you do
            // not have to add any tracing service related code.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));

             // The InputParameters collection contains all the data passed in the message request.
verify plugin message is associate or
        if (context.MessageName=="Associate" || context.MessageName== "AssignUserRole")       
        {
            // Obtain the target entity from the input parameters.

            EntityReference entity = (EntityReference)context.InputParameters["Target"];
        
            // Verify that the target entity represents an entity type you are expecting.
            // For example, an user entity If not, the plug-in was not registered correctly.
            if (entity.LogicalName.ToUpper() != "SYSTEMUSER")
                return;

            // Obtain the organization service reference which you will need for
            // web service calls.
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

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

            try
            {
                Guid userId = context.InitiatingUserId;
                Guid businessUnitId = getBuid(service);
                //get roles of a  user
                Entity role = new Entity();
                role.LogicalName = "role";

                Entity systemUserRoles = new Entity();
                systemUserRoles.LogicalName = "systemuserroles";
//query expression to fetch security role associated to a user
as we have Guid  of initiating user
                QueryExpression query = new QueryExpression()
                {
                    Distinct = false,
                    EntityName = role.LogicalName,
                    ColumnSet = new ColumnSet("name")
                };
               
                query.AddLink(systemUserRoles.LogicalName, "roleid", "roleid").
                LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, userId);


                //query expression to execute the role
                EntityCollection entRoles = service.RetrieveMultiple(query);

                //get role name
                List<string> rolesname = new List<string>();
                foreach (Entity roles in entRoles.Entities)
                {

                    rolesname.Add(roles.Attributes["name"].ToString());
                }

                //create a team if not exist
                Entity team = new Entity("team");
               // team.Id = new Guid();
                team["name"] ="Team1";
                team["businessunitid"] = new EntityReference("businessunit", businessUnitId);
                team["administratorid"] = new EntityReference("systemuser", context.UserId);
             
// Create the team in Microsoft Dynamics CRM if not exist.
                QueryExpression qp = new QueryExpression();
                qp.EntityName = "team";
                qp.ColumnSet = new ColumnSet();
                qp.ColumnSet.AddColumns("teamid", "name");
                qp.Criteria.AddCondition("name",ConditionOperator.Equal,"Team1");
               EntityCollection ent = service.RetrieveMultiple(qp);
               Guid teamid = Guid.Empty;

                foreach(Entity enti in ent.Entities)
                {
                    teamid = (Guid)enti["teamid"];
                }

               if (ent.Entities.Count == 0)
               {
                   service.Create(team);
               }
                // Plug-in business logic goes here.
               foreach(string rolesnames in rolesname)
               {
                 if( rolesnames == "System Administrator")
                 {
                
                     //create a members to a team

                     AddMembersTeamRequest addMembereTeamRequest = new AddMembersTeamRequest();
                     addMembereTeamRequest.TeamId = teamid;
                     Guid[] arrayMembers = new Guid[1];
                     arrayMembers[0] = userId;
                     addMembereTeamRequest.MemberIds = arrayMembers;
                     AddMembersTeamResponse addMembersTeamresp = (AddMembersTeamResponse)service.Execute(addMembereTeamRequest);

                 }
               }
               
            }