Reputation: 46
Trying to compare an existing date from an entity with current date. If entity field (testfield) of entity (testentity) date is equal to OR after current date, then add 1 year to the date in the field.
Issue - For some reason, its reading all the dates and comparing as well but not updating it in the field. I have used post operation step on the entity.
Update: I added ServiceContext.UpdateObject(entity) and ServiceContext.SaveChanges(); to the code but now its giving me "The context is not currently tracking..." error.
Any help would be deeply appreciated. Thanks!
Please take a look at following code.
public class PostUpdate: Plugin
{
public PostUpdate()
: base(typeof(PostUpdate))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "new_testentity", new Action<LocalPluginContext>(ExecutePostUpdate)));
protected void ExecutePostupdate(LocalPluginContext localContext)
{
// get the plugin context
IPluginExecutionContext context = localContext.PluginExecutionContext;
//Get the IOrganizationService
IOrganizationService service = localContext.OrganizationService;
//create the service context
var ServiceContext = new OrganizationServiceContext(service);
ITracingService tracingService = localContext.TracingService;
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];
// Verify that the target entity represents an account.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != "new_testentity")
return;
try
{
var k = entity["new_testfield"];
DateTime m = Convert.ToDateTime(k);
DateTime d = DateTime.Now;
int result = DateTime.Compare(m, d);
// compare the dates
if (result <= 0)
{
try
{
entity["new_testfield"] = DateTime.Now.AddYears(1);
ServiceContext.UpdateObject(entity);
}
ServiceContext.SaveChanges();
//Adding this is giving me "The context is not currently tracking the 'new_testentity' entity."
}
catch (FaultException<OrganizationServiceFault> ex)
{
}
}
}
//<snippetFollowupPlugin3>
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the FollupupPlugin plug-in.", ex);
}
//</snippetFollowupPlugin3>
catch (Exception ex)
{
tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
Upvotes: 0
Views: 5345
Reputation: 3878
You should register your plugin on the pre-operation step then simply add/change the appropriate value in the InputParameter
PropertyBag. That way your changes are inline with the transaction and you don't need a separate update call.
Upvotes: 3