Search code examples
pluginsdynamics-crm-4

How to update a Dynamics CRM 4.0 custom property within an IPlugin context


I'm dealing with a custom (extended) property of a default Entity (email) within a plug-in context and despite the approach works for creation (.Add()) it does not for updates (nor is an .Update() method associated). Here´s the actual code:

public class EmailPreCreateHandler : IPlugin
{
        DynamicEntity dynamicEntity;

        if (context.InputParameters.Properties.Contains("Target")
            && context.InputParameters.Properties["Target"] is DynamicEntity)
        {
            dynamicEntity = (DynamicEntity)context.InputParameters.Properties["Target"];

            if (dynamicEntity.Name != EntityName.email.ToString()) { return; }
        }
        else { return; }

        try
        {
            if (dynamicEntity.Properties.Contains("new_property1")
                || dynamicEntity.Properties.Contains("new_property2"))
            {
                var new_property3 = new CrmBooleanProperty("new_property3", new CrmBoolean(true));
                dynamicEntity.Properties.Add(new_property3);
            }
        }
        catch (SoapException exception)
        {
            throw new InvalidPluginExecutionException(
                "An error occurred with the plug-in.", exception);
        }
    }
}

I was wondering if I should do something like this to make it work?

dynamicEntity.Properties.Remove(new_property3);
dynamicEntity.Properties.Add(new_property3);

Registration details

(Assembly)

  • Location: Database

(Step)

  • Message: Create
  • Primary Entity: email
  • Secondary Entity: none
  • Filtering Attributes: All Attributes
  • Run in User's Context: Calling User
  • Execution Order: 1
  • Eventing Pipeline Stage of Execution: Pre Stage

I will really appreciate any feedback. Thanks much in advance,


Solution

  • It looks like you would add/update new_property3 if either new_property1 or new_property2 are present.

    if (dynamicEntity.Properties.Contains("new_property1") || dynamicEntity.Properties.Contains("new_property2"))
    {
      dynamicEntity["new_property3"] = new CrmBoolean(true);
    }
    

    If you access dynamicEntity["new_property3"] for write access it will either create the property, if it does not exist or overwrite the existing value.