Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Suggested answer

How to retrieve audit history

Posted on by 250

Hello everyone my name is Taniguchi

I'm using C# plugin to retrieve audit history for the opportunity entity and i wish to retrieve every field that were changed and i was able to retrieve audit details like creadon, action and operation now I wish to retrieve the fields that were changed and old and new value. How could can i get this values in plugin ?

My code so far:

string EntitySchemaName = "opportunity";
foreach (var opportunityRecords in result.Entities)
{
    string opportunityGUID = opportunityRecords.Attributes["opportunityid"].ToString();
    string opportunityNumber = opportunityRecords.Attributes["vale_opportunitynumber"].ToString();
    Guid _opportunityID =  new Guid(opportunityGUID);
    // Retrieve the audit history for the account and display it.
    RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
    changeRequest.Target = new EntityReference(EntitySchemaName, _opportunityID);
    RetrieveRecordChangeHistoryResponse changeResponse = (RetrieveRecordChangeHistoryResponse)organizationService.Execute(changeRequest);
     AuditDetailCollection details = changeResponse.AuditDetailCollection;
    foreach (var  attrAuditDetail in details.AuditDetails)
    {
        var detailType2 = attrAuditDetail.GetType();
        if (detailType2 == typeof(Microsoft.Crm.Sdk.Messages.AttributeAuditDetail))
        {
            Microsoft.Crm.Sdk.Messages.AttributeAuditDetail attributeDetail = (Microsoft.Crm.Sdk.Messages.AttributeAuditDetail)attrAuditDetail;
            //Details of Audit
            var auditDetailsRequest = new Microsoft.Crm.Sdk.Messages.RetrieveAuditDetailsRequest
            {
                AuditId = attributeDetail.AuditRecord.Id
            };
            var auditDetailsResponse = (Microsoft.Crm.Sdk.Messages.RetrieveAuditDetailsResponse)organizationService.Execute(auditDetailsRequest);
            if (auditDetailsResponse != null && auditDetailsResponse.AuditDetail != null && auditDetailsResponse.AuditDetail.AuditRecord != null)
            {
                Microsoft.Xrm.Sdk.Entity auditEntity = auditDetailsResponse.AuditDetail.AuditRecord;
                    if (auditEntity.Attributes.Contains("createdon"))
                    {
                        Console.WriteLine(string.Format("Audit2 CreatedOn {0}", auditDetailsResponse.AuditDetail.AuditRecord.Attributes["createdon"]));
                    }
             }
        }
    }
}

  • Suggested answer
    Thomas David Dayman Profile Picture
    Thomas David Dayman 11,323 on at
    RE: How to retrieve audit history

    Hi,

    I have some working code below:

     if (Service != null)
                {
                    RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                    try
                    {
                        Guid guid = TrimGuid(recordGuid.Text);
    
                        changeRequest.Target = new EntityReference(entitiesList.SelectedItem.ToString(), guid);
                        RetrieveRecordChangeHistoryResponse changeResponse =
                        (RetrieveRecordChangeHistoryResponse)Service.Execute(changeRequest);
    
                        AuditDetailCollection auditDetailCollection = changeResponse.AuditDetailCollection;
    
                        Entity entity = Service.Retrieve(entitiesList.SelectedItem.ToString(), guid, new ColumnSet(true));
    
                        foreach (var attrAuditDetail in auditDetailCollection.AuditDetails)
                        {
                            var detailType = attrAuditDetail.GetType();
                            if (detailType == typeof(AttributeAuditDetail))
                            {
                                var auditRecord = attrAuditDetail.AuditRecord;
                                var attributeDetail = (AttributeAuditDetail)attrAuditDetail;
    
                                var newValueEntity = attributeDetail.NewValue;
                                var oldValueEntity = attributeDetail.OldValue;
                                TargetEntity = new Entity(oldValueEntity.LogicalName, oldValueEntity.Id);
    
                                var action = auditRecord.FormattedValues["action"];
                                if (Array.Exists(ValidActions, x => x == action))
                                {
    
                                    foreach (KeyValuePair attribute in attributeDetail.NewValue.Attributes)
                                    {
                                        string fieldmetadata = "";
                                        string lookupId = "";
                                        string oldValue = "";
                                        string newValue = "";
    
                                        if (attributeDetail.OldValue.Contains(attribute.Key))
                                        {
                                            lookupId = GetLookupId(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                            fieldmetadata = GetFieldMetaData(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                            oldValue = GetFieldValue(attribute.Key, attribute.Value, oldValueEntity, oldValueEntity[attribute.Key].ToString());
                                        }
                                        newValue = GetFieldValue(attribute.Key, attribute.Value, newValueEntity, newValueEntity[attribute.Key].ToString());
    
                                        CreateAuditRecord(auditRecord.Attributes["auditid"], auditRecord.Attributes["createdon"], ((EntityReference)auditRecord.Attributes["userid"]).Name,
                                            auditRecord.FormattedValues["action"], attribute.Key, oldValue, newValue, attribute.Value, fieldmetadata, lookupId);
                                    }
    
                                    foreach (KeyValuePair attribute in attributeDetail.OldValue.Attributes)
                                    {
                                        if (!attributeDetail.NewValue.Contains(attribute.Key))
                                        {
                                            string fieldmetadata = "";
                                            string loookupId = "";
                                            string newValue = "";
    
                                            loookupId = GetLookupId(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                            fieldmetadata = GetFieldMetaData(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                            string oldValue = GetFieldValue(attribute.Key, attribute.Value, oldValueEntity, oldValueEntity[attribute.Key].ToString());
    
                                            CreateAuditRecord(auditRecord.Attributes["auditid"], auditRecord.Attributes["createdon"], ((EntityReference)auditRecord.Attributes["userid"]).Name,
                                              auditRecord.FormattedValues["action"], attribute.Key, oldValue, newValue, attribute.Value, fieldmetadata, loookupId);
    
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (InvalidPluginExecutionException ex)
                    {
                        MessageBox.Show($"An error occurred: {ex.Message}");
                    }
                    catch (FaultException ex)
                    {
                        MessageBox.Show($"An error occurred: {ex.Message}");
                    }
                    catch (TimeoutException ex)
                    {
                        MessageBox.Show($"An error occurred: {ex.Message}");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"An error occurred: {ex.Message}");
                    }
                }
            }

    Hopefully this is helpful

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,269 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,198 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans