Validate Multiple Fields in JavaScript

CRM forms can often have multiple fields marked as business required. Mandatory validation is sometimes even added dynamically via JavaScript, for example based off the value of an option set. If you have a large CRM form, it's not always possible to see all of the red (*) asterisks; users will have to try and save the form over and over to be prompted and receive focus of each missing field individually.

You can instead program all of your business required fields into an array in JavaScript, and present all of the missing information in one popup box. This is more user-friendly.

First, setup your array of fields as objects where each object holds the schema name, label and value of the field:

Then iterate through all of your fields to determine which, if any, don't contain a value (which they should because they're business required):

Note: I've chosen to use Array.prototype.forEach() in this example because it's supported in IE9 and above. If your CRM user base is using a more modern browser, consider using let:

More information on array iteration and JavaScript browser compatibility here.

Anyway, we finally need to format the labels of our fields which are missing information into a readable message to be presented as an alert. The following code splits the array of field labels each with a comma, except the last element where an 'and' is placed:

You can then present your alert with alert(message);:

As an alternate message formatting, you could use the • unicode character and the \n escape character to mock bulletpoints. Unfortunately, html tags can't be passed to alert boxes, otherwise we'd use ul:

Note: the example above only uses three fields. The solution presented should probably only be used for a requirement involving 10+ fields. Adding JavaScript adds complexity to the system and makes it harder to maintain and should therefore be avoided where possible.

Post Data from a Dynamics CRM Form to an iFrame

HTML web resources can be embedded into a CRM form within an iFrame. Often you'll need to send data to and from the embedded HTML page. Here's how.

If you need to send data from an HTML page to a CRM form, you can use window.parent to access the Xrm namespace. For example, a user may enter a value into an input field on your embedded HTML page which could then update a value on a CRM form automatically by using:

Sending data the other way (from a CRM form to an HTML resource) is slightly more complicated.

Firstly, when customising your form and adding the embedded HTML resource, ensure that cross-frame scripting is not disabled (which it is by default). If this option is left checked you'll receive a sandboxed script cross-origin error message in the browser console, and the script won't load on the form.

Secondly, set up the data you want to send from your CRM form in JavaScript. This example sends a contact's first and last name in their respective onChange() events:

More on window.postMessage() can be found on MDN here.

Finally, configure your HTML page to accept and process messages from your CRM form. Place the following script tag in your HTML's body:

Here's the finished example:

Retrieve Money Value from an an Aliased Value in a LinkEntity with C#

When you query an entity you can link another entity to it. You might want to do this to:
  • add additional conditions to your query with pertain to a related entity
  • return columns from two entities within only one query (which is more efficient)

Here's a scenario:

You have a Product lookup on the Lead entity titled 'Product of Interest' and the Product entity has an option set called 'Product Type'. A query could therefore be to retrieve all Leads that have a Product of Interest where the Product has a 'Product Type' of 'Equipment'.

In C#, your QueryExpression would utilise a LinkEntity and read as follows:

The query above retrieves all active Leads in CRM and links their Product of Interest, returning no columns from the Lead and the 'Price' column from the Product.

When retrieving the linked Product's 'Price' from a returned Lead, you might expect to be able to use GetAttributeValue, but unfortunately you can't. You must first use GetAttributeValue, then cast the object's Value property to Money, and then retrieve the Money's Value property... phew.

Here's the final code to retrieve a linked entity's Money value:

Note that the attribute you're retrieving from the Lead is "Product.price" not just "price". This is because LinkEntity attributes are prefixed with the EntityAlias property of the LinkEntity object passed to the QueryExpression (see the first code block above).

Backpopulate an AutoNumber Field

If you've just implemented an autonumbering solution in CRM, newly created records will have an autonumber generated for them. Now, however, it's likely you'll need to backpopulate all records that were created before the autonumbering solution was implemented.

As an example, the SQL script below selects all Contacts in CRM and iterates through them, setting their [AutoNumber] field equal to the Contact's database row number. The script also pads this number, to keep in alignment with my autonumber syntax, which is padded to be a minimum of 10 characters long. For example, a row number of 489 is padded to an autonumber of 0000000489

When using this script, replace:

  • [AutoNumber] with the schema name of your autonumber field e.g. new_autonumber
  • [Database] with the name of your CRM database
  • [ContactBase] with the table of the entity you're looking to update. You'll also need to replace ContactId with the primary id of this entity


I recommend this autonumber from Celodon, the code for which is hosted here on GitHub.

Calculate Working Time between Two Dates in C# (including SLA Working Hours)

Often we need to calculate the time between two dates, but only take into account working hours. Working hours usually fall somewhere between 09:00 - 17:00, Monday - Friday, and are defined in CRM via Entitlements and SLAs. There's no way to achieve this out of the box, therefore custom code must be written for this calculation within a plugin or a workflow.

The code I provide in this article is one of many ways this can be achieved. My approach here is to abstract days, minutes and time duration programatically and to then provide a static Calendar class to deal with CRM-specific logic.

Minute's are straightforward. You'll see here I simply conceptualise them as an object that has an Index property to represent which minute of the day the minute is. For example a minute with Index is 00:10.

One level higher, I outline a day, which has a list of minutes (there are 1440 minutes in a day):

Then we have a duration, which is a collection of days between a start and an end:

Finally we have a static calendar class which handles CRM-specific entitlement and SLA logic. This currently only works for retrieving an Entitlement from a Case. Attribute strings can be changed according to your requirement/the entity you're working with.

How is this used?

Firstly, the 4 classes from above are copied into a project.

Next, in the plugin's execute method, two DateTimes are retrieved, along with the context entity. In this example I'm using a Case entity and my Calendar class:

We now have a list of days representing a model of working hours defined in the Case's Entitlement stored in the workingHours variable.

We can now create a duration object, which models the time between our two DateTimes:

Then we remove time which we're not interested in (it falls outside of valid working hours):

And finally call GetTotalMinutes() and calculate the time in minutes between our two DateTimes without the invalid time:

And that's all. We now have the valid working time (in minutes) between the two DateTimes stored in the responseTime variable.

Retrieve Option Set Metadata Via SQL

When working on projects, typically those that involve integration, several stakeholders may need to know the underlying integer values of option sets. Said stakeholders may be third parties or internal developers, who don't necessarily have access to view option set metadata in CRM. The task of providing this metadata can therefore fall to you, the CRM consultant, which can prove to be time consuming and a project bottleneck.

You'll move to your CRM solution, find the attribute and create an excel table for the requested option set to e-mail back to the stakeholder:

Speed things up

If you or better yet, the other stakeholder has SQL access, run the following script to generate a table of option set values and labels for a given option set:

The above code snippet retrieves metadata for the statuscode option set on the Account entity.

In the WHERE clause:

  • statuscode can be replaced with the schema name of any option set
  • Account can be replaced with the schema name of any entity

Note that the e.Name condition is not necessary if you are sure the option set attribute only exists on one entity. In this example however, we need to specify the entity because we know that statuscode exists on every entity in CRM.

C# Attribute Checking is Inefficient

If an entity does not contain an attribute but we try to retrieve the attribute's value anyway, a NullReferenceException is thrown. Therefore, basic practice is to check that an entity contains an attribute before trying to retrieve the attribute's value. The following code snippet gets an account entity from a plugin's context then retrieves value for attribute address1_line1.

This is inefficient because .Contains() uses the same check as GetAttributeValue(), which internally refers to the actual entry location. The lookup functionality (finding the value of a key in a collection) is duplicated.

Use TryGetValue() instead

Last week I posted a set of useful extension methods to shorten our C# code, making it more readable and in some cases more efficient. Add a new extension method:

This method tries to get an attribute's value and returns true if the attribute exists. Crucially, it also returns the value of the attribute if it exists, as an out parameter.

We can now rewrite our code to get the value for address 1 line 1 and only iterate through the attribute collection once:


It's important to remember that this is a micro-optimisation. We should still consider whether slightly more optimised code is actually worth it i.e. does it sacrifice code readability?

This post was inspired by a recent pull request from the .NET Roslyn compiler which is open-source and hosted here on GitHub.

Finally, for the curious, the performance difference between TryGetValue and Contains is discussed further here on StackOverflow.