Showing posts with label user Security. Show all posts
Showing posts with label user Security. Show all posts

Monday, February 6, 2017

Show CRM entity form to particular Business unit users only

In MS CRM we can enable security role to custom forms, and only selected role users can view that form. When selecting role, all Roles are shown form ROOT business unit, there is no option to get security role from child business units.

In some cases if you want to show custom entity form only for particular business unit users regardless of their role, then need to write custom JavaScript code.

Add following function for entity form, which want to show based on business unit, if users business unit is not allowing to view form, then user will be redirected to other form.

var accountScript = {
    showFormBasedOnBusinessUnit: function () {
        var userId = Xrm.Page.context.getUserId();
        userId = userId.replace("{", "").replace("}", "");
        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/systemusers(" + userId + ")?$select=_businessunitid_value", false);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var result = JSON.parse(this.response);
                    var businessunitid = result["_businessunitid_value"];
                    var businessunitidname = result["_businessunitid_value@OData.Community.Display.V1.FormattedValue"];
                   
                    if (businessunitidname != "Finance") {
                        var forms = Xrm.Page.ui.formSelector.items.get();
                        for (var i in forms) {
                            var formname = forms[i].getLabel();
                            if (formname == "Information") {
                                forms[i].navigate();
                                break;
                            }
                        }
                    }

                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
    }

};


Thursday, May 5, 2016

Add / remove users to Access team dynamically

Sometime we need to add users into access teams when record is created or based on some business logic.

From MS CRM 2013 Microsoft introduced access teams.

For information about access team
 Use access teams and owner teams to collaborate and share information

You can enable access team for entity and create access team templates.

Here is more information on how to create access team template and add to form.
Create Access Teams

when you created access team template you can add it to form and add users manually to give access to record, but some time we need to it automatically.

To do automatically, you can use  AddUserToRecordTeamRequest messge.

AddUserToRecordTeamRequest addReq = new AddUserToRecordTeamRequest()
       {
         Record = Record Entity Reference,
         SystemUserId = UserId,
         TeamTemplateId = TemplateId

       };

service.Execute(addReq);

and use Execute to pass this request.

If want to do add user into multiple records access Team.

public void AddUserToAccessTeam(IOrganizationService service, List<EntityReference> lstentref, string templateName, Guid loggedInUser, Guid? TemplateId)
        {
         using (XrmServiceContext Xrmcontext = new XrmServiceContext(service))                                  {
                Guid teamTemplate = new Guid();

                if (TemplateId == null || TemplateId.Value == Guid.Empty)
                    /*Get Access Team Template from Template Name*/
                    teamTemplate = Xrmcontext.TeamTemplateSet.Where(ttm => ttm.TeamTemplateName == templateName).Select(ttm => ttm.TeamTemplateId.Value).FirstOrDefault();
                else
                    teamTemplate = TemplateId.Value;

                int count = 0;
                int TotalRecord = lstentref.Count();
                int recordRemaining = TotalRecord;

                /*Initialize multiple request*/
                ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
                {
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    },
                    Requests = new OrganizationRequestCollection()
                };

                foreach (EntityReference entRef in lstentref)
                {
                    recordRemaining--;
                    /*Add user to Record Team request*/
                    AddUserToRecordTeamRequest addReq = new AddUserToRecordTeamRequest()
                    {
                        Record = entRef,
                        SystemUserId = loggedInUser,
                        TeamTemplateId = teamTemplate
                    };

                    requestWithResults.Requests.Add(addReq);
                    count++;
                    if (count == 999 || recordRemaining == 0)
                    {
                        ExecuteMultipleResponse responseWithResults = (ExecuteMultipleResponse)Xrmcontext.Execute(requestWithResults);
                        requestWithResults.Requests.Clear();
                        count = 1;
                    }
                }
            }
        }


To remove user from access team you can use RemoveUserFromRecordTeamRequest messge.

RemoveUserFromRecordTeamRequest addReq = new RemoveUserFromRecordTeamRequest()
    {
      Record = Record Entity Reference,,
      SystemUserId = User Id,
      TeamTemplateId = Access Team Template Id

    };

Use similar method as AddUserToAccessTeam, if you want to remove user from multiple records.