D365 CRM: How to get de Audit Details of an Entity record using the SDK API



  • If you need to get the audit details of an entity record here is a simple code using the SDK API of CRM:
    First, we need to get the audit collection of the entity record:

                QueryExpression auditQuery = new QueryExpression();
                auditQuery.EntityName = "audit";
                auditQuery.PageInfo.PageNumber = 1;
                auditQuery.PageInfo.PagingCookie = null;
                auditQuery.ColumnSet = new ColumnSet(true);

                FilterExpression filter = new FilterExpression();
                filter.FilterOperator = LogicalOperator.And;

                ConditionExpression condExp = new ConditionExpression();
                condExp.AttributeName = "objectid";
                condExp.Operator = ConditionOperator.Equal;
                condExp.Values.Add(recordId); // The record Id to get the auditing
                filter.AddCondition(condExp);

         // You can add here another condition to get the audit of a specific date using the created-on attribute filter

                OrderExpression order = new OrderExpression();
                order.AttributeName = "createdon";
                order.OrderType = Microsoft.Xrm.Sdk.Query.OrderType.Ascending;
                auditQuery.Orders.Add(order);
                auditQuery.Criteria = filter;

                EntityCollection auditCollection = Service.RetrieveMultiple(auditQuery);

    Then we need to get for each audit retrieved, the details to see the difference of the attribute value:

    foreach (Entity audit in auditCollection.Entities)
    {
    string action = audit.FormattedValues["action"].ToString(); // The action of the change for ex. Create/Update/Delete
    RetrieveAuditDetailsRequest auditDetailsRequest = new RetrieveAuditDetailsRequest
    {
            AuditId = audit.Id
    };

    RetrieveAuditDetailsResponse auditDetailsResponse = (RetrieveAuditDetailsResponse)Service.Execute(auditDetailsRequest);
    if (((AttributeAuditDetail)auditDetailsResponse.AuditDetail).NewValue != null)
    {
       if (((AttributeAuditDetail)auditDetailsResponse.AuditDetail).NewValue.Attributes.Count > 0)
          {
              var oldDetail = ((AttributeAuditDetail)auditDetailsResponse.AuditDetail).OldValue; // The Old value
              var newDetail = ((AttributeAuditDetail)auditDetailsResponse.AuditDetail).NewValue; // The New value
          }
    }
    }

    Enjoy it!
     


  • Comments



Add a Comment