Setting Values Programmatically via the CRM 2011 SDK

Roshan Mehta, 19 July 2012

In this blog, I will show you how to set field values for Microsoft Dynamics CRM 2011 entities using the Microsoft Dynamics CRM 2011 SDK. Previous versions of Dynamics CRM required the use of specific “CRM data types” such as CrmBoolean or CrmDateTime which can be frustrating when it comes to casting values to the appropriate types. These have been replaced with native .NET types to allow more control for your custom CRM applications. There are also a few special CRM 2011 data types which we will also explore such as OptionSetValue and Money.

Firstly, let’s take a look at how we would set field values using native .NET types. These include string, DateTime, decimal, int and bool.

Entity opp = new Entity("opportunity");
opp ["name"] = "Interested in purchasing 1000 ice cream cones";      // string
opp ["estimatedclosedate"] = new DateTime(2012, 12, 1);              // DateTime
opp ["discountpercentage"] = 0.15;                                   // decimal
opp ["closeprobability"] = 62;                                       // int
opp ["isrevenuesystemcalculated"] = false;                           // bool 

Here is how we would set special field values in Dynamics CRM 2011. These include OptionSetValue, Money (Currency), and EntityReference (Lookup).

Entity opp = new Entity("opportunity");
opp["opportunityratingcode"] = new OptionSetValue(2);               // OptionSetValue
opp["estimatedvalue"] = new Money(700.2M);                          // Money
opp["campaignid"] = new EntityReference("campaign", campaignId);    // EntityReference 

It is important to note the parameter values which are passed into each of the special CRM 2011 types. The OptionSetValue type takes an integer parameter which maps to the ordinal value of the option we want to set. A value of “2” for the opportunityratingcode in CRM maps to the display value “Warm” as seen in the screenshot below.

 Setting Values Programmatically via the CRM 2011 SDK

The Money type takes in a decimal value as a parameter. In our example, we set the estimatedvalue to $700.20 by specifying the “M” suffix as required by the .NET Framework.

Lastly, our EntityReference type takes two parameters – the schema name (or internal name) of the entity as well as the unique identifier (GUID) of the record we want to reference. Common platform operations such as create or update will fail if an incorrect entity schema name or unique identifier is specified for the EntityReference.