Search code examples
dynamics-crmcrm

Dynamics 365 Plugin SDK throwing exception when updating a strongly typed entiy in sandbox mode


I'm an learning Dynamics 365 plugin development.

Problem: When invoking the Update method on a strongly typed entity, I an getting a exception. The exact error message is:

"System.Runtime.Serialization.SerializationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #1330ADC1"

My Setup: My solution contains a simple plugin. I have created a strongly typed entity Account. The plugin's Isolation mode is Sandbox. Telephone1 field is a string.

I retrieve the Account from CRM, then update the Telephone1 field to a new value and update the Account record. Simple :)

Code:

public class PostOperationaccountUpdate: IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        var organisationService = serviceProvider.GetService(typeof (IOrganizationService)) as IOrganizationService;
        var context = serviceProvider.GetService(typeof (IPluginExecutionContext)) as IPluginExecutionContext;

        var entityAccount = context.InputParameters["Target"] as Entity;
        var id = entityAccount.Id;

        var account = organisationService.Retrieve("account", id, new ColumnSet("telephone1"));

        //Get a strongly typed version of the Account entity
        var dbAccount = account.ToEntity<Account>();

        //Update the telephone1 field using the "old" way
        account["telephone1"] = "1234567890";

        try
        {
            //This will pass
            organisationService.Update(account);

            //Update the strongly typed Account
            dbAccount.Telephone1 = "plop";

            //This fails
            organisationService.Update(dbAccount);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

What have I tried: -> I have changed the plugin's Isolation mode to None - this works! According to the best practices, it isn't recommended

Thanks for the help Charles


Solution

  • A SerializationException occurs when you mix early-bound types with code expecting late-bound types, here the MSDN gives some degree of explanation.

    Essentially, the exception occurs when you require the platform to convert between early-bound and late-bound types.

    Update expects a late-bound type

    organisationService.Update(dbAccount); // dbAccount should be an 'Entity' object
    

    and this causes the exception.

    I never use early-bound types so I can't reliably tell how to fix your code, but the following MSDN articles should be useful: