Wednesday, 21 June 2017

{know-how} Or condition between linked entities or multiple entites in MSCRM Fetchxml

I have seen many struggling to achieve an OR condition between filters in parent entity and the linked entity. So today lets see how to overcome this issue and how to achieve an OR condition spanning between multiple entities.

I want to select an account with specific phone number or its primary contacts phone number is equal to the given number

In this scenario we may not able to form an or condition for the filters as the filters are split between the parent(account) and the linked entity(contact) in advanced find editor. But the same can be achieved in fetchxml.

Fetchxml supports conditions from other linked entities, the trick is to use an attribute called entityname in condition node to specify which entity it links to. The same is highlighted below.

<fetch version="1.0" output-format="xml-platform" mapping="logical" >
    <entity name="account" >
        <attribute name="accountid" />
        <filter type="or" >
            <condition attribute="telephone1" operator="eq" value="1234" />
            <condition entityname="contact" attribute="telephone1" operator="eq" value="1234" />
        <link-entity name="contact" alias="contact" from="contactid" to="primarycontactid" />

Hope this helps!

{know-how} Set a lookup value on create/update of a record using MSCRM WebApi - An undeclared property Error

Recently faced an error while creating and updating records in CRM using WebAPI. The issue was around setting a lookup value and following is the error message

An undeclared property new_primaryincident which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.

The issue is due to the fact that whenever we set a lookup value we need use schema name and not the logical name. In my case I had to use "new_PrimaryIncident" instead of  "new_primaryincident".

Code snippet:

// code with issue

// code after fix

Hope this helps!

Tuesday, 20 June 2017

{know-how}MSCRM open external url using Xrm.Utility.openWebResource - D365

Hello All,

Good to be back with another know-how post, lets see how to open an external url using Xrm.Utility.OpenWebresource

On click of search ribbon button in account form of CRM, open an external url(bing search) using Xrm.Utility.openWebResource

Why to use Xrm.Utility.openWebResource is not a supported method to open a webresource

  1. Open a custom HTML webresource using openWebResource method and pass the encoded external URL as query string parameter
  2. In the webresource, redirect to the encoded URL in  parameter.

Steps and code explanation: 
  1. Create a custom HTML webresource(use the code below).
  2. Onload of page, call a js function named getParameters.
  3. The function will retrieve the encoded URL available in query string
  4. Then it will redirect to the encoded external URL(Bing search)

Code snippets

To open Webresource:
var customParameters = encodeURIComponent("<URL goes here>");
Xrm.Utility.openWebResource("ram_webContainer.html", customParameters)

HTML webresource named ram_webContainer.html:

<!DOCTYPE html>
    <meta charset="utf-8" />
    <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
    <script type="text/javascript">
        var CRMCustomParameters = [];
        var getParameters = function () {
            var Parameters = GetGlobalContext().getQueryStringParameters();
            if (Parameters && Parameters.Data) {
                location.href = Parameters.Data;

<body onload="getParameters()">


Hope this helps!

Friday, 16 June 2017

{know-how} Editable grid disable fields conditionally using Javascript - Dynamics CRM D365 - D365_EditableGrid#1

Editable grid is an awesome way to manage related child records effectively and efficiently within few clicks and I personally love it for the same. For this kind of requirements, building a custom grid was the story for long time and now Editable grid is a real savior.

Before deep diving into code , below are the supported JavaScript events for editable grid. 

Scenario: In account form we have contact editable grid. Whenever the account name is DisableFields(felt lazy to find another field :P), disable all the fields in the editable grid row.

Event Registration:
  1. Open form editor and then open editable grid properties
  2. Navigate to Events tab and select Event named OnRecordSelect
  3. Add a function to the event.While adding function do not forget to enable "Pass execution context as first parameter"

Code Explanation:
To access the current row(entity record) we need the editable grid's formcontext which is a part of the context passed as first parameter. From there the rest of the code is similar to our traditional js implementations. 

function setFieldsDisabled(context) {
    var name = Xrm.Page.getAttribute("name").getValue();
    if (name == "DisableFields") {
        var contact = context.getFormContext().data.entity;
        contact.attributes.forEach(function(field, i) {

Hope this helps! 

Friday, 9 June 2017

Mobile compatible development - disable all fields using JS - Microsoft Dynamics CRM - MoCA_Tip#3

Hello All,

Lets go though a quick tip on best practice around disabling all fields using JavaScript in MoCA.

In traditional CRM JS development, we tend to use  getDisabled function to identify whether a control is disabled or not and setDisabled to enable or disable a field.

But in MoCA there are some controls which do not expose the above functions which result in JS error(not defined or not found).

Before calling the function validate whether the function exist or not  and then call the same. By this way we can avoid unnecessary chaos in our JS.

Code Snippet:

if (control && control.getDisabled && !control.getDisabled()) {

Refer this blog for MoCA compatible disable all fields script

Don't forget to go through previous tips if you have missed,
  1. Form Selector and its usage

Monday, 29 May 2017

Mobile compatible development - formSelector - Microsoft Dynamics CRM - MoCA_Tip#2

After the MoCA wave with D365, we are rapidly evolving in mobile space. This evolution demands mobile compatible development and the same is our key to success.

I have planned to share my experience with MoCA as a series and the link for previous tips can be found at the end of this blog.

lets jump on to the tip now,

Its common to have Xrm.Page.ui.formSelector in our JavaScript development and the same is used to identify current form and for form navigation.

Xrm.Page.ui.formSelector is not supported in mobile!
In MoCA formselector is not available and usage of the same will result in form error. This is because mobile application doesn't have multiple forms. 

From MSDN Library:
Dynamics 365 for phones and tablets does not provide the capability to switch between forms. If you have more than one main form for an entity, the one displayed depends on the form order set and which security roles are assigned to the form.

Ways to overcome this issue,
  1. Preferred solution is to avoid using multiple forms 😉  - This may sound crazy, but its better to design the main form in a way that everything fits into it. This automatically streamlines all your form related development mobile compatible. 
  2. Another way is to conditionally avoid form selector piece of code by validating the client. If the client is mobile skip the specific portion of code, sample code snippet is as follows

if (Xrm.Page.context.client.getClient() != "Mobile")
    //Form selector code goes here


Don't forget to go through previous tips if you have missed,
  1. Document template Fix
  2. Hidden tabs and Mobile application organization settings

Happy learning!

Thursday, 25 May 2017

MSCRM - Email Tracking token understanding and configuration

In this article we are going to understand the purpose, configuration and tracking of the Email tracking token.

What is tracking token and why we need it?

Whenever an email is sent via CRM, a tracking token is suffixed to subject line by default and it is used for email tracking and correlation purpose.

This helps in auto mapping/matching related conversations to the regarding object. If its turned off, then we may need to compare key words in subject, sender and receiver to find the best match and this results in reduced probability.

Example Tracking Token: CRM:00010001

Should we disable tracking token?

Sometimes tracking tokens may cause confusion around the subject of the mail and we may need to get rid of it . But disabling tracking token affects the accuracy of email tracking and its not recommended by Microsoft.

In such situations we can update the prefix to a more meaningful one, like

  • TrakingToken:00010001
  • Tracking#00010001 
  • #00010001
Note from Microsoft website
Tracking tokens are the only supported correlation method that can be used when you use Dynamics 365 for Outlook connected to an SMTP server and send email to a non-Exchange recipient. In this situation, if tracking tokens are not enabled, then correlation events, such as the automatically creating records based on the regarding object, may not work.

The tracking token is configurable under Email tab in System Settings,

For more information refer below link - Old article but the content is perfect

Tuesday, 23 May 2017

MSCRM - Retrieve more than 5000 records using FetchXML - Simplified

I was working on a piece of C# code to retrieve more than 5000 records using Fetchxml. This may get bit tricky, so tried to simply the same as much as possible in the below post.

By default an organization service can return only the first five thousand records and page details for the next set of records, if exists.

The result entity collection exposes a Boolean attribute called MoreRecords, it will be true if more records available else false.

If more records available then we need to use the combo of pagingcookie and page(pagenumber) to retrieve rest of the records.

**Do not forget to add {0} in fetchxml which is used to include page details in below code

Code Snippet:

        public List<Entity> RetrieveAllRecords(IOrganizationService service, string fetch)
            var moreRecords = false;
            int page = 1;
            var cookie = string.Empty;
            List<Entity> Entities = new List<Entity>();
                var xml = string.Format(fetch, cookie);
                var collection = service.RetrieveMultiple(new FetchExpression(xml));

                if (collection.Entities.Count >= 0) Entities.AddRange(collection.Entities);

                moreRecords = collection.MoreRecords;
                if (moreRecords)
                    cookie = string.Format("paging-cookie='{0}' page='{1}'", System.Security.SecurityElement.Escape(collection.PagingCookie), page);
            } while (moreRecords);

            return Entities;


            var fetch = "<fetch {0}>" +
                        "    <entity name='accounts' >" +
                        "        <attribute name='accountid' />" +
                        "        <attribute name='name' />" +
                        "    </entity>" +
            var accountCol = RetrieveAllRecords(service, fetch);

SSRS shared dataset deployment error - The feature: "Shared dataset" is not supported in this edition of Reporting Services.

Today I was deploying reports using visual studio and faced a weird error while creating shared dataset. The error is as follows

The feature: "Shared dataset" is not supported in this edition of Reporting Services

After a bit of analysis found that issue is related to the edition of SQL Reporting server. Only certain editions of SQL server supports shared datasets and the rest doesn't.

Refer this Microsoft article for more information.

The following are the editions that should not support shared datasets
  • Web
  • Express with Advanced Services
  • Express with Tools
  • Express

and the below are the one's which should support the same
  • Enterprise
  • Standard
  • Developer

Friday, 19 May 2017

C# - Null conditional operator - Null check with question mark to handle null reference exception

Hello All,

Its good to meet you with yet another exciting tip and this time its around C#. With C# 6.0 there are many handy features introduced when it comes to day to day development.

One such feature is  Null conditional operator. ?

Personally during c# development, I always felt that in C# we lack better null condition handlers and I had to develop my own extensions to handle the same. But the situation is upside down now and I am loving this new null conditional operator.

Lets go through a quick example with code snippet

Consider the following function where we are trying to replace a value in a string, here we handle null in a conventional way

        private string StringReplaceTest(string input)
            if (input == null) return null;

            return input.Replace("1", "2"); 

With the latest version, we got our handy way to handle the null's and below is the updated code,

        private string StringReplaceTest(string input)
            return input?.Replace("1", "2"); 

Hope this helps.

MSCRM - Retrieve optionset label - RetrieveAttributeRequest - optionsetmetada - C#

Hello All,

Below is a quick code snippet that can retrieve picklist label based on value,

private string GetOptionsSetTextOnValue(IOrganizationService service,string entityName, string attributeName, int option)  
       RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest  
         EntityLogicalName = entityName,  
         LogicalName = attributeName,  
         RetrieveAsIfPublished = true  
       RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);  
       PicklistAttributeMetadata attributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse?.AttributeMetadata;  
       if (attributeMetadata == null) return string.Empty;  
       var currentOption = attributeMetadata?.OptionSet?.Options?.FirstOrDefault(x => x.Value == option);        
       return currentOption?.Label?.UserLocalizedLabel?.Label != null ? currentOption.Label.UserLocalizedLabel.Label : string.Empty;  

To know more on conditional operator  with question mark, please refer

Friday, 12 May 2017

MSCRM - Microsoft Dynamics CRM BIDS Extension Setup has stopped working - Reporting authoring extension installer failure - windows 10

A quick tip to solve report authoring extension installation issue which results in installer crash. It was hard to find the root cause as error was not specific.

Tried multiple things such as compatibility mode, visual studio shell extension installation and many other workarounds and nothing worked. Finally found that the issue was with RunOnce registry key.

Note: The below solution should also fix "Setup cannot continue because there is a pending restart required. Restart the computer and then try running Setup again" error

Solution :
If we delete this registry key(back-up before delete),  the installer will work fine

Possible Registry Key Locations:
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
  • HKEY_CURRENT_USER\Software\Microsoft\Windwos\CurrentVersion\RunOnce
  • HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce

Saturday, 6 May 2017

MSCRM - FetchXML filter based on time and time zone

Recently came across a scenario where we had to query CRM and retrieve accounts based on UTC date. After a fair bit of research, came-up with a Fetch query that can retrieve records based on time and time zone filters.

The key part in querying is the ISO 8601 format to specify the date time with timezone.

In the below date, +00.00 stands for UTC Time Zone and we can use any timezone by modifying this part.

Below is a sample fetchxml, which retrieve records with modifiedon greater than or equal to given UTC datetime.

Note: Use 'greater than or equal to' or 'lesser than or equal to' instead of 'on or before' or 'on or after'

   <entity name="account" >  
     <filter type="and" >  
       <condition attribute="modifiedon" operator="ge" value="2017-05-05T22:03:19+00:00" />  

To filter time based on user's timezone remove the timezone part(+00:00) from the query and the sample will look like below,

   <entity name="account" >  
     <filter type="and" >  
       <condition attribute="modifiedon" operator="ge" value="2017-05-05T22:03:19" />  

Hope this helps!

Friday, 5 May 2017

MSCRM - Entity not available in post configuration

Hi All,

I have seen lot of queries around entity not available in post configuration(Activity feed configuration).

By default CRM doesn't refresh the post configuration entities, we need manually refresh to view the latest entities.

To manually refresh, hit the refresh ribbon button and it should solve the issue

Tuesday, 2 May 2017

MS CRM - Xrm.Page.getAttribute("attribute").fireOnChange() - #JSTip4

Hello All,

In our Xrm clientside object we have an method called fireOnChange(),

Purpose and Usage:
Triggers onchange event of the specific attribute, which in turn triggers the JavaScript functions attached to it.

  • At times, based on business needs we may need to execute a JS logic pinned to field on demand, where this function comes handy.
  • Script updates to a field will not trigger onchange of that field. We can use this way to trigger onchange event of the field if needed. 
In account form, we have address fields and on change of address fields there is a logic to populate shipping address. Now when we add a primary contact consider the address fields should be updated from contact address. In this scenario, using JS if we update address fields the shipping address functionality tied to address fields will not fire. This is where we need to use fireOnchange.

Code Snippet:

MS CRM - A currency is required if a value exists in a money field. Select a currency and try again - #CRMTip

Hello All,

Good to be back with another quick tip regarding currency and money fields.

Many of us might have experienced issues with money and currency fields, In this post we are going to learn a best practice and fix for one of the money or currency issues

A currency is required if a value exists in a money field. Select a currency and try again

Steps to replicate:
Open an existing CRM record without currency value populated, now enter data into any of the money fields and you will experience the above error.

Root Cause:
Money fields are currency dependent and when the currency is empty, its obvious that money is invalid.

Quick fix:
Populate currency field and it will fix the issue.

Best practice:
Make sure that currency field is always populated during create/update via workflow/plugin. If any custom logic is used to select currency, default a currency if no match found.

Thursday, 13 April 2017

MS CRM - Better way of Hiding or Disabling a field in Form - #JSTip3

Hello All,

Lets go through a quick development tip regarding hiding or disabling an attribute using JavaScript,

To hide or disable a field in CRM, its very common to use Xrm.Page.getControl. Though the method is very handy it has its own restrictions.

Xrm.Page.getControl - Not the best way
This function will return only the first occurrence of the specific attribute in the form.

Consider we have statecode attribute at multiple area's of a form, In this scenario getcontrol can handle only the first occurrence of this attribute, which affects the robustness of the solution.

Instead of using getControl we can use getAttribute.controls to hide all the fields related to a particular attribute.

Here we select the attribute, then we loop through all the controls available for that attribute and we are hiding them.

Sample code snippets are as follows,

Usual Way:

Best way:
        function (control) {

Saturday, 8 April 2017

MS CRM Plugin - IPluginExecutionContext InitiatingUserId and UserId - #PluginTip2

Hello All,

Glad to meet you with another tip, In plugin execution context we have two attributes which points to user record with which we can create organization service. Both the attributes are of type EntityReference and at the end of this post you will have good idea on what is the difference between them and when to use specific attribute.

This is the user who performs the operation that triggers the plugin. If USER-A creates a record and a plugin is triggered on record create then the Initiatinguserid is USER-A.
This contains the "run in user's context" users id that is set as a part of plugin step creation. If the value is not set, then it equivalent to Initiatinguserid
In below code, we have created orgservice with both user entityreference's
Example code:
 IPluginExecutionContext context = (IPluginExecutionContext)  
 IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));  
 IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);  
 IOrganizationService intiatingUserService = serviceFactory.CreateOrganizationService(context.InitiatingUserId);  

Example Scenario's
Scenario - 1
USER-A executes a plugin step without  "run in user's context".
Initiatinguserid/Userid  = USER-A
Scenario - 2
USER-A  executes a plugin step with  "run in user's context" as USER-B
Initiatinguserid = USER-A
Userid = USER-B

Hope this helps!
Also check out my blog on plugin depth

Wednesday, 5 April 2017

MS CRM - IPluginExecutionContext.Depth a detailed look - #PluginTip1

Today, we are going to have a detailed look on the depth property available in plugin or workflow context. By the end of this post, you will have enough knowledge to decide when to use depth and how to use it wisely.

Depth property is used to find the position of the plugin in current call stack. To be simple, with this property we can find whether the plugin is triggered by another process(plugin/workflow) or directly by platform/user.

Default depth value is 1. 

If plugin depth is greater than 1, then it is triggered by another process. Depth of the plugin is incremented by 1, if called by another process.

There is a myth around depth, that it can be used to break infinite loops. Yes they can, but these checks may become dangerous and may skip your plugin logic at times. For example, If a plugin from account triggers a plugin in contact, the depth in contact plugin is 2 and that is not an infinite loop.

Example 1:
Lets take an example for infinite loop,
On an account update(post-operation) we have a plugin and this plugin updates the account again, This update triggers the same plugin again.

Here for the first time depth would be 1 and from then on every time it will be incremented by 1. So to avoid loop, we should to check the depth but personally I don't prefer using depth here.

Example 2:
Lets take an example for parent child,
On an account update post-operation we have a plugin and this plugin updates a contact record which in-turn triggers another plugin. If we may need to restrict the plugin execution on contact, only when there is a direct operation on contact and not from account. We can use depth to achieve this.

Here for the first plugin depth would be 1 and for the child/triggered plugin the depth would be 2. You can use depth validation to exit the plugin,

Be wise when using depth validation!

Feel free to comment your views, hope this post is informative.

Also check out my blog on IntitatingUserId and UserId

Tuesday, 4 April 2017

Mobile compatible development - Microsoft Dynamics CRM - MoCA_Tip#1

After the release MoCA, I was interested in exploring the functionalities available and I am happy with the available features.

Now, we are going to see some tips based on my previous experience with MoCA. I will try to provide some more tips in upcoming blog posts,

Behavior of hidden tabs
  • ·        CRM web forms ignore hidden tabs when they are loaded in Mobile. Therefore, if you have any logic based on hidden section fields then those logics are going to break.
  • ·        Make sure the tab is visible on form. Then hide the same using JavaScript, this will make the tab and fields available on form.

Error with field's customized event – Random errors on specific forms
  • ·        This error is common on the forms, which contains multiple tabs/sections/fields, and the errors are random and not specific to any functionality.
  • ·        This is because, we have limits on the count of controls available on mobile form and these are configurable in orgsettings

The default and max allowed items for a mobile form is as follows,

Default Value
Max Value

Sunday, 2 April 2017

MS CRM - Refresh Form - #JSTip2

In the latest version of CRM, there were situations where we need to refresh the whole form instead of refreshing date using

To achieve conventional refresh, we can use openEntityForm available in Xrm.Utility. This method reopens the record in a conventional way which is equivalent to full refresh.

Code snippet for the same is as follows

function refreshForm() {;

Wednesday, 29 March 2017

Disable the Script Error Notifications in MS Dynamics CRM 365

we need to set the following setting under Settings=>administration=>privacy preferences

Monday, 27 March 2017

MS Dynamics 365 CRM referesh composite address field - #JSTip1

I have found a quick hack(dirty way) to refresh composite fields based on other address fields in the form using direct DOM manipulation, below is the sample and explanation.

1. Go to the parent window in the java script
2. Trigger a click on address field which pop's up the address 
3. Close the pop-up which will refresh data.


Enclose them into a try catch block for soft exit. For closing and reopening the window, use the second statement before calling the first and second statements.

Sunday, 26 March 2017

Microsoft Dynamics 365 Mobile(MoCA) - Metadata Error(Metadata corrupted - Error_Message_Generic_Mobile_Client ErrorDialog.ProvideTechnicalDetails)

Hello All,

Lets go through a quick fix for a type of Metadata Error in Microsoft Dynamics Mobile Application (MoCA). 

In one of our recent projects, we faced a metadata error in MoCA application out of no where. After spending hours around this issue and with the timely support of MS team, we were able to find the root cause and fix,

Issue Summary is as follows,

Issue: While opening mobile app, the app crashes with an error Error_Message_Generic_Mobile_Client ErrorDialog.ProvideTechnicalDetails

This error can be caused because of multiple reasons, In our case we used logs and browser's developer tool errors to identify the issue is around MSCRM Document templates.

This occurs whenever you delete an entity from CRM and it has an associated document template. When MoCA builds metadata, it was trying to retrieve a document template of a deleted entity that results in a null reference error.

Identify the document template related to the deleted entity and remove the same from the system.

Hope this helps!

Friday, 3 February 2017

MSCRM - Disable all fields using javascript - Make fields read only

Hello all,

Below is a simple JavaScript  function that can disable all fields in a form by iterating through controls.

The below code is mobile(MoCA) compatible, so feel free to use it even on mobile based JavaScript development.

    function disableAllFields() {
        Xrm.Page.ui.controls.forEach(function (control, i) {
            if (control && control.getDisabled && !control.getDisabled()) {

Thursday, 26 January 2017

MS CRM - How to find a plugin is synchronous or Asynchronous - SdkMessageProcessingStepMode

At times, we may need to find whether the current plugin step is executing synchronous or asynchronous via code.

We can use the property called mode in IPluginExecutionContext to identify the same.

Code snippet:
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if(context.Mode == SdkMessageProcessingStepMode.Asynchronous)

Monday, 23 January 2017

MS CRM Online - #SSRSTip1 - Fetch Data Source and Connection String

Hello All,

Lets learn a quick tip regarding fetch based SSRS report development. With CRM online, FetchXml is the primary option to retrieve data from CRM.

This tip deals with Fetch data source connection string and best ways to avoid issues with connection string.

While developing a new Fetch based report, the fetchxml datasource connection string should be the server URL. In most cases, with server URL the report works as expected.


But at times while debugging from local, we may face weird issues like
  • No data retrieved for a valid query
  • Field not available error for a valid query
  • Entity not available error for a valid query
Sometimes these fetch data sources may point to some first instance in the group of organizations instead of the one specified in URL.

Use the organization unique name with connection string which will fix the issue.

The organization unique name will be available in Developer resources under Settings => Customization

In the following sample, contoso is my org unique name

Hope this helps!