How to Set the Entity Image on a Contact in Dynamics 365 Using C#

Adam Murchison, 05 April 2019


When trying to set an entity image for a contact programmatically it may seem logical that you would set it using the base64 string of an image just like you would set the ‘documentbody’ field in an annotation, but this is not the case for entity image. When deciding on an entity image for the contact it is recommended by Microsoft to use a 144x144.png for best results. Other viable dimensions are: 60x80, 144x400, 400x500, 400x144 which is all noted in Microsoft’s documentation here.

When uploading a base 64 string to the ‘entityimage’ field you will be presented with the following error:

"Message": "An error has occurred.",

"ExceptionMessage": "Type Mismatch: Type of Attribute: Contact.entityimage is: System.Byte[]. However, Type of passed-in value is: System.String",

"ExceptionType": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",

"StackTrace": "\r\nServer stack trace: \r\n at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)\r\n at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)\r\n at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)\r\n at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)\r\n\r\nException rethrown at [0]: \r\n at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)\r\n at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)\r\n at Microsoft.Xrm.Sdk.IOrganizationService.Update(Entity entity)\r\n at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.UpdateCore(Entity entity)\r\n at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Update(Entity entity)\r\n at Test.Web.API.Controllers.AccountController.Index() in C:\\Projects\\Test\\Test\\Test.Web.API\\Controllers\\AccountController.cs:line 67"

The key part of this error is that you’re setting the attribute ‘entityimage’ to a string rather than setting it to a byte[].

Entity update = new Entity("contact", id);

update["entityimage"] = Convert.FromBase64String(base64img);


Note: Convert.FromBase64String function returns a byte array and OSM is the organization service manager which connects to Dynamics 365. This is a standard update request.

This is how to set the entity image in C# when you have the base 64 string of an image.