I am writing my first plugin for CRM 2011 and followed the MS Tutorial here:http://msdn.microsoft.com/en-us/library/gg695782.aspx.
Everything works fine and it adds the note to a new contact. What I would like to do now is change the plugin to update the Middle Name of the Contact for example, so I tried doing something like: contact.MiddleName = "test"; but that does absolutely nothing. I would like to populate the Middle Name field when the Contact is created, but I don't know how to do this? In the Plugin registration I tried both Synchronous and Asynchronous but nothing really happens, the field is not populated.
Furthermore, how can I trigger the plugin upon update of the record? In the plugin registration tool I tried setting the Message to Update and the Event to 'Pre-Operation' but that does nothing.
Here is the code I am trying to use:
using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Xrm;
publicclass Plugin: IPlugin
{
publicvoid Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
Entity entity;
// Check if the input parameters property bag contains a target
// of the create operation and that target is of type Entity.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"]
is Entity)
{
// Obtain the target business entity from the input parameters.
entity = (Entity)context.InputParameters["Target"];
// Verify that the entity represents a contact.
if (entity.LogicalName != "contact") { return; }
}
else
{
return;
}
try
{
IOrganizationServiceFactory serviceFactory =
(IOrganizationServiceFactory)serviceProvider.GetService(
typeof(IOrganizationServiceFactory));
IOrganizationService service =
serviceFactory.CreateOrganizationService(context.UserId);
var id = (Guid)context.OutputParameters["id"];
AddNoteToContact(service, id);
}
catch (FaultException<OrganizationServiceFault> ex)
{
thrownew InvalidPluginExecutionException(
"An error occurred in the plug-in.", ex);
}
}
privatestatic
void AddNoteToContact(IOrganizationService service, Guid id)
{
using (var crm =
new XrmServiceContext(service))
{
var contact = crm.ContactSet.Where(
c => c.ContactId == id).First();
Debug.Write(contact.FirstName);
var note = new Annotation
{
Subject = "Created with plugin",
NoteText = "This Note was created by the example plug-in",
ObjectId = contact.ToEntityReference(),
ObjectTypeCode = contact.LogicalName
};
contact.MiddleName = "test"; //this is the only line I added, no errors, just does not populate the field
crm.AddObject(note);
crm.SaveChanges();
}
}
}
Thanks!