Sunday, February 3, 2008

Generate postImageEntityXml (MSCRM 3.0) equivalent in MS CRM 4.0 Plugins

If you worked on MS CRM 3.0 callouts, in the method signature of Pre/Post you get a string called as postImageEntityXml.

postImageEntityXml is nothing but an XML string that describes the entity after the assign operation was performed. This is a serialized version of DynamicEntity.

You can create the DynamicEntity Object using the Context Object.
DynamicEntity entity = (DynamicEntity)context.InputParameters.Properties["Target"];

Below is the code for MS CRM 4.0 which is equivalent of the postImageEntityXml string value in 3.0.

To implement this code functionality in plugin, use the Sample Plugin Code:
public class postImageEntityXmlExample : IPlugin

// This fucntion gets called from the EXECUTE method of plugin (marked in bold)

private string SerializeDynamicEntity(Microsoft.Crm.Sdk.DynamicEntity entity)
XmlSerializer serializer = new XmlSerializer(typeof(Microsoft.Crm.Sdk.DynamicEntity));
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
serializer.Serialize(writer, entity);
return writer.ToString();

private void WriteToFile(string message)
StreamWriter sw = new StreamWriter(@"c:\ErrorLog.txt", true);
catch (Exception ex)
//TODO Develop Code, if an Error comes while write to File

public void Execute(IPluginExecutionContext context)
DynamicEntity entity = null;

if (context.MessageName=="Create" context.MessageName == "Update")
if (context.InputParameters.Properties.Contains("Target") &&
context.InputParameters.Properties["Target"] is DynamicEntity)
entity = (DynamicEntity)context.InputParameters.Properties["Target"];

//call the below code to Serialize Dynamic Entity into postImageEntityXml
WriteToFile("\XML string \n" + SerializeDynamicEntity(entity));


Isn't it simple?
Happy MS CRM Development.

Comments are welcome..... :)

1 comment:

Amol G said...

Nice info Ranjit.
Most required code for any MS CRM developper!!!

-Amol Gholap