Sunday, August 4, 2019

Guidelines to write good JavaScript code in Microsoft Dynamic CRM




Here is another blog post listing Most Common JavaScript methods for Dynamic 365 CRM


Naming your Web-Resource

Prefix_/EntityName/SpecificPurpose/[version].js

Few examples:
  • msdyn_/SalesInsightsConfig/Resources/Globalization.1025.js
  • new_/invoice/cancelAllContractNotificationOnRenewal.js
  • msdyn_/solutionlayers/static/js/main.js
  • new_/Quote/CreateDuplicateQuote.js

Note: It is important to consider having our own publisher where we can define our prefix to be used in all web-resource.


Commenting your Code

File comment to denote why, when and by whom its been created.

/********************** Source File Header **************************
Project Name: Clinic_ZZZZZ

Creation Date: 4th Feb 2018
Created By: vjCity \ Vipin Jaiswal
Last Modification Date: 27th Feb 2018
Last Modified By: vjCity \ Vipin Jaiswal
Version: 1.0.0.0
Purpose: Common JS Library
********************************************************************/

Going further in the blog you will notice how comments help us in understanding our code better.


Coding Style – Modular vs Object Oriented

When writing any helper class which is going to be used across all entities, I suggest going with Object Oriented way as we get a benefit of having our own namespace. There are two style of having object-oriented JavaScript code:
Explicit Namespace Declaration and using .(Dot) to have classification

// declare the default namespace
if (vjCity === undefined) {
    var vjCity = {};
}
/// The cached user role
var cachedUserRole = new Array();

////////////////////Global Values////////////////////
vjCity.ERRORNotification = "ERROR";
vjCity.WarningNotification = "WARNING";
vjCity.INFONotification = "INFO";

//*******************Dialogs*************************
vjCity.changePasswordDialogId = "C3E7C5CD-AEF7-4DE7-8483-FBDF494F1A04";
vjCity.submitBusinessIdeaDialogId = "1A7A07C8-6B21-48DB-8BB4-1199451086E3";

//*******************Workflows***********************
vjCity.SubmitCommitteeDecisionsWorkflowId = "E2D77408-4A98-43D0-8856-ABEDEB8537D4";
vjCity.MembershipRequest_WorkflowId = "6F327E10-B358-4332-85F4-18D08C16F076";
vjCity.MembershipRequest_TransferToSupportWorkflowId = "5FDAA058-2301-43E6-B82E-7300339529E9";


/*
* Retrieve data
* Id = Id of the record
* type = Entity logical name
* select = fields to be retrieved ex: "new_A,new_B"
* callback = callback function
* example how to call this function :
***********************************************
var obj = Xrm.Page.getAttribute("exkb_client").getValue();
    if (obj === null) return;
    getDataById(obj[0].id, 'exkb_client', 'exkb_clientId, exkb_ClientContact', function(o)
    {
        if(!!o)
            Xrm.Page.getAttribute("customerid").setValue([{id: o.exkb_ClientContact.Id, name:o.exkb_ClientContact.Name, entityType:'contact'}]);
    });
***********************************************
*/
vjCity.getDataById = function (id, type, select, callback) {
    var serverUrl = Xrm.Page.context.getClientUrl();
    var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/" + type + "Set(guid'" + id + "')?$select=" + select;
    var req = new XMLHttpRequest();
    req.open("GET", oDataSelect, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    req.onreadystatechange = function () {
        if (req.readyState === 4) {
            if (req.status === 200) {
                callback(JSON.parse(req.responseText).d);
            }
        }
    };
    req.send();

};


All Code within curly bracket ( { )

// declare the default namespace
if (vjCity === undefined)
{
  var vjCity =
  {
    ////////////////////Global Values////////////////////
    ERRORNotification = "ERROR";
    WarningNotification = "WARNING";
    INFONotification = "INFO";

    //*******************Dialogs*************************
    changePasswordDialogId = "C3E7C5CD-AEF7-4DE7-8483-FBDF494F1A04";
    submitBusinessIdeaDialogId = "1A7A07C8-6B21-48DB-8BB4-1199451086E3";

    //*******************Workflows***********************
    SubmitCommitteeDecisionsWorkflowId = "E2D77408-4A98-43D0-8856-ABEDEB8537D4";
    MembershipRequest_WorkflowId = "6F327E10-B358-4332-85F4-18D08C16F076";
    MembershipRequest_TransferToSupportWorkflowId = "5FDAA058-2301-43E6-B82E-7300339529E9";


    /*
    * Retrieve data
    * Id = Id of the record
    * type = Entity logical name
    * select = fields to be retrieved ex: "new_A,new_B"
    * callback = callback function
    * example how to call this function :
    ***********************************************
    var obj = Xrm.Page.getAttribute("exkb_client").getValue();
        if (obj === null) return;
        getDataById(obj[0].id, 'exkb_client', 'exkb_clientId, exkb_ClientContact', function(o)
        {
            if(!!o)
                Xrm.Page.getAttribute("customerid").setValue([{id: o.exkb_ClientContact.Id, name:o.exkb_ClientContact.Name, entityType:'contact'}]);
        });
    ***********************************************
    */
    getDataById = function (id, type, select, callback) {
        var serverUrl = Xrm.Page.context.getClientUrl();
        var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/" + type + "Set(guid'" + id + "')?$select=" + select;
        var req = new XMLHttpRequest();
        req.open("GET", oDataSelect, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        req.onreadystatechange = function () {
            if (req.readyState === 4) {
                if (req.status === 200) {
                    callback(JSON.parse(req.responseText).d);
                }
            }
        };
        req.send();
    };
  };
}

Modular Approach to JavaScript

This is most straight forward way of coding and we can use this style when we are writing entity specific code and we just need declaration of methods.

An Example:

///
/*
Date created : 10 Jan 2018
Name : Vipin Jaiswal
Last updated : 13 Feb 2018
Purpose : JS Library for Applicant(Contact) Entity
*/


//****************** Global Value ******************************
var entityName = "contact";
var recordId = Xrm.Page.data.entity.getId();

//*************** Form Methods Start ****************************

function form_OnLoad()
{
    SetDocumentFrame("IFRAME_documents");
    CheckMembershipExpiry();
    CheckEstablishment();
    var val = Xrm.Page.getAttribute("address1_postofficebox").getValue();
    Xrm.Page.getAttribute("address1_postofficebox").setValue(ValidatePOBox(val));
}

function form_OnSave()
{

}

//************ Ribbon Methods ***********************************
function changePasswordCallDialog()
{
    //Call the change password dialog
    Alert.showDialogProcess(changePasswordDialogId, entityName, recordId);
}
function bulkCreateCommitteeSessions()
{
    // Call the bulk create committee sessions
    Alert.showDialogProcess(bulkCreateCommitteeInstances, entityName, recordId);
}

//************* On Change Methods *************************
function EmploymentStatusOnChange() {
    CheckEstablishment();
}
function EmariteIdOnChange() {
    ValidateEmiratesId(Xrm.Page.getAttribute("kfexc_emiratesid").getValue());
}
function PassportExpiryDateOnChange() {
    var passportExprity = Xrm.Page.getAttribute("kfexc_passportexpirydate").getValue();
    if ((passportExprity !== null || passportExprity !== undefined) && vjCity.dateIsLater(Date.now(), passportExprity)) {
        vjCity.showFormNotification("Passport is Expired", vjCity.WarningNotification, "1");
    }
    else
        vjCity.clearFormNotification("1");
}

function BirthdateOnChange() {
    var birthdate = Xrm.Page.getAttribute("birthdate").getValue();
    if ((birthdate !== null || birthdate !== undefined) && vjCity.dateIsLater(birthdate, Date.now())) {
        vjCity.showFormNotification("Birth Date is in the future", vjCity.WarningNotification, "3");
    }
    else
        vjCity.clearFormNotification("3");
}
function MobileNumberOnChange() {
    var mobNumber = Xrm.Page.getAttribute("mobilephone").getValue();
}
function HomeNumberOnChange() {
    var Number = Xrm.Page.getAttribute("address1_telephone1").getValue();
    vjCity.ValidateMobileNumber(Number, "address1_telephone1");
}


//
//*************** Business Validation Methods **************

function ValidateEmiratesId(txt) {
    if (txt === "")
        return;
    var patt = new RegExp("^[0-9]{15}$");
    var res = patt.test(txt);

    if (!res || !txt.startsWith("784")) {
        vjCity.showFieldNotificiation("kfexc_emiratesid", "Emirates Id format is invalid");
    }
    else {
        vjCity.clearFieldNotification("kfexc_emiratesid");
        var a = "";
        for (var i = 0; i < txt.length ; i++) {
            switch (i) {
                case 2:
                    a = a + txt[i] + "-";
                    break;
                case 6:
                    a = a + txt[i] + "-";
                    break;
                case 13:
                    a = a + txt[i] + "-";
                    break;
                default:
                    a = a + txt[i];
            }
        }
        Xrm.Page.getAttribute("kfexc_emiratesid").setValue(a);
    }
}

function ValidatePOBox(val)
{
    if (val !== undefined && val != null)
        return val.replace("-", "");
    return "";
}


I hope there are better approach to have perfect coding style, please do let me know if you came across any in comments.

Thanks,
Vipin Jaiswal
vipinjaiswal12@gmail.com


Saturday, August 3, 2019

Dynamic CRM keeps asking for credentials


You are prompted for your username and password when you open Microsoft CRM or while you are even browsing dynamic CRM.

Before we start troubleshooting, check if this is happening even in In-Private or Incognito mode of the browser also.

There could be multiple reason for this, lets look at few of them in the order listed here

1) Incorrect credential cached in Credential Manager
Your Windows system stores user credentials on your computer. If the cached credentials are incorrect, you will be prompted for password. This issue usually happens after the password for your domain user account is changed. Before your password changed, you saved your credentials. The stored credentials are not overwritten when CRM triggers the authentication prompt even if you enable the Remember my credentials option.

To fix this issue, you need to remove the corrupted credentials, follow these steps:

1. Click Start, click Control Panel, and then click Credential Manager.
2. Locate the set of credentials that has Dynamic CRM in the name.
3. Click the name to expand the set of credentials, and then click Remove from Vault.


2) Adding the Microsoft CRM Web site to the list of local intranet sites in Internet Explorer

1.     Start Internet Explorer.
2.     Click Tools, click Internet Options, and then click the Security tab.
3.     Click Local Intranet, click Sites, and then click Advanced.
4.     Add the Microsoft CRM server name, the Microsoft CRM server fully qualified domain name (FQDN), and any host header or alias names that you created for the Microsoft CRM URL.
5.     Click Close.

What is Hierarchy Security Model in Dynamic 365 CRM


Microsoft Dynamic CRM has introduced additional hierarchy security model that can be use with existing security model that are business units, security roles, sharing, and teams. It offers a more granular access to records for an organization and helps to bring the maintenance costs down. There are two types of it, lets look at them in details.

In Manager hierarchy, a manager must be within the same business unit, or in the parent business unit, to have access to the data.

Manager’s and the report’s relationship are established by using the Manager field on the system user entity.



Note: If a direct report has deeper security access to an entity than their manager, the manager may not able to see all the records that the direct report has access to.

Position hierarchy allows data access across business units. It is not based on the direct reporting structure, like the Manager hierarchy.

A user can be tagged only with one position in each hierarchy, however, a position can be used for multiple users.

Users at the higher positions in the hierarchy have access to the data of the users at the lower positions, in the direct ancestor path.


With the Position hierarchy security, a user at a higher position has access to the records owned by a lower position user or by the team that a user is a member of, and to the records that are directly shared to the user or the team that a user is a member of.

More on Sales life cycle in Dynamic 365 CRM


How to filtered records by logged in user team


Problem Statement
Need to create a view for Lead/Account/Opportunity entity that is filtered by the logged in user's Business Unit/Team/Reporting Hierarchy.


Solution 1
There are various options that are present in Advanced Find to filter opportunities, we should try understanding them and design our CRM accordingly so that we do not require more customization. Lets first have a look at it.




A] Equals Current User
It simply states that listing opportunities whose owner field is populated with current logged-in user only.

B] Does Not Equal Current User
If current user is having Organizational or Business Unit level access to opportunity record, a user can see all the opportunities respectively. If user is interested in viewing other user’s opportunities record that do not directly belong to him can select this view.

C] Equal Current User Or His Reporting Hierarchy
To understand the option “His Reporting Hierarchy”, we must first understand Hierarchy Security Model in Microsoft Dynamic CRM.
Selecting this will list all records which either directly belongs to the user or belongs to the subordinate user which are reporting under him.

D] Equals Current User’s Team
A user can be a part of one or multiple teams. (Refer Alex in below image as he is a part of both Sales and marketing team.
A team can have multiple users.
This selection will list records which directly belongs to any team which a current user is a part of.
For example: Alex can see records for both Sales and Marketing teams, where as Marco can see records of only Marketing team.


E] Equals Current User or User’s Team
This selection will list out records which either directly owned by the current user or records which belongs to the team which he belongs to.

F] Equals Current User And His Teams Or His Reporting Hierarchy And their Teams
It’s a combination of all the above selection which list out records which belongs to current users and records belongs to any team which a user part of or records which are owned by user which comes in his reporting hierarchy.


Solution 2
We can use Owing user as linked entity to get to the records which belongs to the user current business unit. This will restrict the records getting rendered that do not belongs user business unit.




Friday, July 19, 2019

The email must have at least one recipient before it can be sent.



This is the most common exception in Dynamic CRM when sending an email using a workflow. There could be multiple reason for this exception to occur. 

In this blog post I will be discussing how to troubleshoot and identify possible cause for such an exception.

It is only about Recipient (To, CC or BCC)

We have nothing to do with From section of an email, otherwise you will get different error when sending an email. We only need to focus on recipient of an email.

'To' is mandatory among all Recipient.



In workflow designer you might skip To and set only CC or BCC alone or set both CC and BCC, but in run-time you will get an exception.


Recipient entity without an email address


It is always better to check if email field is populated or not in a workflow before we  try to sent an email to either Contact, Account, Lead etc. 

If your business requires sending an email to such entities why not make email as mandatory field.


In above workflow we are verifying if respective entity (Contact in this context) has Email field populated, otherwise we are notifying CRM Admin or Business Owner about missing email address.

Contact Preference set to - Do Not Allow.


Even if Contact, Lead or Account have a valid email address populated in its email field, CRM workflow engine will not consider this as valid recipient if its contact preference is set to Do Not Allow. 

So it is a good practise that we should always verify such conditions in our workflow steps before we send out an email.



Hope it Helps
Vipin Jaiswal