1
votes

Is it possible to delete entity while same is still in plugin update transaction?

It seems following code is not working. I need to delete entity when its get updated and some other circumstances

Something like:

protected void ExecutePosAnnotationtUpdate(LocalPluginContext localContext)
{
    if (localContext == null)
    {
        throw new ArgumentNullException("localContext");
    }

    if (localContext.PluginExecutionContext.Depth > 1) return;


    Entity postEntityImage = null;
    if (localContext.PluginExecutionContext.PostEntityImages.Contains("PostImage"))
    {
        if (localContext.PluginExecutionContext.PostEntityImages["PostImage"] != null)
        {
            postEntityImage = localContext.PluginExecutionContext.PostEntityImages["PostImage"];
        }
    }

    Entity preEntityImage = null;
    if (localContext.PluginExecutionContext.PreEntityImages.Contains("PreImage"))
    {
        if (localContext.PluginExecutionContext.PreEntityImages["PreImage"] != null)
        {
            preEntityImage = localContext.PluginExecutionContext.PreEntityImages["PreImage"];
        }
    }

    if ((bool)postEntityImage.Attributes["isdocument"])
    {
        if ( some condition )
            localContext.OrganizationService.Delete(postEntityImage.LogicalName, postEntityImage.Id);
    }
}

`

1
Did you try to register your plugin on the async update stage? - Henk van Boeijen
I'm curious: are you attempting to prevent users from uploading files in notes ? - Alex
@Alex :) Yes almost you're right .. I want to move attachment on update event - user3499805
If you're on prem you can turn on the tracing and see more detailed errors to be able to determine what's going on. - Rickard N

1 Answers

1
votes

Since you're updating, the record is there in Target.

public void Execute(IServiceProvider serviceProvider)
{
    var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    var service = serviceFactory.CreateOrganizationService(context.UserId);

    var target = context.InputParameters["Target"] as Entity;
    var condition = /* whatever */ 
    if(condition)
    {
        service.Delete(target.LogicalName, target.Id);
    }
}

Works as expected when attached to Update message, Post-Operation, Asynchronous. Works inside the Sandbox, also.

Records will not disappear at once, it takes some time (~20 seconds on my on-premise playground). If you make it Synchronous it will still work but alerts are going to come up because data disappears while being handled by the CRM during the update.