Question

I want to create an auditing plugin that whenever a "contact" entity is changed, a "historical contact" entity is created that had all the data of the old "contact" entity before the change.

My question is, if I have a lookup field in "contact" to "accounts", how do I get this lookup to the specific "account" and place it in the lookup field for the "historical contact" entity?


I completed the plugin, but now there is a new issue.

The "contact" entity can have a blank in the "first name" field.

The "historical contact" entity has "first name" as its primary field, although it is not required.

If there is no "first name" when creating "historical contact" entity it throws an error. I do not know why this is.

Do I need a primary field to create an entity even if the field is labeled to have "no constraint"?

Was it helpful?

Solution

You have two options:

1) create a plugin along the lines of the following:

public void Execute(IServiceProvider serviceProvider)
{
    var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    var service = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(context.UserId);

    var originalContact = context.InputParameters["Target"] as Entity;
    var newContact = new Entity("new_historicalcontact");
    if (originalContact.Contains("firstname"))
    {
        newContact.Add("new_firstname", orginalContact["firstname"]);
    }
    if (originalContact.Contains("emailaddress1"))
    {
        newContact.Add("new_emailaddress1", orginalContact["emailaddress1"]);
    }
    if (originalContact.Contains("parentcustomerid"))
    {
        newContact.Add("new_parentcustomerid", orginalContact["parentcustomerid"]);
    }

    //etc etc for other properties
    service.Create(newContact);
}

if you aren't familiar with plugins, there are plenty of tutorials around, you can start with something like the recommendation I gave in this question

2) use the out of the box auditing features. May or may not be what you are looking for but you can read more about that here and here

OTHER TIPS

I'm not sure I follow. You're creating a full copy of a contact when something changes? To do that is be quite simple with a Pre Image on the Post Execute of Update message. The Pre Image is a snapshot of the contact before the update.

But why aren't you using the provided Auditing functionality?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top