A Plugin is a very powerful tool to extend the out-of-the-box functionality of Dynamics CRM 2011. You can integrate your custom business logic with Microsoft Dynamics CRM to modify or augment the standard behaviour of the platform. You can visit here to know more about Plugin Development.
*
In my previous blog posts I have shown you how to write a Naming Plugin that registered for “Post-Update” operation, now I will show you how to modify the code, to make my Naming Plugin work for “Pre-Update-operation”.
In short, if we register our Plugin on “Pre-Update” operation, our code will be executed before the changes being saved to database. It is not hard to guess what “Post-Update” means - our plugin will be executed after the “Update” operation. If you want to compare these two ways of writing plugins, you can check out my previous post here.
Firstly we will change the HandleUpdate function to:
private void HandleUpdate(Guid meetingId, Entity changedMeeting)
{
Entity oldMeeting = _sdk.Retrieve("meeting", meetingId, new ColumnSet(true));
changedMeeting.MergeWith(oldMeeting);
HandleGeneric(changedMeeting);
}
As you notice, I took out the “updating” Boolean field, as we will use the same way to handle “Create” “Update” operation. Then change the HandleGeneric function to the one below:
private void HandleGeneric(Entity meeting)
{
// Get the meeting time
DateTime meetingTime = meeting.Get<DateTime>("new_time");
// Get the name of Contact
Guid meetingContactId = meeting.Get<Guid>("new_with");
Entity meetingContact = _sdk.Retrieve("", meetingContactId, new ColumnSet("fullname"));
string meetingContactName = meetingContact.Get<string>("fullname");
// Get the place
string meetingPlace = meeting.Get<string>("new_place");
string nameCreated = GenerateName(meetingTime.ToString("dd/MM/yyyy"), meetingContactName, meetingPlace);
meeting["new_name"] = nameCreated;
}
Now we don’t need to call the UpdateCrm function anymore, as we registered our step as “Pre-Update”, CRM will save our meeting entity into database once it finishes executing our plugin.
Finally we need to change the way to call these two functions:
if (_context.MessageName.Equals("create", StringComparison.InvariantCultureIgnoreCase))
{
HandleGeneric(target);
}
else if (_context.MessageName.Equals("update", StringComparison.InvariantCultureIgnoreCase))
{
HandleUpdate(_context.PrimaryEntityId, target);
}
As you can see, the code for developing a plugin on “Pre” stage is much simpler, and the performance is much better, as CRM doesn’t need to save a record into database twice, so the system will run faster and steadier, as there is less code.
*Image source: http://msdn.microsoft.com/en-us/library/gg327941.aspx