Tip for identifying button/command ID in Ribbon Workbench

Ribbon Workbench is a great tool for customising the ribbon in CRM. When you need to customise an OOTB button/command however, it can be a bit difficult to identify the correct button/command to work with. This is particularly true when some of the OOTB buttons appear the same on the Ribbon Workbench’s UI, such as the Add Existing buttons below.

One way to identify the correct button/command is to inspect the HTML on the CRM form.

In the example below, I can see that the ID of the + (add existing record) button on a sub-grid is Mscrm.AddExistingRecordFromSubGridAssociated.

I can then pick the right button to customise in Ribbon Workbench by selecting the button with the same ID for CommandCore:

Hope this helps increase your productivity with Ribbon Workbench.

Posted in CRM | Leave a comment

‘An unexpected error occurred’ and using early-binding in CRM plugins

Our plugin was throwing the error below when creating a new task record:

‘An unexpected error occurred.’

at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Create(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)
at Microsoft.Crm.Extensibility.InprocessServiceProxy.CreateCore(Entity entity)

We were not doing anything fancy that led to this error – except we used early-binding classes:

var task = new Task
	Subject = "New task",
	Description = "Some description..."

task.Id = _organisationService.Create(task);

Our plugin was deployed to the database, and we used ILMerge to package everything into a single DLL as required by CRM under this deployment type. This was not the cause of our problem.

The strange thing is the plugin only error when running asynchronously. Changing the plugin step to be synchronous and everything works fine.

It turns out that this is because there are different behaviours between the CRM execution context for synchronous versus that for asynchronous.

Let’s take a step back in order to fully understand this. The IOrganizationService instance has a non-public property _proxyTypesAssembly that points to the assembly where the early-binding classes are defined. This must be set for the service instance to be able to work with early-binding classes properly. When things are good, this is what it looks like when you debug:

The error occurs when this property is null.

So how does this property get set? In plugins we typically use an instance of IOrganizationServiceFactory to get access to an instance of IOrganisationService:

serviceFactory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof (IOrganizationServiceFactory));
service = serviceFactory.CreateOrganizationService(userId);

It is at this point that the _proxyTypesAssembly property is set for the IOrganizationService instance by the IOrganizationServiceFactory.

Below is a screenshot of inspecting the IOrganizationServiceFactory when the plugin in running synchronously. Note that the public ProxyTypesAssembly property is automatically set.

Also note that the type of the IOrganizationServiceFactory instance (serviceFactory) is Microsoft.Crm.Extensibility.PipelineExecutionContext.

Below is a screenshot of the same plugin running asynchronously. Note that the public ProxyTypesAssembly property is null, and the type of the IOrganizationServiceFactory is different compare to when running synchronously.

This is why by default plugins that use early-binding work fine in synchronous mode, but fail when running asynchronously.

To fix this issue we need to set the ProxyTypesAssembly property of the IOrganizationServiceFactory instance. While this property is not exposed on this interface, Darko Micic has found that the IOrganizationServiceFactory interface can be casted to IProxyTypesAssemblyProvider, which allows us to set this property.

The code to retrieve an instance of IOrganizationService therefore becomes:

var serviceFactory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof (IOrganizationServiceFactory));
var proxyTypesAssemblyProvider = serviceFactory as IProxyTypesAssemblyProvider;

if (proxyTypesAssemblyProvider != null)
	proxyTypesAssemblyProvider.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

service = serviceFactory.CreateOrganizationService(userId);

Note that in Darko’s post he mentioned casting the execution context to IProxyTypesAssemblyProvider. In my debugging I have found that IOrganizationServiceFactory and IPluginExecutionContext actually points to the same instance when retrieved from the service provider. I therefore have chosen to cast the IOrganizationServiceFactory instance instead.

Posted in CRM | Leave a comment

How to set EntityCollection property of service response for unit testing purposes [CRM]

When unit testing CRM C# codes, you may find that you need to mock the response of calls to CRM’s Organisation service. A number of response classes in the SDK contain an EntityCollection property. This property however is null and is read-only, which means you cannot populate it with mock entries – or at least it seems that way.

This will not work:

var mockResponse = new InstantiateTemplateRequest();

//This won't compile as EntityCollection property does not have a setter
mockResponse.EntityCollection = new EntityCollection();

Neither will this:

var mockResponse = new InstantiateTemplateRequest();

//This will give you a run-time exception as EntityCollection property is null.
mockResponse.EntityCollection.Add(new Entity());   

Behind the scene, the EntityCollection property is actually a facade for reading a key from the Results property. The Results property is defined on the base class of all response classes.

You therefore can set and populate the EntityCollection property as follow:

//The mock response
var response = new InstantiateTemplateResponse();
response.Results["EntityCollection"] = new EntityCollection(new List<Entity> { new Entity() });

//response.EntityCollection will now contain one mock entity that we have just configured above.
Posted in CRM, Unit Test | Leave a comment

Getting entity type name, entity code, and entity display name in JavaScript [CRM]

This is a rehash of Michaël Hompus’ post https://blog.hompus.nl/2015/05/28/entity-type-code-using-javascript-only/ to help me remember this very useful trick.

Note that the scripts described in this post are unsupported.

In JavaScript, use Mscrm.EntityPropUtil.EntityTypeName2CodeMap to retrieve the entity type code for a given entity type name, e.g.:

Mscrm.EntityPropUtil.EntityTypeName2CodeMap.new_application   //returns 10008

Use Mscrm.EntityPropUtil.EntityLogicalNameToLocalizedNameMap to retrieve the entity display name for a given entity type name, e.g.:

Mscrm.EntityPropUtil.EntityLogicalNameToLocalizedNameMap.new_application   //returns Credit Application

Depending on how your script was loaded, Mscrm may be null, in which case try looking for it under the parent object instead, i.e. parent.Mscrm.EntityPropUtil…

Posted in CRM | 2 Comments

Mixing early-binding and late-binding with nameof operator in C# [CRM]

There are many benefits of using early-binding when coding against CRM. There are times however when you need to fall back to late-binding, for example when you need to query relationships, or when you need to call Retrieve to optimise performance (as this service call allows you to load only selected fields of a record).

Rather than using literal string, you can use the nameof operator in C# 6 to get the attributes and relationship names. This works because the properties of the early-binding classes are generated based on the attributes and relationship names in CRM.

For example, to get the AccountNumber field of an Account record:

var client = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CRM"].ConnectionString);

//Remember to convert to lowercase.
var accountNumberAttributeName = nameof(Account.AccountNumber).ToLower();

var entity = client.Retrieve(Account.EntityLogicalName, Guid.NewGuid(), new ColumnSet(accountNumberAttributeName));
var accountNumber = entity.ToEntity<Account>().AccountNumber;

And there you have it: late-binding with all the early-binding zen!

Posted in CRM | 2 Comments

Apply filtering to subgrid’s inline lookup in CRM

A common requirement is to apply filtering to a subgrid’s inline lookup on CRM form. For example, you might want to allow users to add only contacts of a particular account (selected in another field) to a contact subgrid on the form.

Just to be clear, the highlighted lookup below is what we want to filter (and what this post is about). There are several posts on the web that talk about filtering the subgrid; but they are about filtering the records that appear on a subgrid, and not the records that appear in the inline lookup that is use to add a record to the subgrid.


Note: The method described in this post is unsupported.

The inline lookup of a subgrid is actually a normal lookup control (more or less), and therefore has the same methods as a normal lookup control. We therefore can apply filtering to this control using the standard addPreSearch and addCustomFilter methods of the control.

It is however difficult to gain access to this control (for a subgrid) as it is not exposed in any of the API. We therefore will need to use unsupported methods to access it.

The subgrid’s lookup control is actually given a control name by CRM, and this name is based on the name of the subgrid. For example, if the subgrid is named grdContacts in the form, the name of the subgrid’s lookup control would be lookup_grdContacts. We can use this name to retrieve the lookup control – but wait..

While you can use Xrm.Page.getControl(“lookup_grdContacts”) to retrieve the subgrid’s lookup, you can only do so after the user has clicked the + icon on the subgrid to bring up the lookup control. Therefore, our code to retrieve the lookup control and call the addPreSearch and addCustomFilter methods on it would need to happen within (or triggered by) the click event of the + icon.

The HTML ID of the + icon has the format [gridName]_addImageButton, e.g. grdContacts_addImageButton. Using this ID we can retrieve the + icon from the DOM and attach code to the click event to retrieve the lookup control and apply our filter.

Below is the code. Please review the in-code comments.

function setSubgridLookupFiltering() {
	var subgridAddButtonId = "grdContacts_addImageButton";

	//Try to get the element from both the current and the parent document.
	var subgridAddButton = document.getElementById(subgridAddButtonId) || window.parent.document.getElementById(subgridAddButtonId);

	//This script may run before the subgrid has been fully loaded on the form. If this is the case,
	//delay and retry until the subgrid has been loaded.
	if (subgridAddButton == null) {
		setTimeout(setSubgridLookupFiltering, 2000);

	//Local function to retrieve the lookup control and apply the filter. We will queue this function in the click event handler of the
	//Add button's click event.
	var getSubgridLookupAndAddFilter = function() {
		var subgridLookup = Xrm.Page.getControl("lookup_grdContacts");

		//Delay and retry until we can locate the lookup.
		if (subgridLookup == null) {
			setTimeout(getSubgridLookupAndAddFilter, 200);

		//This is a custom property we are tagging on to the lookup control to ensure that we will
		//apply the custom filter only once when the Add button is first clicked.
		if (subgridLookup.customFilterAdded) {

		subgridLookup.addPreSearch(function() {
			//Standard logic to build up the filter query string
			var filterQuery = "";

			//filterQuery = "<filter type='and'.....></filter>";

			//Standard call to add filter to the lookup control
			subgridLookup.addCustomFilter(filterQuery, "contact");

		//Mark the fact that we have already added the filter so that we won't do it again the next time the user clicks the Add button.
		subgridLookup.customFilterAdded = true;

	//Attach the function to retrieve the lookup and apply the filter to the Add button's click event. Remember that we
	//can only get the lookup after the user has clicked the Add button.
	subgridAddButton.addEventListener("click", function() {
		setTimeout(getSubgridLookupAndAddFilter, 200);

Here is another post that uses a similar approach: http://www.bobylog.com/microsoft-dynamics-crm-2015-subgrid-lookup-filter/. This however retrieves the lookup control using a magic sequence of object properties, which differ between versions of CRM, and in my opinion is more prone to breaking in future versions.

Posted in CRM | 1 Comment

Non-admin users cannot see updated group names in form navigation [CRM]

Recently we renamed the group names in an entity’s form navigation. These are the headings that group navigation links to related entities on an entity’s form.


After deploying the solution we found that only users with System Administrator role can see the updated names. Non-admin users still see the old names, even after F5 and Ctrl + F5 to refresh the browser.

I found the answer on this post http://www.magnetismsolutions.com/blog/11-12-09/Changing_Form_Navigation_Group_Names_Dynamics_CRM_2011.aspx. It turns out that a particular privilege is required to see the updated names, and this is the ISV Extensions privilege. You can find this privilege under the Customization tab of the security role editor.

Posted in CRM | Leave a comment