Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Suggested answer

Updating an Entity record via a Plugin

Posted on by 20

I'm trying to understand how plug ins work. Specifically how the Pipeline Stages work.

I created a very simply book Entity.

What I was trying to do was after a new record is added to the database I wanted the price of the book to be incremented by 10%  GST.

I wanted this action to be carried out on the server side  by a plugin.

From the online documentation I read that the new record would be available in the database during the PostOperation  Stage  of the Create Step.

Can someone confirm that this is correct ?

This is not what i found.

Regardless what code i used i kept getting the error in the plugin code that the record i was trying to update did not exist.

I removed all the code from my plugin and replaced it all with a single line of code

 throw new Exception("just so we can debug");

As it states, i just wanted to kill the code from doing anything in the PostOperation stage so no changes are made to the record in the database..

After "save and close " of the new record the exception is thrown.  I then confirmed via the App and the Entity table that NO new record was created.

Since by the time the PostOperation  is called the new record should already safely exists in the entity table nothing i did in that event should affect it.

But the fact that the new record was NOT created says otherwise.

Can some explain why this is occurring.

And how would i update the record in the plugin when a users does a "Save" or Save close"  on a new record

Regards

Erick

  • Michel Gueli Profile Picture
    Michel Gueli 982 on at
    RE: Updating an Entity record via a Plugin

    Can i give you a tip? Try to write the plugin logic in a seperate class. Make the Plugin class, which implements IPlugin and has the Execute function, as dumb as possible. Then you can test this locally in Visual Studio to see what you're code is doing.

    public void Execute(IServiceProvider serviceProvider)

           {

               ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

               IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

               IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

               IOrganizationService service = factory.CreateOrganizationService(context.UserId);

               var book= context.GetTargetEntity();

               if (book!= null)

               {

                       var bookHandler= new BookHandler(service, trace);

                       bookHandler.IncreasePriceBy10Percent(book);

               }

           }

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Updating an Entity record via a Plugin

    Hi,

    You are sure correct, On Pre-validate stage you don't need to call Update method. Whatever attribute you set the Target Entity attribute will be saved to Database.

    When you enable profiler, system creates copy of the same steps in your instance. So it is always good idea to kill the profile before exporting the solution and import it into production instance otherwise you will have same code running twice. And in case if you are creating say Task record or any entity record from plugin you will see duplicat record getting created.

    I hope this clear your doubts.

    Please mark my answer verified if this is helpful!

    Regards,

    Bipin Kumar

    Follow my Blog: xrmdynamicscrm.wordpress.com/

  • ErickTreeTops Profile Picture
    ErickTreeTops 20 on at
    RE: Updating an Entity record via a Plugin

    Thank for you reply. My step is in the PreValidation of the Create step.  From my understanding the "Target" contains the data that is on it's way to be added to the database.  Any changes I make to the Entity in the "Target" will be persisted to the database.  Additionally at this stage there is no need to call the update method.  Once I turned off the profiler the code worked as expected.  I'm now adding to my  code to  have the same action occur during the Update message.  I just need to read up on preventing recursive updates before I implement.

  • Suggested answer
    Pradeep Rai Profile Picture
    Pradeep Rai 5,490 Super User 2024 Season 2 on at
    RE: Updating an Entity record via a Plugin

    Hi,

    You can refer below link to get more details about each stages and example.

    https://carldesouza.com/dynamics-365-plugin-execution-pipeline/

    Thanks,
    Pradeep.

  • Suggested answer
    Moh Helper Profile Picture
    Moh Helper 250 on at
    RE: Updating an Entity record via a Plugin

    Hi,

    I have some remarks about your code (The final answer is at the end) :

    - Did you register the plugin in the post operation stage ?

      If Yes , you have to change the '10' by '40'.  Because no data exists in the pre-validation of a "create" message.

    - Secondly you have to be sure that the field "new-price" is set in the creation of the book record.

    - Finally, you need to update your change about the new_gstprice because you are in the post-operation

    Example of code :

    Entity updateRecord = new Entity("book");

    updateRecord.Id = newRecord.Id;

    updateRecord.Attributes.Add("new_gstprice", new Money(price));

    service.update(updateRecord);

    But the good way it's to register your plugin in the pre-operation :

    - change the context.stage == '10" by context.stage == '20'

    And Normally all will work correctly.

    Here a draft schema to allow you to understand.

     Pre-Operation      Operation   Post-Operation

    Target contains the changes 

    All changes in the target will be taken care of the operation stage

    Record creation with the values in the target

    Target contains the values registered in the database. 

    If you need to update a value , you need to explicitely do an update

                                                                                           

    I hope I was able to help you.

    Kr,

    M.Helper                      

  • ErickTreeTops Profile Picture
    ErickTreeTops 20 on at
    RE: Updating an Entity record via a Plugin

    I killed the profiler I had running in the registration tool on the step I was debugging.  This prevented the unknown exception from.  My code seems to be working fine now.  Not really sure why the profile was causing the exception at the end of the plugin execution.  Perhaps some one can shed some light on this phenomena it.

  • ErickTreeTops Profile Picture
    ErickTreeTops 20 on at
    RE: Updating an Entity record via a Plugin

    Since the "new_gstprice" field is not set during the creation of a record it is not available as an Attribute.  That is why I added it.  I get an exception thrown on the Save and close of a new record.  But when I step through he plugin in debug mode all lines of the plug execute without an error.  The trace log also shows the last line of the plugin is executed without issue.  I am unable to determine what the issue is.

  • ErickTreeTops Profile Picture
    ErickTreeTops 20 on at
    RE: Updating an Entity record via a Plugin

    namespace Library
        {
        public class CalcGSTPrice : IPlugin
            {
            public void Execute(IServiceProvider serviceProvider)
                {
                try {
                        //Obtain the execution context from the service provider.
                        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                        
                        // create a trace log so you can see where in the code it breaks
                        ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                        
                        // create access to service
                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
                        tracingService.Trace("have reached execute event in plugin.");
    
                        // get a reference to the newly added record.
                        Entity newRecord = (Entity)context.InputParameters["Target"];
                    if (newRecord != null)
                        {
                        // are we in a 'create' message occuring during the Prevalidation Event
                        if (context.MessageName.ToLower() == "create" && context.Stage == 10)
                            {
                            if (newRecord.Contains("new_price"))
                                {
                                // Get price of book
                                Decimal price = newRecord.GetAttributeValue("new_price").Value;
                                // increase price of book by 10%
                                price = Decimal.Multiply(price, (Decimal)1.1);
                                // create new attribute and set value to new price of book
                                newRecord.Attributes.Add("new_gstprice", new Money(price));
                                tracingService.Trace("Update of new_gstprice has completed");
                                }
                            }
                        }
                        tracingService.Trace("Last line of plugin execute method reached");
                    return;
                } catch (Exception ex )
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }
                }
            }
        
        }

  • Moh Helper Profile Picture
    Moh Helper 250 on at
    RE: Updating an Entity record via a Plugin

    Hi,

    Can you share your code to see where is the problem ?

    Kr,

    M.Helper

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Updating an Entity record via a Plugin

    Hi,

    If Price field is present of Book entity itself then you can write you code in Pre-operation plugin.

    No need to write the code and register in Post Operation Plugin.

    Sample Code -

    Entity entity=(Entity)context.InputParameters["Target"];

    //Check if Price value if entered by the user

    if(entity.Attributes.Contains("new_bookprice"))

    {

    // Get the price field value

    Decimal price=((Money)entity.Attributes["new_bookprice"]).Value;

    Decimal increasePriceBy10Percentage=price+(price*10/100);

    entity["new_bookprice"]=new Money(increasePriceBy10Percentage);

    }

    else

    {

    // if book price is not entered by user

    // What value is to be stored in Book Price field?

    }

    Please mark my answer verified if this is helpful!

    Regards,

    Bipin Kumar

    Follow my Blog: xrmdynamicscrm.wordpress.com/

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!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans