Showing posts with label Assign. Show all posts
Showing posts with label Assign. Show all posts

Monday, February 23, 2009

Using Assign Message in CRM 4.0 Plugin

Assign message is very usefull if you want to store history of all owners of a record with Start and End Date. Following code sample can be used to do this:


public void Execute(IPluginExecutionContext context)
{
if (context.InputParameters.Properties.Contains("Target") && context.InputParameters.Properties["Target"] is Moniker)
{
Moniker moniker = (Moniker)context.InputParameters.Properties["Target"];
Guid id = moniker.Id;
ICrmService crmService = context.CreateCrmService(true);
DynamicEntity PreImage = null;
DynamicEntity PostImage = null;
//Get the Pre and Post Images
if (context.PreEntityImages.Properties.Contains("Images") && context.PreEntityImages.Properties["Images"] is DynamicEntity)
{
PreImage = (DynamicEntity)context.PreEntityImages.Properties["Images"];
}
if (context.PostEntityImages.Properties.Contains("Images") && context.PostEntityImages.Properties["Images"] is DynamicEntity)
{
PostImage = (DynamicEntity)context.PostEntityImages.Properties["Images"];
}
if (PreImage != null && PostImage != null)
{
Guid? keyWorkerIdPre = Utils.GetOwnerId(PreImage, "ownerid");
Guid? keyWorkerIdPost = Utils.GetOwnerId(PostImage, "ownerid");
if (keyWorkerIdPre != keyWorkerIdPost)
{
//Close previous involvement records for this user
if (keyWorkerIdPre.HasValue)
{
CloseKeyWorkerRecord(id,keyWorkerIdPre.Value, crmService);
}
if (keyWorkerIdPost.HasValue)
{
CreateKeyWorkerHistoryRecord(id, keyWorkerIdPost.Value, crmService);
}
}
}
}
}


//GetOwnerId function


public static Guid? GetOwnerId(DynamicEntity entity, string attributeName)
{
attributeName = attributeName.ToLower();
if (entity.Properties.Contains(attributeName))
{
return ((Owner)entity.Properties[attributeName]).Value;
}
else
{
return null;
}
}