Creating an Audit Plugin in Dynamics CRM 2011

Zhen Yuwang, 11 January 2012

Recently I worked on a Plugin that was required to send an email notifying specified users of changes to any updated fields’ including the display name, original value and updated value.

We needed some entities to contain values before update and after update. The “name” property of “EntityReference” can contain a value or null. The name property of EntityReference will not contain data when the property is retrieved inside a plugin; for example: from the InputParameters or Pre/Post EntityImages. The way to get the name of an EntityReference is to re-retrieve the record using fetchxml or queryexpressions.

 Creating an Audit Plugin in Dynamics CRM 2011

So we need “Pre Image” and “Post Image” entities under the “Update of contact” step as well as the entity in the context InputParameters.

Entity entity = (Entity)context.InputParameters["Target"];
Entity preEntity = context.PreEntityImages["PreImage"];
Entity postEntity = context.PostEntityImages["PostImage"];

Those “preEntity” and “postEntity” contains Not-null “name” property of “EntityReference”. The only difference is the former gets the properties AFTER update operation has been completed, while the latter one gets the properties BEFORE update operation has begun.

Next, we need the display name of each updated fields and we use RetrieveEntityRequest to get EntityMetadata of current entity.

Next, for each updated field in the entity.Attributes collection, we obtain the field Name from its key.  Search with this Name BOTH in “preEntity” and “postEntity” to get the proper Value. Besides the simple string type, there are other complex types such as EntityReferenceMoney and OptionSetValue.

Comparing what we get from “preEntity” and “postEntity”, if those two are not equal, search attribute in EntityMetadata.Attributes, retrieve the Display Name by

displayName = attribute.DisplayName.LocalizedLabels[0].Label;

Finally, the Display Name and Value in pre and post are all retrieved by us. We can put them in the appropriate position with neat formatting.

It just looks like this:

 Creating an Audit Plugin in Dynamics CRM 2011