Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)
Answered

Prevent delete of Record

Posted on by 6,203

Hi All,

On a delete operation, i want to prevent delete of record and inactive that record.

Any help would be appraicted.

Regards,

Shahbaaz

*This post is locked for comments

  • Suggested answer
    Kjeld Poulsen Profile Picture
    Kjeld Poulsen 180 on at
    RE: Prevent delete of Record

    This approach actually works (update the target for delete onvalidatedelete, and then prevent the delete onpredelete or onpostdelete)

    it will updates the "entity to be deleted", and still gives the business process errors - preventing the delete

    There are two drawbacks in the approach

    1) The UI will no update immidiatly. You have to press F5 or similar to get the new values of fields

    2) OnValidateDelete does not trigger on cascade delete. The result is, that if the reason for delete comes from a parent with cascade delete configured, the OnValidateDelete will not trigger, and the record will be left unchanged in this situation.

    Otherwise it is a prettye good solution.

  • Suggested answer
    Iron Arm Profile Picture
    Iron Arm 129 on at
    RE: Prevent delete of Record

    Wow.  You don't have to do all that.  

    In the plug-in registration tool, you have it trigger on the "Delete" message.  So you know context.MessageName equals "Delete", you don't have to check that.  You don't have to check context.Stage either.  Create a "preImage".   Then instead of putting a condition on InputParameters you put a condition on PreEntityImages.  The meat of the plug-in literally only needs to be 3 lines (inside your try/catch). 

    if (context.PreEntityImages.Contains("preImage") && context.PreEntityImages["preImage"] is Entity) {
        throw exception
    }

  • Peter Hale - QLD Profile Picture
    Peter Hale - QLD 480 on at
    RE: Prevent delete of Record

    Agree with  Wei Jie Fun

    This should be the first and only option  -  In fact, delete should be removed from everyone (all types records) except a select few high level users and even then it is questionable.

    It should be a periodic review of deactivated records and only someone with System Admin role should delete (even then supervised) - because there is no recovery for erros

    Even then, doesn't seem to work for activities but i'm working on that

    Pete

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Prevent delete of Record

    @Alex :   client didn't liked the plugin approach to stop user from deleting the record, instead we removed the rights for the user and it worked.

  • Rawish Kumar Profile Picture
    Rawish Kumar 13,756 on at
    RE: Prevent delete of Record

    great!

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Prevent delete of Record

    Thank you every one for the help, very much appreciated.

    Below is the code that worked for me, on the pre validation i deactivated the record and on post operation trigger exception with the message.

    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk;
    using System;
    using System.Xml;
    
    
    namespace PreOperationPluginDemo
    {
        public class PreOperation : IPlugin
        {
    
            public void Execute(IServiceProvider serviceProvider)
            {
                // for tracing the service value
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                // obtain exexution context from service provider
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    
                IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = factory.CreateOrganizationService(context.UserId);
    
                tracingService.Trace("depth" + context.Depth.ToString());
                // check the depth of the plugin 
                //if (context.Depth > 1)
                //{
                //    return;
                //}
                //else
                //{
                try
                {
    
    
                    if (context.MessageName == "Delete")
                    {
                        EntityReference entityReference = (EntityReference)context.InputParameters["Target"];              
                        if (context.Stage == 10)//Pre Stage
                        {
                            tracingService.Trace("in 10 number");
                            service.Execute(new SetStateRequest
                            {
                                EntityMoniker = new EntityReference("contact", entityReference.Id),
                                State = new OptionSetValue(1),
                                Status = new OptionSetValue(2)
                            });
                        }
                        else if (context.Stage == 40) //Post Stage
                        {
                            tracingService.Trace("in 40");
                            throw new InvalidPluginExecutionException("test");
                        }
                        //Code to be executed during Delete event of an entity
                    }
    
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Exception : " + ex.Message);
                    throw new InvalidPluginExecutionException(ex.Message.ToString());
    
                }
            }
            //}
        }
    }
    


  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Prevent delete of Record

    Shahbaaz, 

    My apologies ! Me too tried with different approach , seems this is not working as we can not set order in the workflow and second due to transaction, no matter we are creating two workflow ,its executing in same transaction. So its not working using OOB workflow as well.

    Using plugin you will also face same issue , you can not pop out message in the same transaction saying Business Process Error.

    There is two approach you can follow.

    First show error using workflow while delete the record, saying that you can not delete the record , rather deactivate the record .

    Second approach will be remove delete permission from the entity.

    Hope this helps.

  • Verified answer
    Kokulan Profile Picture
    Kokulan 18,048 on at
    RE: Prevent delete of Record

    Hi

    I have done a bit of testing on the solution i suggested above, the reason for it not working is that when it executes the Stop step with Cancel status, it also cancels the child workflow it initiated.

    I know you can simply remove the delete privilege but you may want to prevent even Sys Admins deleting it.

    If you create plugins on Pre Validation and post operation of Delete message and make the record inactive in pre-validation (any DB operation at pre-validation stage wont be rolled back)

    and then in your post operation of delete throw an invalid plugin exception

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Prevent delete of Record

    @Goutam, but it will delete the record, please can u provide the screenshot ?

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Prevent delete of Record

    Wei Jie Fun, that is the last option

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

New! Quick response templatesâš¡

Save time with the new custom templates!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,219 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,056 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans