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);

                 }
               }
               
            }
           

Friday, 1 November 2013

Java Script to Navigate to differrent form based on option set in a form MSCRM

Secanrio :When user select option set the layout of form should be different then on selecting different option set.
step 1: create one form new form , then we will have two forms Account and New Form
step 2: create a option set with two option set
form1 and form2
step3: wrtie a java script on form load and form save :

// JScript source code
function showForm() {
   
//get the form type
    if (Xrm.Page.ui.getFormType() == 2)

        var labelOfForm;

// get the option set value
    var Type = Xrm.Page.getAttribute("new_formtype").getValue();

    switch (Type) {
        case 100000000:
            labelOfForm = "Account";
            break;
        case 100000001:
            labelOfForm = "New Form";
            break;
        default:
            labelOfForm = "Account";
    }
// get the form label
    if (Xrm.Page.ui.formSelector.getCurrentItem().getLabel() != labelOfForm)
    {
        var items = Xrm.Page.ui.formSelector.items.get();
        for (var i in items) {
            var item = items[i];
            var itemId = item.getId();
            var itemLabel = item.getLabel()
//if current form label is different then it will navigate to different form
            if (itemLabel == labelOfForm) {

                item.navigate();


            }
        }
    }
}