Entity Image Byte Data to Base 64 Workflow C#
Recently in my current project there is a requirement of converting Entity Image Byte Data to Base 64 Data. After that they will use base 64 data in SSRS Reports.
Here is my generic workflow code which will take 2 inputs from user, first one is Entity image field schema name and second one is target field to store base 64 data.
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;
namespace EntityImageByteDataToBase64Workflow
{
public class ByteTobase64 : CodeActivity
{
public InArgument<string> ImageFieldSchemaName { get; set; }
public InArgument<string> Base64dataField { get; set; }
public Guid RecordID { get; set; }
protected override void Execute(CodeActivityContext context)
{
ITracingService tracingService = context.GetExtension<ITracingService>();
IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);
Entity PreImage = workflowContext.PreEntityImages;
RecordID = PreImage.Id;
tracingService.Trace("Near to find the entityimage field");
tracingService.Trace("EntityId" + RecordID);
tracingService.Trace("Fieldname = " + ImageFieldSchemaName.Get<string>(context));
tracingService.Trace("Condition = " + PreImage.Contains(ImageFieldSchemaName.Get<string>(context)));
byte[] etityImageFile = getEntityImageData(PreImage.Id, PreImage.LogicalName, ImageFieldSchemaName.Get<string>(context), service);
tracingService.Trace("Got the entityimage field");
tracingService.Trace("entityImageData"+ etityImageFile);
string base64 = covertByteArrayToBase64(etityImageFile);
tracingService.Trace("base64Data" + base64);
if (base64 != null)
{
Entity ent = new Entity(PreImage.LogicalName);
ent.Id = PreImage.Id;
ent = base64;
tracingService.Trace("Going To Update");
service.Update(ent);
tracingService.Trace("Updated");
}
}
public string covertByteArrayToBase64(byte[] etityImageFile)
{
String B64String = Convert.ToBase64String(etityImageFile);
return B64String;
}
public byte[] getEntityImageData(Guid EntityID, string LogicalName, string ImageFieldSchema ,IOrganizationService service)
{
Entity entitydata = new Entity();
entitydata = service.Retrieve(LogicalName, EntityID, new ColumnSet(ImageFieldSchema));
Byte[] imagedata = new byte[0];
if (entitydata.Contains(ImageFieldSchema) && entitydata.Attributes[ImageFieldSchema] != null)
{
imagedata = (byte[])entitydata.Attributes[ImageFieldSchema];
}
return imagedata;
}
}
}