CRM 4.0 Plugins are a way to integrate custom business logic into CRM 4.0's platform. Here are the high-level steps to follow in plugin creation and registration. For the plugin registration, Plugin Registration Tool for CRM 4.0 delivered with CRM 4.0 SDK is used.
Implement Plugin
- Visual Studio class library project can be used to implement plugins
- Inherit the class from IPlugin class
- Implement "Execute" method taking IPluginExecutionContext type context as a parameter as follows
public void Execute(IPluginExecutionContext context)
- Here is a sample "Execute" method implemented for Opportunity entity
public void Execute(IPluginExecutionContext context)
{
string m_OpportunityName = string.Empty;
string m_OpportunityId = string.Empty;
if (context.MessageName.Equals("Create"))
{
// Entity creation.
DynamicEntity postEntity;
if (context.PostEntityImages.Contains("Target"))
{
postEntity = ((DynamicEntity)context.PostEntityImages["Target"]);
if (postEntity.Properties.Contains("opportunityid"))
{
Key opportunityId = (Key)postEntity.Properties["opportunityid"];
if (opportunityId != null)
{
m_OpportunityId = opportunityId.Value.ToString();
}
}
if (postEntity.Properties.Contains("name"))
{
m_OpportunityName = postEntity.Properties["name"].ToString();
}
}
}
else if (context.MessageName.Equals("Update"))
{
// Entity update.
DynamicEntity pretEntity;
DynamicEntity postEntity;
if (context.PreEntityImages.Contains("Target"))
{
pretEntity = ((DynamicEntity)context.PreEntityImages["Target"]);
}
if (context.PostEntityImages.Contains("Target"))
{
postEntity = ((DynamicEntity)context.PostEntityImages["Target"]);
}
if (postEntity.Properties.Contains("opportunityid"))
{
Key opportunityId = (Key)postEntity.Properties["opportunityid"];
if (opportunityId != null)
{
m_OpportunityId = opportunityId.Value.ToString();
}
}
if (postEntity.Properties.Contains("name"))
{
m_OpportunityName = postEntity.Properties["name"].ToString();
}
}
}
Register Plugin
Copy plugin dll(s) to "……\Program Files\Microsoft Dynamics CRM\Server\bin\assembly"
Run "Plugin Registration Tool" come with the SDK to register the plugin for an entity.
Then create a step for "Create" and another step for "Update". "Create Step" executes the plugin in new entity instance creation, while "Update Step" executes the plugin in entity update.
Then create a "Post Image" for "Create Step" and "Pre Image" and a "Post Image" for "Update step".
That is it. If the Steps are created as "Synchronous", plugin can be debugged by attaching to "w3wp.exe" process. If the Steps are created as "Asynchronous", plugin can be debugged by attaching to "CrmAsyncService.exe" process.
One thing that should be noted is, Active Directory account used to deploy and register new assembly has to be added into "Deployment Administrators" group in CRM Deployment Manager. Having assigned only "System Administrator" role is not sufficient for this task.