Skip to main content

Notifications

Microsoft Dynamics 365 | Integration, Dataverse...
Suggested answer

Updating the field using C# plugin

Posted on by 30

32755.png

The scenario is :

In SaleOrder entity , i take 'orderId'  and 'Potential Customer' Name and concat it in 'name' field of same record. it work fine for create operation but not work for update operation. i register both step in pre-operation. 

Adding code for reference

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.IdentityModel.Metadata;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace CreateAndUpdate
{
public class OrderEntity : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
if (context.MessageName.ToLower() == "create")
{
Entity entity = (Entity)context.InputParameters["Target"];
{

var OrderId = entity.Attributes["ordernumber"].ToString();
string OrderIdOriginal = entity.GetAttributeValue<string>("ordernumber");

EntityReference Customer = (EntityReference)entity.Attributes["customerid"];
//Retriving customer Name based on a ID
var RetrviName = service.Retrieve(Customer.LogicalName, Customer.Id, new ColumnSet("name"));
//Getting Customer Name
var AccountName = RetrviName["name"].ToString();
var concat = OrderId + " " + AccountName;
entity.Attributes.Add("name", concat);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}

else if (context.MessageName.ToLower() == "update")
{
//Entity entity = (Entity)context.InputParameters["Target"];
Entity entity = service.Retrieve("salesorder", context.PrimaryEntityId, new ColumnSet("ordernumber", "customerid"));
try
{

var OrderId = entity.Attributes["ordernumber"].ToString();
string OrderIdOriginal = entity.GetAttributeValue<string>("ordernumber");

EntityReference Customer = (EntityReference)entity.Attributes["customerid"];
//Retriving customer Name based on a ID
var RetrviName = service.Retrieve(Customer.LogicalName, Customer.Id, new ColumnSet("name"));
//Getting Customer Name
var AccountName = RetrviName["name"].ToString();

var concat = OrderId + " " + AccountName;

entity.Attributes.Add("name", concat );

}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}
}

pastedimage1684066065798v2.png

pastedimage1684066131154v3.png

it work fine for create operation but not work for update operation
  • Suggested answer
    XM-22040801-0 Profile Picture
    XM-22040801-0 11 on at
    RE: Updating the field using C# plugin

    In update operation, you need pre-operation and pre-image.

    In the pre-image, add customerid and ordernumber fields.

    Change your code in "update" by this:

    Entity entity = (Entity)context.InputParameters["Target"];
    
    try
    {
        Entity preImage = (Entity)context.PreEntityImages["Image"];
    
        // Take the orderNumber from the Target if it exists, otherwise take it from the PreImage
        string orderNumber = entity.GetAttributeValue("ordernumber") ?? preImage.GetAttributeValue("ordernumber");
    
        // Take the customerRef from the Target if it exists, otherwise take it from the PreImage
        EntityReference customerRef = entity.GetAttributeValue("customerid") ?? preImage.GetAttributeValue("customerid");
    
        // Retrieve Customer and get the name
        var customer = service.Retrieve(Customer.LogicalName, customerRef.Id, new ColumnSet("name"));
        string accountName = customer.GetAttributeValue("name");
    
        // Set the name of the order
        entity.SetAttributeValue("name", $"{orderId} {accountName}");
    }
    catch (Exception ex)
    {
        throw new InvalidPluginExecutionException(ex.Message);
    }

    This code take the target values first, if not exist it take the pre-image values.

  • Ayush Solanki Profile Picture
    Ayush Solanki 30 on at
    RE: Updating the field using C# plugin

    The code is:

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    using System;

    using System.Collections.Generic;

    using System.IdentityModel.Metadata;

    using System.Linq;

    using System.Security.Principal;

    using System.Text;

    using System.Threading.Tasks;

    using System.Xml;

    namespace CreateAndUpdate

    {

       public class OrderEntity : IPlugin

       {

           public void Execute(IServiceProvider serviceProvider)

           {

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

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

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

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

               if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

               {

                   if (context.MessageName.ToLower() == "create")

                   {

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

                       try

                       {

                           var OrderId = entity.Attributes["ordernumber"].ToString();

                           EntityReference Customer = (EntityReference)entity.Attributes["customerid"];

                           //Retriving customer Name based on a ID

                           var RetrviName = service.Retrieve(Customer.LogicalName, Customer.Id, new ColumnSet("name"));

                           //Getting Customer Name

                           var AccountName = RetrviName["name"].ToString();

                           //myEntity.Id = entityId;

                           var concat = OrderId + " " + AccountName;

                           entity.Attributes.Add("name", concat);

                       }

                       catch (Exception ex)

                       {

                           throw new InvalidPluginExecutionException(ex.Message);

                       }

                   }

                   else if (context.MessageName.ToLower() == "update")

                   {

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

                       try

                       {

                           Entity postImageOrder = (Entity)context.PostEntityImages["Image"];

                           var OrderId = postImageOrder.Attributes["ordernumber"].ToString();

                           EntityReference Customer = (EntityReference)postImageOrder.Attributes["customerid"];

                           //Retriving customer Name based on a ID

                           var RetrviName = service.Retrieve(Customer.LogicalName, Customer.Id, new ColumnSet("name"));

                           //Getting Customer Name

                           var AccountName = RetrviName["name"].ToString();

                           var concat = OrderId + " " + AccountName;

                           entity.Attributes.Add("name", concat);

                           service.Update(entity);

                       }

                       catch (Exception ex)

                       {

                           throw new InvalidPluginExecutionException(ex.Message);

                       }

                   }

               }

           }

       }

    }

    Now it will get this error. "An item with the same key has already been added". when i update the record.

    For update operation , I add post operation and post Image .

  • Suggested answer
    XM-22040801-0 Profile Picture
    XM-22040801-0 11 on at
    RE: Updating the field using C# plugin

    Hi,

    Target contains only the modified fields.

    Target will be used by Dynamics to create/update your record in a pre-create/pre-update step: If you want to changes the data of the current record, do it in Target (like you do in Create message). In your code, you modify the record obtained by a retrieve, this record will not be updated by Dynamics.

    To avoid doing a retrieve (best practice), you can create a Pre-Image. Add the necessary fields (Order Number, Potential Customer) in the Pre-Image.

    To compute the name, look at the Target and Pre-Image. Example: If the user only change the Potential Customer, Target will not contains the Order number, so you need to get it from the Pre-Image.

    To learn more about Pre-Image: community.dynamics.com/.../pre-image-and-post-image-in-dynamics-crm

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,188 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,030 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans