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);
    }
}

The Microsoft Dynamics 365 Custom Control Framework

In version 9 of Dynamics 365 / CRM, Microsoft introduced the Custom Control Framework, which gives Dynamics 365 customizers and developers more options on how to display fields and data-sets, such as views. The Custom Control Framework offers a wide range of aesthetically appealing displays, enabling you to transform regular fields and data-sets into more appealing visualizations that are likely to increase user engagement and enhance user experience.

Examples

The default display for a numeric input field, i.e. Whole Number, Decimal, Currency, Floating Point Number, is:

Numeric Field - Default Display

Using the Custom Control Framework, you can transform this regular numeric input field into other displays such as Number Input, Arc Knob, Radial Knob, Linear Gauge, Linear Slide, Star Rating, among others.

Numeric Field - Other Display Options

Depending on the type of input field, different Custom Control Framework displays are available. For an Option Set field, the regular display is:

OptionSet - Default Display

Using the Custom Control Framework’s Option Set, it can also be displayed as tiles:

OptionSet - Tiles Display

How to Implement the Custom Control Framework

Step 1: Go to the edit mode of the entity’s form that you wish to apply the Custom Control Framework to. In the example below, I will be editing the Account entity’s Account form.

Account form in edit mode

Step 2: Click on the field you would like to apply the Custom Control Framework to. In the ribbon, click on ‘Change Properties’.

Step 3: In the Field Properties window that pops up, select the ‘Controls’ tab.

Field's Controls tab

Step 4: Click on “Add Control…”. Then select the control you would like to apply (1 – image below). Having selected the control you would like to apply, click ‘Add’ (2 – image below).

Note: In the example below, I am applying the Custom Control Framework to a numeric field.

Add a Custom Control

Step 5: Set the properties of the control. Select the devices you want your control to be displayed on i.e. Web Browser, Phone, Tablet (1 – image below). Enter the control’s properties i.e. Min, Max and Step values (2 – image below). Click ‘OK’ (3 – image below).

Set the control's properties

In (2 – image above), you can bind the Min, Max and Step values to a static value (A – image below) or to another field (B – image below).

Binding min, max and step values to a static value or field.

Step 6: Save and publish the entity’s form. You can now go and view the published version of the form to see your custom control in action.

Depending on the type of input field selected, different Custom Control Framework displays are available in Step 4 above. Also, the properties available in Step 5 are dependent on the type of input field selected . That is, the Custom Control Framework displays available for a numeric field are different from those available for an option set field.

Conclusion

As shown above, the Custom Control Framework offers organizations more options for displaying fields and has a nice aesthetic touch. However, like all tools, Dynamics 365 customizers and developers, have to assess their client’s needs and determine whether to use the default displays or the Custom Control Framework displays.

Microsoft Dynamics 365: How to Set Up a Free Online Trial Version

For organizations seeking a comprehensive, robust and extendable customer relationship management platform, it is worth considering the Microsoft Dynamics 365 platform. In this post, we will cover a quick case for considering Microsoft Dynamics 365 for your customer relationship management and provide a guide on how set up a free Dynamics 365 Online 30 day Trial Version.

A Quick Case for Microsoft Dynamics 365

Why should you choose Microsoft Dynamics 365 over other customer relationship management platforms? Here are 6 reasons to choose Microsoft Dynamics 365 over its competitors:

  • Familiar, intuitive and easy to adopt user interface: If an organization is familiar with the Microsoft Office suite, it is easy to adopt the Microsoft Dynamics 365 user interface, as they are designed by the same organization. You can spend less on change management.
  • Integration with the Microsoft ecosystem: You can easily integrate Microsoft Dynamics 365 with the rest of the Microsoft ecosystem like Outlook, Office 365 (Word, Excel, PowerPoint, Outlook, etc), Windows Server, Exchange Server, Skype for Business, SharePoint, Power BI, and PowerApps.
  • Powerful analytics, social sales and embedded intelligence features like LinkedIn Sales Navigator Application Platform and Relationship Assistant, to enhance productivity, efficiency and effectiveness.
  • Flexible and extendable architecture, deployment options, and pricing, making it easy for an organization to customize Dynamics 365 to its specific requirements and only pay for its unique needs.
  • Detailed, flexible and seamless security model: Dynamics allows you to control who can access general sections and specific areas like fields. Users only see areas they have been granted access to.
  • Microsoft’s commitment to the product quality and innovation as well as partner support: Microsoft is committed to quality and regularly releases updates, continuously innovating and improving the product. Also, Microsoft has a global network of partners to support clients across the world.

Setting up a Microsoft Dynamics 365 Free Online Trial Version

Are you convinced about Microsoft Dynamics 365? If you are, and ready to take it to the next level, here are the steps you need to set up a Microsoft Dynamics 365 online trial version:

Step 1: Go to the Microsoft Dynamics 365 product home page.
Dynamics 365 product home page

Step 2: Click on “Schedule a demo”.
Click on "Schedule a demo"

Step 3: Click on “Sign up for a free trial”.
Sign up for a free trial

Step 4: Click on “Sign up here”.
Click on "Sign up here"

Step 5: On the pop-up, if you are not a Microsoft employee or partner organization, click on “No, continue signing up”.
If you are not a Microsoft employee or partner organization, click on "No, continue signing up"

Step 6: Enter the required information and click “Next”.
Enter the required information and click on "Next"

Step 7: Enter the required information about the Microsoft Dynamics 365 trial organization you are about to create and click on “Create my account”. Also, if you would like to hear from Microsoft or its partner in your geographical location to provide support on your Dynamics 365 journey, select the options provided below.
Click "Create my account"

Step 8: Enter your phone number for Microsoft to verify that you are not a robot. You will receive an automated text or phone call, depending on the option you select.
Enter your phone number to verify that you are not a robot

Step 9: Hooray!!! You have created your Office 365 and Dynamics 365 organizations, you will get the page below. Take note of the “Sign-in page’ and “Your user ID”, you will need this information to sign into your new organization.
You have created a D365 organization

Step 10: Go to the Microsoft Office 365 home page. If you are requested to sign in, click on “Sign in” and login using the user ID from step 9 and the password you created earlier, in step 7.
Go to Microsoft Office 365 home page and sign into the organization you created in Step 9.

Step 11: After logging in, click on the “Admin” app, to access your Office 365 organization’s administration options and configurations.
Office 365 home - select Admin app

Step 12: Adding other users to your new Office organization and Dynamics 365 organization: In the Admin app, navigate to Users >>> Active Users. You will get a page similar to the one below. Click on ‘Add a user’ to start the process of adding a new user to the Office 365 organization.
Add other users

Step 13: Enter the user’s basic information and click Next:
User's basic info

Step 14: You can add a user to your Office 365 organization without giving them access to the Dynamics 365 organization. However, if you if you want the user to be both a member of the Office 365 organization and Dynamics 365 organization, you have to grant the user a Dynamics 365 license (see the image below). You can also assign the user other product licenses from this section. Click Next.

The creator of the organization has a Global Administrator role, in Office 365, as well as System Administrator and System Customizer security roles, in Dynamics 365, giving them the rights to add users to both Office 365 and Dynamics 365.
Assign licenses

Step 15: You can also assign administration roles to the user if you wish. These settings are optional. Click Next.
Optional settings

Step 16: Review the user details. If you have happy with the setup details, click on ‘Finish adding’ to add the user to the organization.
Finish adding user

Step 17: After successfully adding the user, you will get a page similar to image below. You can add more users from this window. After you finish add users, click ‘Close’.
Successfully added user

Step 18: Back in the Admin page, in the left navigation, navigate to ‘All admin centers ‘. If you cannot see ‘All admin centers ‘ in your left navigation panel, click on ‘Show all’. In the main window, click on ‘Dynamics 365’ to access the Dynamics 365 administration center, in order to complete the set up of your Dynamics 365 organization.
All Admin Centers

Step 19: To complete your Dynamics 365 setup, select the apps you are interested in. If you are not interested in the provided apps, you can select “None of these. Don’t customize my organization” for a vanilla Dynamics of 365 organization. Click on ‘Complete Setup’.
Select the Dynamics 365 apps you are interested in.

Step 20: Depending on the app(s) you selected in the previous step, you will get a launch pad similar to this:
D365 Published Apps

Step 21: Select the Dynamics 365 app you would like to launch by clicking on it and you will get the app’s home page. Here is an example of the Dynamics 365 Customer Service app home.
D365 -Customer Service

Your brand new Dynamics 365 instance has been set up and is ready for your adventures. Feel to explore and play around with the environment. You just have entered the fascinating world of Dynamics 365. Welcome!!!

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.