Tag Archives: d365

Microsoft Dynamics 365: Counting Sub-grid Records and Enabling Users to Hide Empty Sub-grids

In Microsoft Dynamics 365, we can use sub-grids to present data to users in a tabular format. This is a nice and compact way of displaying data. However, sometimes there is no data in those sub-grids to display and the end users might prefer to get back that space and optimize the space on the form. In this blog post, we cover how we can dynamically obtain the number of records in a sub-grid using JavaScipt and use that information to give end users the flexibility to optimize the space on forms by hiding empty sub-grids.

There are two types of sub-grids on Dynamics 365 forms:

  • Read-only sub-grids: Show data in a tabular format but do not allow users to edit data directly on the sub-grid. To edit the data, users have to double click on the record in the grid to open the form, edit the data, and then save it.
  • Editable sub-grids: Apart from showing data in a tabular format, editable sub-grids offer rich inline editing capabilities on web and mobile clients including the ability to group, sort, and filter data within the same sub-grid so that you do not have to switch records or views. In addition to providing all these extensive editing capabilities, editable sub-grids still honor the read-only sub-grid metadata and field-level security settings as well as the general Microsoft Dynamics 365 security model.

Summary of the key syntax

Here is a high-level summary of the main Microsoft Dynamics 365 JavaScript syntax covered in this blog post.

  • Count the number of records in sub-grid, where <subgridName> is the logical name of the sub-grid :
    formContext.getControl("<subgridName>").getGrid().getTotalRecordCount();
  • Remove the blank option in an option set, where <optionsetName> is the logical name of the option set:
    formContext.getControl("<optionsetName>").removeOption("");
  • Get the option set’s selected value , where <optionsetName> is the logical name of the option set:
    formContext.getAttribute("<optionsetName>").getValue();
  • Set the selected value of an option set, where <optionsetName> is the logical name of the option set and <value> is the value the option set will be set to:
    formContext.getAttribute("<optionsetName>").setValue("<value>");
  • Enable/Disable a field, where <fieldName> is the logical name of the field and <Boolean> can be true or false (i.e. true disables field and false enables it):
    formContext.getControl("<fieldName>").setDisabled(<Boolean>);
  • Hide/Unhide section, where <nameOfTab> is the name of the tab containing the section, <nameOfSection> is the name of the section and <Boolean> can be true or false (i.e. true makes the section visible and false hides the section):
    formContext.ui.tabs.get("<nameOfTab>").sections.get("<nameOfSection>").setVisible( <Boolean>);

Application Example: Enabling Users to Hide Empty Sub-grids

Using the code below, we can give end users the flexibility to optimize the space on forms by hiding empty sub-grids. In the code below, the hideEmptyOfficesSubgrid function is the entry point and is called when saving the form and loading the form.

function hideEmptyOfficesSubgrid(executionContext) {  
    var formContext = executionContext.getFormContext();
    var operationsTabName = "tab_operations";
    var officeGridSectionName = "office_grid_section";
    var officeGridName = "office_subgrid";
    var enableOfficeGridName = "hos_enableofficesgrid";
    var no = 183840000;
    var yes = 183840001;
    formContext.getControl(enableOfficeGridName).removeOption(""); 

    setTimeout(function () {
        if (formContext.getControl(officeGridName) != null && formContext.getControl(officeGridName) != undefined) {
            var count = formContext.getControl(officeGridName).getGrid().getTotalRecordCount();
            var enableOfficeGrid = formContext.getAttribute(enableOfficeGridName);
            var enableOfficeGridCtrl = formContext.getControl(enableOfficeGridName);
            var officeGridSection = formContext.ui.tabs.get(operationsTabName).sections.get(officeGridSectionName);
            disableSubgridControlField(count, enableOfficeGridCtrl);
            hideEmptySubgrid(count, enableOfficeGrid, officeGridSection, no, yes);
        }
    }, 5000);      
}

function disableSubgridControlField(count, subgridCtrlField) {  
    if (count <= 0) 
        subgridCtrlField.setDisabled(false);       
    else if (count > 0) 
        subgridCtrlField.setDisabled(true);
}

function hideEmptySubgrid(count, subgridCtrlField, subgridSection, no, yes) {  
    if (areTheseTwoInputsIdentical(subgridCtrlField.getValue(), yes)) 
        subgridSection.setVisible(true);       
    else if (count <= 0 && (areTheseTwoInputsIdentical(subgridCtrlField.getValue(), no) || subgridCtrlField.getValue() == null)) 
        subgridSection.setVisible(false);
    else if (count > 0 && areTheseTwoInputsIdentical(subgridCtrlField.getValue(), no)) {
        subgridCtrlField.setValue(yes);
        subgridSection.setVisible(true);
    }
}

function areTheseTwoInputsIdentical(input1, input2) {
    if (input1 == input2) 
        return true;
    else 
        return false;
}

How the code works

In the first image below, the account record is not enabled for Offices (i.e. the value of Enable Office Grid option set is No). Therefore, Offices grid is empty and hidden.
Account record not enabled for Offices sub-grid

After enabling the account record for Offices by changing the value of the option set field, “Enable Offices Grid” to Yes, the Offices sub-grid shows up and we can add offices to the sub-grid as shown below. The “Enable Offices Grid” field controls the appearance and disappearance of the Offices sub-grid.
Account record enabled for Offices sub-grid

As shown in the image above, the Enabled Office Grid option set is locked as soon as we add and save records to the Offices sub-grid. This prevents a scenario of logic inconsistency where an account record has offices in it’s sub-grid and the user proceeds to change the value of the Enable Offices Grid field to No. Therefore, the Enable Office Grid field value can only be changed back to No and hide the Offices grid after the sub-grid emptied up and there are no more records in it. Therefore, using the solution above, end users can be empowered with the option of hiding empty sub-grids and optimize the space on the form.

Microsoft Dynamics 365: Varying Form Behavior On Form-type and Save-mode

Microsoft Dynamics 365 offers the ability to vary the behavior of forms based on the form type and how the form is saved, using JavaScript. In this blog post, we cover how we can make use of this flexibility offered by the platform to deliver unique solutions for end users.

Summary of the key syntax

Here is a high-level summary of the main Microsoft Dynamics 365 JavaScript syntax covered in this blog post.

  • Getting the type of form:
    formContext.ui.getFormType();
  • Hide a tab on a form (where “TabName” represents the name of the tab you would like to hide):
    formContext.ui.tabs.get("TabName").setVisible(false);
  • Get the object with methods to manage the Save event:
    executionContext.getEventArgs();
  • Get the form Save Mode:
    executionContext.getEventArgs().getSaveMode();
  • Inhibit the default save behavior on a form
    executionContext.getEventArgs().preventDefault();
  • Check if the default save behavior was inhibited
    executionContext.getEventArgs().isDefaultPrevented();
  • Get the form context
    executionContext.getFormContext();

Form Type

To get the Form Type, you use the following JavaScript code:

formContext.ui.getFormType();

Here are the different Dynamics 365 form types and their respective JavaScript return values:

Form type Return Value
Undefined0
Create1
Update2
Read Only3
Disabled4
Bulk Edit6

Application Example: Varying form behavior on Form Type

In this application example, we will hide the Products and Services tab on the Create type form (with JavaScript Return Value = 1). However, it will be still be visible on all other applicable form types. This prevents users from adding information to the Products and Services tab before a Contact record has been created and saved. Therefore, the user must first create the Contact record (using the Create form type) and after the record has been created, the users will be presented with the Update form type (with JavaScript Return Value = 2) and will be able to access the Products and Services tab as well as its contents.

The Contact entity’s create form type will look similar to this (i.e. the Products and Services tab is hidden):
Contact - Create form type

In contrast, the Update form type still shows the Products and Services tab.
Contact - Update form type

Here is the code to executes the requirement above.

//Hide Products and Services tab on Create form 
function HideProductsServicesTab(executionContext) {   
  //Get form context   
  var formContext = executionContext.getFormContext();   
  //Get form type   
  var formType = formContext.ui.getFormType();   
  //If formtype is Create, hide Products and Services tab on form     
  if (formType == 1) {
    formContext.ui.tabs.get("productsandservices").setVisible(false);   
  }   
  //To see the form type return value in your browser console
  console.log("Form type = " + formType); 
}

Save Mode

To get the form’s Save Mode, you use the following JavaScript code:

executionContext.getEventArgs().getSaveMode();

Here are Dynamics 365’s different Save Modes and their respective JavaScript return values as well as the applicable entities.

Entity Save Mode Return Value
AllSave1
AllSave and Close2
AllDeactivate5
AllReactivate6
EmailSend7
LeadDisqualify15
LeadQualify16
User or Team owned entitiesAssign47
ActivitiesSave as Completed58
AllSave and New59
AllAuto Save70

Application Example: Varying form behavior on Save Mode

Here is an example of how you can vary the form’s behavior on the Save Mode.

//Inhibit auto save functionality on a form
function InhibitAutoSave(executionContext) {
  var eventArgs = executionContext.getEventArgs();
  //To see the Save Mode return value in your browser console
  console.log("Save Mode = " + eventArgs.getSaveMode());
  //If save mode is 'Save and Close' or 'Auto Save', inhibit default behavior i.e. save 
  if (eventArgs.getSaveMode() == 2 || eventArgs.getSaveMode() == 70) {
    eventArgs.preventDefault(); 
  } 
  //To see if the auto save behavior was prevented in your browser console
  console.log("Default behaviour prevented: " + eventArgs.isDefaultPrevented());
 }

If you have some unsaved changes on a form, the code above inhibits the regular form auto save behavior as well as inhibits the regular Save and Close auto save behavior, that you ordinarily get when you navigate away from from a form with unsaved changes. Instead of auto-saving (i.e. the default behavior), if you try to navigate away from a form with an unsaved changes, the JavaScript code above will block the auto save behavior and offer you the pop up notification below. If you choose “OK”, you will loose all your unsaved changes, and if you choose “Cancel”, you will remain the same form. With the default auto save behavior inhibited, users have to manually save the form, by clicking on the Save button or using the keyboard shortcut: “Control + S”.
Auto Save Inhibited: Do you want to loose your changes?

What if you want to inhibit the auto-save behavior throughout your Dynamics 365 organization (i.e. disable auto-save on all forms), instead of a specific form? It would be inefficient to implement the JavaScript code above on all forms across all your Dynamics 365 organization entities. An efficient way execute such a requirement (i.e. on all forms) is to:

  1. Go to Settings > Administration.
  2. Click on System Settings.
  3. Click on the General tab
  4. Set the Enable auto save on all forms option, to No.
  5. Click OK, in the footer of the window.

Disabling Auto Save in a Dynamics 365 Organization

Dynamics 365: How To Get and Set Fields on Forms Using JavaScript

In this post, we will cover how to get and set values for fields on Microsoft Dynamics 365/CRM forms. Dynamics 365 has the following types of fields (or datatypes): Single Line of Text, Option Set, MultiSelect Option Set, Two Options, Image, Whole Number, Floating Point Number, Floating Point Number, Decimal Number, Currency, Multiple Lines of Text, Date and Time, Lookup and Customer.

At the time of writing, there are two ways of accessing fields on Dynamics 365 forms i.e. using the formContext JavaScript API and Xrm.Page JavaScript API. However, Microsoft has the following JavaScript API recommendations:

  • Before Dynamics 365/CRM version 9.0, use the Xrm.Page API:
    Xrm.Page.getAttribute(fieldName);
  • Version 9.0 of Dynamics 365/CRM and after, use the formContext API:
    executionContext.getFormContext().getAttribute(fieldName);

With the release of version 9.0 of Dynamics CRM/365, Microsoft announced that it would deprecate the Xrm.Page JavaScript API. For details on how you can transition from the Xrm.Page API to the formContext API, see my earlier post: Quick Guide: Transitioning away from Microsoft Dynamics 365 Xrm.Page JavaScript API. From Xrm.Page to formContext, how you get and set values has not fundamentally changed. However, how you access fields and other form properties has changed.

Single Line of Text

Here is an example of a Single Line of Text field on a Dynamics 365 form:
Single Line of Text field

Here is the JavaScript for getting and setting the value of a Single Line of Text field (Display Name: “Account Number” | Database Name: “accountnumber”):

//Get and Set a Single Line of Text field value
function SingleLineOfTextFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var accountNumberFieldLogicalName = "accountnumber";
    //Access the field on the form
    var accountNumberField = formContext.getAttribute(accountNumberFieldLogicalName);
    //Declare the other variables as needed
    var accountNumberFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (accountNumberField != null) {
        // Get the value of the field
        accountNumberFieldValue = accountNumberField.getValue();

        // Set the value of the field
        accountNumberField.setValue("BYA-2019-AIR-0099");
    }
}

Multiple Lines of Text

Here is an example of a Multiple Lines of Text field on a Dynamics 365 form:
Multiple Lines of Text field

Here is the JavaScript for getting and setting the value of a Multiple Lines of Text field (Display Name: “Description” | Database Name: “description”):

//Get and Set Multiple Lines of Text field value
function MultipleLineOfTextFieldValue(executionContext) {
    debugger;
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var descriptionFieldLogicalName = "description";
    // Access the description field on the form
    var descriptionField = formContext.getAttribute(descriptionFieldLogicalName);
    //Declare the other variables as needed
    var descriptionFieldValue;
    var exampleText = "\
            To be, or not to be, that is the question:\
            Whether 'tis nobler in the mind to suffer\
            The slings and arrows of outrageous fortune,\
            Or to take Arms against a Sea of troubles,\
            And by opposing end them: to die, to sleep;\
            No more; and by a sleep, to say we end \
            The heart - ache, and the thousand natural shocks \
            That Flesh is heir to ? 'Tis a consummation \
            Devoutly to be wished.To die, to sleep, \
            perchance to Dream; aye, there's the rub, \
            For in that sleep of death, what dreams may come, \
            When we have shuffled off this mortal coil,\
            Must give us pause. "  ;

    //Check that field exist on the form before you try to Get/Set its value
    if (descriptionField != null) {
        // Get the value of the description field
        descriptionFieldValue = descriptionField.getValue();

        // Set the value of the description field
        descriptionField.setValue(exampleText);
    }
}

Whole Number

Here is an example of a Whole Number field on a Dynamics 365 form:
Whole Number Field

Here is the JavaScript for getting and setting the value of a Whole Number field (Display Name: “Number of Employees” | Database Name: “numberofemployees”):

//Get and Set a Whole Number field value
function WholeNumberFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var numberOfEmployeesFieldLogicalName = "numberofemployees";
    // Access the field on the form
    var numberOfEmployeesField = formContext.getAttribute(numberOfEmployeesFieldLogicalName);
    //Declare the other variables as needed
    var numberOfEmployeesFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (numberOfEmployeesField != null) {
        // Get the value of the field
        numberOfEmployeesFieldValue = numberOfEmployeesField.getValue();

        // Set the value of the field
        numberOfEmployeesField.setValue(20000);
    }
}

Decimal Number

Here is an example of a Decimal Number field on a Dynamics 365 form:
Decimal Number field

Here is the JavaScript for getting and setting the value of a Decimal Number field (Display Name: “Exchange Rate” | Database Name: “exchangerate”):

//Get and Set a Decimal Number field value
function DecimalNumberFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var exchangeRateFieldLogicalName = "exchangerate";
    // Access the field on the form
    var exchangeRateField = formContext.getAttribute(exchangeRateFieldLogicalName);
    //Declare the other variables as needed
    var exchangeRateFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (exchangeRateField != null) {
        // Get the value of the field
        exchangeRateFieldValue = exchangeRateField.getValue();

        // Set the value of the field
        exchangeRateField.setValue(1.35551);
    }
}

Floating Point Number

Here are some examples of Floating Number fields on a Dynamics 365 form:
Floating Number field

Here is the JavaScript for getting and setting the value of a Floating Number field (Display Name: “Address 1: Longitude” | Database Name: “address1_longitude”):

//Get and Set a Floating Point Number field value
function FloatingPointNumberFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var longitudeFieldLogicalName = "address1_longitude";
    // Access the field on the form
    var longitudeField = formContext.getAttribute(longitudeFieldLogicalName);
    //Declare the other variables as needed
    var longitudeFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (longitudeField != null) {
        // Get the value of the field
        longitudeFieldValue = longitudeField.getValue();

        // Set the value of the field
        longitudeField.setValue(-79.387054);
    }
}

Currency

Here is an example of a Currency field on a Dynamics 365 form:
Currency field

Here is the JavaScript for getting and setting the value of a Currency field (Display Name: “Annual Revenue” | Database Name: “revenue”):

//Get and Set a Currency field value
function CurrencyFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var revenueFieldLogicalName = "revenue";
    // Access the field on the form
    var revenueField = formContext.getAttribute(revenueFieldLogicalName);
    //Declare the other variables as needed
    var revenueFieldValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (revenueField != null) {
        // Get the value of the field
        revenueFieldValue = revenueField.getValue();

        // Set the value of the field
        revenueField.setValue(52000000);
    }
}

Two Options

Here are some examples of Two Options fields on a Dynamics 365 form:
Two Options field

Here is the JavaScript for getting and setting the value of a Two Options field (Display Name: “Email” | Database Name: “donotemail”):

//Get and Set a Two Options field value
function TwoOptionsFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var dontAllowEmailsFieldLogicalName = "donotemail";
    // Access the field on the form
    var dontAllowEmailsField = formContext.getAttribute(dontAllowEmailsFieldLogicalName);
    //Declare the other variables as needed
    var dontAllowEmailsValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (dontAllowEmailsField != null) {
        // Get the value of the field
        dontAllowEmailsValue = dontAllowEmailsField.getValue();

        // Set the value of the field to TRUE
        //dontAllowEmailsField.setValue(true);

        // Set the value of the field to FALSE
        dontAllowEmailsField.setValue(false);
    }
}

Option Set

Here is an example of an Option Set field on a Dynamics 365 form:
Option Set field

Here is the JavaScript for getting and setting the value of an Option Set field (Display Name: “Contact Method” | Database Name: “preferredcontactmethodcode”):

//Get and Set a Option Set field value
function OptionsetFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var contactMethodFieldLogicalName = "preferredcontactmethodcode";
    // Access the field on the form
    var contactMethodField = formContext.getAttribute(contactMethodFieldLogicalName);
    //Declare the other variables as needed
    var contactMethodValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (contactMethodField != null) {
        // Get the value of the field
        contactMethodValue = contactMethodField.getValue();
        
        // Set the value of the field to FALSE
        contactMethodField.setValue(5);   
    }
}

MultiSelect Option Set

Here is an example of a MultiSelect Option Set field on a Dynamics 365 form:
MultiSelect Option Set field

Here is the JavaScript for getting and setting the values of a MultiSelect Option Set field (Display Name: “Geographical Areas of Operation” | Database Name: “hse_geographicalareasofoperation”) :

//Get and Set a MultiSelect Option Set field value
function MultiSelectOptionsetFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var locationFieldLogicalName = "hse_geographicalareasofoperation";
    // Access the field on the form
    var locationField = formContext.getAttribute(locationFieldLogicalName);
    //Declare the other variables as needed
    var locationValue;

    //Check that field exist on the form before you try to Get/Set its value
    if (locationField != null) {
        // Get the value of the field
        locationValue = locationField.getValue();

        // Set the value of the field to the desired values
        locationField.setValue([864700000, 864700003, 864700005, 864700007]);
    }
}

Date and Time

Here are some examples of Date and Time fields on a Dynamics 365 form:
Date and Time fields

Here is the JavaScript for getting and setting the value of a Date and Time field (Display Name: “Follow Up Date” | Database Name: “hse_followupdate”):

//Get and Set a Date and Time field value
function DateAndTimeFieldValue(executionContext) { 
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var createdOnFieldLogicalName = "createdon";
    var followUpFieldLogicalName = "hse_followupdate";
    // Access the fields on the form
    var createdOnField = formContext.getAttribute(createdOnFieldLogicalName);
    var followUpField = formContext.getAttribute(followUpFieldLogicalName);
    //Declare the other variables as needed
    var createdOnFieldValue;
    var followUpFieldValue = new Date();
    var numberOfDays = 30;
    var daysMillisecondsConverter = 24 * 60 * 60 * 1000;

    //Check that fields exist on the form before you try to Get/Set its values
    if (createdOnField != null && followUpField != null) {
        // Get the value of the field
        createdOnFieldValue = createdOnField.getValue();

        //Before you use the createdOnFieldValue value, verify that it exists
        if (createdOnFieldValue != null) { 
            //Set the follow up date to 30 days after the record was created
            followUpFieldValue.setTime(createdOnFieldValue.getTime() + (numberOfDays * daysMillisecondsConverter));           
            // Set the value of the field
            followUpField.setValue(followUpFieldValue);
        }        
    }
}

Lookup

Here is an example of a Lookup field on a Dynamics 365 form:
Lookup field

Here is the JavaScript for getting and setting the value of a Lookup field (Display Name: “Account Manager” | Database Name: “hse_accountmanager”) :

//Get and Set a Lookup field value
function LookupFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var accountmanagerLogicalName = "hse_accountmanager";
    // Access the field on the form
    var accountmanagerField = formContext.getAttribute(accountmanagerLogicalName);
    //Declare the other variables as needed
    var accountmanagerFieldValue;
    var guid;
    var name;
    var entityName;

    //Check that field exist on the form before you try to Get/Set its value
    if (accountmanagerField != null) {
        // Get the value of the field
        accountmanagerFieldValue = accountmanagerField.getValue();
        //Check if the field contains a value
        if (accountmanagerFieldValue != null) {
            //To get the attributes of the field
            guid = accountmanagerFieldValue[0].id.slice(1, -1);
            name = accountmanagerFieldValue[0].name;
            entityName = accountmanagerFieldValue[0].entityType;
        }

        // Set the value of the field
        accountmanagerField.setValue([{
            id: "4BDB64C8-AA81-E911-B80C-00155D380105",
            name: "Joshua Sinkamba",
            entityType: "systemuser"
        }]);

        //Alternative Approach: Set the value of the field
        //var lookupValue = new Array();
        //lookupValue[0] = new Object();
        //lookupValue[0].id = "4BDB64C8-AA81-E911-B80C-00155D380105";
        //lookupValue[0].name = "Joshua Sinkamba";
        //lookupValue[0].entityType = "systemuser";
        //accountmanagerField.setValue(lookupValue);
    }
}

Customer

Here is an example of a Customer field on a Dynamics 365 form:
Customer field

Here is the JavaScript for getting and setting the value of a Customer field (Display Name: “Main Customer” | Database Name: “hse_maincustomer”):

//Get and Set a Customer field value
function CustomerFieldValue(executionContext) {
    //Get the context of the form
    var formContext = executionContext.getFormContext();
    //The logical name of the field of interest
    var mainCustomerLogicalName = "hse_maincustomer";
    // Access the field on the form
    var mainCustomerField = formContext.getAttribute(mainCustomerLogicalName);
    //Declare the other variables as needed
    var mainCustomerFieldValue;
    var guid;
    var name;
    var entityName;

    //Check that field exist on the form before you try to Get/Set its value
    if (mainCustomerField != null) {
        // Get the value of the field
        mainCustomerFieldValue = mainCustomerField.getValue();
        //Check if the field contains a value
        if (mainCustomerFieldValue != null) {
            //To get the attributes of the field
            guid = mainCustomerFieldValue[0].id.slice(1, -1);
            name = mainCustomerFieldValue[0].name;
            entityName = mainCustomerFieldValue[0].entityType;
        }

        // Set the value of the field
        mainCustomerField.setValue([{
            id: "EE047399-CDE0-E911-B817-00155D380105",
            name: "Avanade",
            entityType: "account"
        }]);

        //Alternative Approach: Set the value of the field
        //var customerValue = new Array();
        //customerValue[0] = new Object();
        //customerValue[0].id = "EE047399-CDE0-E911-B817-00155D380105";
        //customerValue[0].name = "Avanade";
        //customerValue[0].entityType = "account";
        //mainCustomerField.setValue(customerValue);
    }
}

Optimize Entity Attributes Access in Dynamics 365

I was recently working at a client site and came across the error/exception below. A plugin I had developed a few weeks earlier stopped working in the integration environment after an update to a different class/plugin. The error did not make sense and sent me on a wild goose chase for a few hours. How can code function in one environment and not in another environment, when one environment is a replicate of the other and all the parameters as well as infrastructure is the same? As a software developer, the favorite part of my job is coming across such conundrums.

The Error

“The given key was not present in the dictionary” exception

This was as much information as I could get from the system. This exception indicates that I was trying to access an attribute that was not present in the internal .NET dictionary. I looked very closely at both environments and they had all the entity attributes I was accessing in the plugin.  

In investigating this error, I came across a more efficient way to access entity attributes in Microsoft Dynamics 365. Often, before Dynamics 365 software developers perform logic on a retrieved value, they have to check if the retrieved value exists. Executing such logic usually follows the following path or something similar (we use the Contact entity in this example but this can be applied to any out of the box entity or custom entity):

Accessing attributes using Attributes.Contains() method

//Declare the contact entity and retrieve it from the execution context
Entity contact = pluginExecutionContext.InputParameters["Target"] as Entity;
//Check if attribute exists in collection, using Attributes.Contains
if (contact.Attributes.Contains("company"))
{
    //Get attribute of interest, as a string
    string contactCompany = contact.GetAttributeValue("company");
    //Perform operations on your attribute of interest
    /*
    */
}

Accessing attributes using Attributes.TryGetValue() method

//Declare the contact entity and retrieve it from the execution context
 Entity contact = pluginExecutionContext.InputParameters["Target"] as Entity;
 //Object that will store the attribute object if the retrieval is successful
 Object contactComp;
 //Check if attribute exists in collection, using Attributes.TryGetValue
 if (contact.Attributes.TryGetValue("company", out contactComp))
 {
    //Get attribute of interest, as a string
    string contactCompany = (String)contactComp; 
     //Perform operations on your attribute of interest
     /*
     */
 } 

Despite the Attributes.Contains() method and the Attributes.TryGetValue() being used to achieve the same objective, the latter is more efficient. When you use the Attributes.Contains() method, your code is performing two look up operations in the background. First, it checks if the specified attribute is contained in the internal dictionary. If the dictionary contains the specified attribute, another look up will be performed to get the corresponding value for the attribute. The Attributes.TryGetValue() method performs both operations in one swoop by returning a Boolean value, true (value exists) or false (value does not exist), and an output object, which contains the attribute value.

If you are only accessing the attribute dictionary as shown above, a few times, you may not see significant savings in execution time, by using Attributes.TryGetValue(). However, as the application grows and you are performing these operations regularly or in a loop, the code optimizations benefits of using Attributes.TryGetValue() become self-evident.

To learn more about Attributes.TryGetValue() method, look at the Microsoft documentation: TryGetValue().

Conclusion

The Attributes.TryGetValue() method resolved the exception I was getting within my plugin and optimized my code. This is more than what I had bargained for when I began my investigation, which is a terrific and extremely rewarding outcome. Therefore, I would recommend the Attributes.TryGetValue() method over the Attributes.Contains() method.