Using RetrieveEntityChangeRequest to track changes in CRM 2015 / 2016.

As a first step,

Enable Change Tracking for the entity, custom Demo Entity in our case here.

Suppose we have 5 records created for Demo Entity.

As we are calling it for the first time DataVersion is set as empty.

We got all the 5 records as new or updated item.

Save the DataToken to be used while determining the changes and to be passed next time.

Now let us delete Record 1 and Record 2 and update Record 5 and run the code again this time passing the DataToken saved

As expected we get 3 changes.

Now suppose we create a new record name Record 6 and still use the old Data Token

As expected we got 4 changes here, which includes the new record 6 as new or update.

Point to remember here is if no version is passed the system will return all the records as new, and system will consider records that are within 90 days, if it is older than 90 days all the records will be returned.

If we have a new record created and deleted before we retrieved for the changes and the record didn’t exist at the time of retrieval, we will still get the record as deleted.

Sample Code


EntityCollection newOrUpdatedEntityCollection = new EntityCollection();
EntityReferenceCollection removeOrDeletedEntityRefCollection = new EntityReferenceCollection();

RetrieveEntityChangesRequest retrieveEntityChangeRequest = new RetrieveEntityChangesRequest();
retrieveEntityChangeRequest.Columns = new ColumnSet();
retrieveEntityChangeRequest.Columns.AddColumn("new_name");

// pass DataVersion
retrieveEntityChangeRequest.DataVersion = "1018501!10/24/2016 12:31:46";

retrieveEntityChangeRequest.EntityName = "new_demoentity";
retrieveEntityChangeRequest.PageInfo = new PagingInfo();

RetrieveEntityChangesResponse retrieveEntityChangesResponse = (RetrieveEntityChangesResponse)organizationProxy.Execute(retrieveEntityChangeRequest);

foreach (var entity in retrieveEntityChangesResponse.EntityChanges.Changes)
{
var dataToken = retrieveEntityChangesResponse.EntityChanges.DataToken;

if (entity.Type == ChangeType.NewOrUpdated)
{
newOrUpdatedEntityCollection.Entities.Add(((NewOrUpdatedItem)entity).NewOrUpdatedEntity);
}
else if (entity.Type == ChangeType.RemoveOrDeleted)
{
removeOrDeletedEntityRefCollection.Add(((RemovedOrDeletedItem)entity).RemovedItem);
}
}

Hope it helps ..


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s