Hi,
A Newbie here! I am trying my hands on Dynamics programming and testing out a basic code to update a custom entity that I created in a plugin.
Task I am trying to code is: when "sales rep" is assgined to to a zone (custom field "crdc2_repinzoneid") set field "status" (type:two option, name:crdc2_status) to "assigned" (See screenshot below)
Step is registered to fire on Entity Update at PostOperation (see screenshot below).
This is what I did in plugin code:
1. Create a new entity "sales rep" using context.PrimaryEntityId
Entity salesRep = new Entity("crdc2_salesrep", context.PrimaryEntityId);
2. Create attribute which needs to be updated:
salesRep["crdc2_status" = entity["crdc2_repinzoneid" == null ? false : true; //set value
3. Fire Update
service.Update(salesRep);
I debugged the plugin and at #3 I get the exception System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary
I fail to understand the reason here. The name "crdc2_status" exists in "crdc2_salesrep" entity.
What am I missing here!
Code:
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
tracingService.Trace("SalesRepAssignedPlugin plgin: start execution4");
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
try
{
Entity entity = (Entity)context.InputParameters["Target"];
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.UserId);
if (entity.LogicalName != "crdc2_salesrep")
return;
//create new entity with only fields that needs to be updated
Entity salesRep = new Entity("crdc2_salesrep", context.PrimaryEntityId);
//create attrib to update
salesRep["crdc2_status"] = entity["crdc2_repinzoneid"] == null ? false : true; //set value
service.Update(salesRep);
}
catch (FaultException ex)
{
tracingService.Trace("SalesRepAssignedPlugin plgin ex: {0}", ex.ToString());
throw new InvalidPluginExecutionException("SalesRepAssignedPlugin plgin:siyapa!", ex);
}
catch (Exception ex)
{
tracingService.Trace("SalesRepAssignedPlugin plgin ex: {0}", ex.ToString());
throw;
}
}
Custom Entity Fields
Plugin step:
Thanks,
Jags