I’m trying to bind a plugin to the update contact event in Microsoft Dynamics CRM 2011.
I’ve made a plugin and i already registered the assembly and step for my organisation.
screenshot: CRM registration tool
For this moment, i’m using sample code for my plugin.
public class Plugin : IPlugin
{
public void 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)
{
throw new InvalidPluginExecutionException(
"An error occurred in the plug-in.", ex);
}
}
private static 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
};
crm.AddObject(note);
crm.SaveChanges();
}
}
}
But every time i modify a contact form and save it, i get this error:
The given key was not present in the dictionary
I’ve been looking for answers for a week now. I hope there is someone here who can guide me to the sollution for this problem. I can give every code or information you need. But for now, i can’t think of anything more that maybe can help you to see where my error is located. Any help is very much appreciated.
Thanks!
M.Medhat is absolutely correct, but let’s expand on it a bit more so you understand.
The first thing that you need to know is the difference between InputParameters vrs OutputParameters. A quick read at this MSDN article describing the difference between InputParameters and OutputParameters.
Make sure to note this statement:
Hence, this code would break:
Since you’ve already created an entity (by casting it off of InputParameters) you could delete that line and do something like this:
Don’t forget about tracing, it’s your best friend. It can show information when an exception is thrown. Here’s a good link on it: tracing