Re-create deleted records using Audit History

By | August 14, 2013
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 = +
      “ +
    +
     +
    +
    +
   +
    “   “ +
    “ “ +
    ““;
                //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 (Entityaudit in auditrecords.Entities)
                {
                    // create retrieveaudit detail request object
                    RetrieveAuditDetailsRequest auditDetailsRequest = new RetrieveAuditDetailsRequest();
                    //assign audit id value
                    auditDetailsRequest.AuditId = audit.Id;
                    //execute request and retrieve response
                    RetrieveAuditDetailsResponseauditDetailsResponse =
                        (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 deletedrecord
                     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!

Leave a Reply