Recently while trying to programmatically migrate Personal Email Templates between CRM organisations I got this error:
“An unhandled exception of type 'System.ServiceModel.FaultException`1' occurred in Microsoft.Xrm.Sdk.dll Additional information: An unexpected error occurred.”
Event Viewer didn’t give much more information either:
The Web Service plug-in failed in OrganizationId: 6608e5d4-4fef-e211-b192-00155d0c8332; SdkMessageProcessingStepId: 5dcabb1b-ea3e-db11-86a7-000a3a5473e8; EntityName: template; Stage: 30; MessageName: Create; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=220.127.116.11, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
After a lot of digging I found the problem to be in the templatetypecode.
While according to CRM this is an option set when you look at the attribute metadata is states that it is in fact an “EntityNameType” where other option sets are “PicklistTypes”.
So rather than taking the integer value of this option set I did in fact have to take the string.