Wednesday, August 14, 2013

Re-create deleted records using Audit History

Many a times we come across situations where we accidentally, delete a particular record and wish to recover that record back in CRM. This is possible only if you have “Auditing” enabled for that respective entity. So from the audit history we can re-create deleted records in CRM.

Let us take an example, supposing some records were deleted today and needs to be recovered.

//fetch XML for retrieving auditing records which were deleted today

                string fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' no-lock='true' distinct='false'> " +
    "<entity name='audit'>  " +
    "<attribute name='auditid' /> " +
     "<attribute name='operation' /> " +
    "<filter type='and'> " +
    "<condition attribute='createdon' operator='today' /> " +
   "<condition attribute='operation' operator='eq' value='3' /> " +
    "</filter>   " +
    "</entity> " +
    "</fetch>";

                //retrieve the audit records from fetchxml
                var auditrecords = service.RetrieveMultiple(new FetchExpression(fetchXML));

                //loop through each audit entity record found and create deleted records
                foreach (Entity audit in auditrecords.Entities)
                {
                    // create retrieve audit detail request object
                    RetrieveAuditDetailsRequest auditDetailsRequest = new RetrieveAuditDetailsRequest();

                    //assign audit id value
                    auditDetailsRequest.AuditId = audit.Id;

                    //execute request and retrieve response
                    RetrieveAuditDetailsResponse auditDetailsResponse =
                        (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);
                 
                    //create auditDetail variable and assign its value
                    AuditDetail auditDetail = auditDetailsResponse.AuditDetail;

                    //type cast audtitDetail as AttributeAuditDetail
                     AttributeAuditDetail attributeAuditDetail = auditDetail as AttributeAuditDetail;

                    //create the deleted record
                     service.Create(attributeAuditDetail.OldValue);
                }


In above code first we have retrieved audit entity records which were created “today” and operation was “Delete”.

“Operation” field is an “Option Set” field and values are

-              Create = 1
-              Update = 2
-              Delete = 3
-              Assign = 4





Hope this post helps!


2 comments:

  1. Hello,

    Thank you for this sample, the Fetch query is using an "Audit" entity, is there any System entity by Audit and is this a supported approach.

    Thanks,
    CP

    ReplyDelete
  2. Yes this is supported approach. The audit entity is available for retrieve operations through the SDK

    ReplyDelete