Menu Close

Micrsoft Dynamics CRM 2011 online – Retrieve Plugin

Retrieve
If  you want to write a plugin that executes every time a user opens a record.

Here is the Retrieve Code

First, create a new Plugin and sign the assembly with a key:


public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

if (context.Depth == 1)
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// Obtain the target entity from the input parmameters.
EntityReference entity = (EntityReference)context.InputParameters["Target"];

ColumnSet cols = new ColumnSet(
new String[] { "lastname", "firstname", "address1_name" });

var contact = service.Retrieve("contact", entity.Id, cols);

if (contact != null)
{
if (contact.Attributes.Contains("address1_name") == false)
{
Random rndgen = new Random();
contact.Attributes.Add("address1_name", "first time value: " + rndgen.Next().ToString());
}
else
{
contact["address1_name"] = "i already exist";
}
service.Update(contact);
}
}
}


Next, got to the Plugin Registration Tool (included with the CRM SDK) and register the plugin as follows:

image


What you’ll end up with in this example is:


On first open of the record:


clip_image002


On all future opens of the record:


clip_image002[5]



Share this:
Posted in Blog

Related Posts