Thursday 20 July 2017

Sharing and unSharing records using custom workflow

Sharing and Revoke Records to Team using Custom Workflow


Hi all,

Recently I got a requirement for Sharing records using Workflow. As of now I never tried sharing records. By default, we don't have any OOB functionality for sharing records. We have the only option for Assigning records. 

So I decided to create a custom workflow. Here I am pasting my code.

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;

namespace SharingAccountRecordstoTeam
{
    public class Class1 : CodeActivity
    {
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            Entity account = (Entity)context.InputParameters["Target"];

            // Create the request object and set the target and principal access
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target = new EntityReference("account", account.Id),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal = new EntityReference("team", Team.Get<EntityReference>(executionContext).Id),
                    AccessMask = AccessRights.WriteAccess | AccessRights.ReadAccess | AccessRights.ShareAccess                                     // Mention here what Access you want to provide.
                }
            };

            // Execute the request.
            GrantAccessResponse granted = (GrantAccessResponse)service.Execute(grantRequest);

// Revoke The shared recorde from Team
 RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
            {
                Target = new EntityReference("account", account.Id),
                Revokee = new EntityReference("team", Team.Get<EntityReference>(executionContext).Id),
            };

            // Execute the request.
            RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revokeRequest);
      }
        [Input("Team")]
        [ReferenceTarget("team")]
        public InArgument<EntityReference> Team { get; set; }
    }
}


This is the code for Sharing and revoking records to Team. Once Completed the code, then register your workflow to Plugin Registration Tool. then your workflow will be available in processes. Just add your condition and after that call this Workflow.

Note:   Pass Team Id as a parameter.

This is for the new users who want to create a custom workflow.

Hope it will help you.

Thanks,
Shivaram.


Sunday 12 February 2017

Hide +New button in Subgrid programmatically.

Hide +New button in Subgrid programmatically.


Hi all,

             Recently I got one requirement that Hide +New button from subgrid based on Condition. By default we can hide button using Right Click --> Hide button. But based on condition if we want to hide then we need to write our custom function. 

            Here I am posting this for how to achieve this. For achieve this, we should have Ribbon Workbench Solution. you can download that using following link


or you can down load latest XRM tool which is providing Ribbon workbench Plugin directly. 


Now Create one web Resource Javascript in your CRM solution.



In this scenario, I am hiding New Button, if Form is having value for Name field. If Name field is not having value then New button field should be visible. For that I wrote following code.

function RemoveNewButton(){
// Checking Name field is having Value or not
if(Xrm.Page.getAttribute("rbn_name").getValue()!=null)
           return false;
else
          return true;
}

If you want to Hide/Show button based on user role, first get the user role using following code.

function CheckUserRole() {
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
         var userRoleId = currentUserRoles[i];
    var userRoleName = GetRoleName(userRoleId);
        if (userRoleName == "System Administrator") {
            return true;
        }
    }
    return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
    //var serverUrl = Xrm.Page.context.getServerUrl();
    var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
    var roleName = null;
    $.ajax(
        {
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                roleName = data.d.results[0].Name;
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect);
}
        }
    );
    return roleName;
}


After adding this Javascript to your web resource, then open your ribbon workbench and Import which solution you are working on. Now select which entity Form deactivate button you need to hide.Here I want to hide Contact Entity Deactivate Button.


Now click on Customize Command button in above options. (Above Image Accidentally I highlighted Customize Button please observe)

Then Add New Enable rule. 

Using following Steps.

Right Click -> Add New-> right side you can see Steps Lookup -> Click on that -> Add New.
Observe following images







Then you will get following options



Fill all those details like above and then click Ok.

Now you successfully created Enable Rule.

Now go to Commands section and click On deactivate command. And select Edit Enable Rule. like following


Then You will get following popup


Click Ok and Publish your customizations. Then Deactivate button will visible only for System Admin.

But I will suggest you one thing in your Js code. Don't use hardcoded GUID Value in code. Because it might be vary from one environment to another Environment (Dev to Test)

Hope it helps you.

Thanks.