Retrieve Dynamics CRM audit summary with CRM SDK

Retrieve Dynamics CRM audit summary with CRM SDK

If you need to obtain the audit history list of a particular entity, you can query the audit logs using CRM SDK and C# provided Auditing has been enabled in Dynamics CRM.

You can also filter the logs using a specific attribute to get retrieve attribute history.

For example,  if I want to know what changes had been made to name attribute of a particular account, I can do this by retrieving the data change history using RetrieveRecordChangeHistoryRequest Class

Retrieve dynamic CRM audit summary with CRM SDK

Full source code in C# is given below with inline comments:

   //Create a new RetrieveAttributeChangeHistoryRequest

RetrieveAttributeChangeHistoryRequest req = new RetrieveAttributeChangeHistoryRequest();

//Set the target Entity

req.Target = new EntityReference(“account“, new Guid(“296C4D23-B8A1-45D8-9126-ECCA91A57B2C“));

//Set the attribute you want to retrieve specifically

req.AttributeLogicalName = “new_name“;

  //Execute the request against the OrgService

RetrieveAttributeChangeHistoryResponse resp = (RetrieveAttributeChangeHistoryResponse)orgService.Execute(req);

AuditDetailCollection details = resp.AuditDetailCollection;

  //Iterate through the AuditDetails

foreach (var detail in details.AuditDetails)

{

//Important: the AuditDetailCollection.AuditDetails doesn’t always contain the type of AttributeAuditDetail, so make sure it is of correct type before casting

if (detail.GetType() == typeof(AttributeAuditDetail))

{

AttributeAuditDetail attributeDetail = (AttributeAuditDetail)detail;

String oldValue = “(no value)“, newValue = “(no value)“;

if (attributeDetail.OldValue.Contains(“new_name“))

oldValue = attributeDetail.OldValue[“new_name“].ToString();

if (attributeDetail.NewValue.Contains(“new_name“))

newValue = attributeDetail.NewValue[“new_name“].ToString();

   //TODO: Use the old value and new value in the Business Logic

}

}

 

549 total views, 1 views today

About Author

Ricky Saini

Ricky Saini
Dynamics CRM, SharePoint, Office 365, Windows Azure and .Net Architect/Consultant/Freelancer in Australia ( Melbourne, Sydney and Canberra)

Leave a Comment