Create and Update Rows Using a Plugin in Microsoft Dynamics CE (CRM)

Microsoft Dynamics CRM is a powerful Customer Relationship Management (CRM) tool that helps businesses manage customer interactions and streamline various processes. One of the key features of Dynamics CRM is the ability to use plugins to extend its functionalities and customize data operations. In this article, we will explore how to create, update, and delete rows using a plugin in Microsoft Dynamics CRM, along with code snippets to guide you through the process.

What is a Plugin in Microsoft Dynamics CRM(CE)?
A plugin in Microsoft Dynamics CRM(CE) is a custom business logic that can be registered and executed in response to specific events or messages. Plugins enable developers to automate tasks, modify data, and perform additional operations based on predefined conditions.

To create a plugin in Microsoft Dynamics CRM(CE), follow these steps:

  1. First set up your development environment: Ensure you have Visual Studio and the Dynamics 365 SDK installed on your machine.
  2. Create a new project : In Visual Studio, Create a new class library project.
  3. Add references to the required Dynamics 365 assemblies. Microsoft.Xrm.Sdk
  4. To do that Right click on References node in Solution explorer and select Manage NuGet Packages.
  5. Go to Browse tab, search for Microsoft.Xrm.Sdk and select the latest version and click Install. It will install the assembly which is required for plugin creation.
  6. Delete the class which project created by default.

Create a row in entity using plugin

When an account record is created, we will create a contact record with the same account number using plugin.

To create a contact record in entity using CRM plugin follow these steps.

  1. Create a new class named as CreateContactRecord.
  2. Replace the class code with the code below.
  3. class CreateContactRecord : IPlugin     
    {
    public void Execute(IServiceProvider serviceProvider)
    {
    //Initializing Service Context.
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

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

    try
    {
    //Defining Entity Object.
    Entity eTarget = null;

    if (context.MessageName == "Create")
    {
    eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ? context.InputParameters["Target"] as Entity : null;

    string AccountName = eTarget.GetAttributeValue("accountname");
    int AccountNumber = eTarget.GetAttributeValue("accountnumber");
    EntityReference ContactLookup = eTarget.GetAttributeValue("contact");
    DateTime AccountDate = eTarget.GetAttributeValue("accountdate");
    Money AccountRevenue = eTarget.GetAttributeValue("accountrevenue");
    int AccountOptionset = eTarget.GetAttributeValue("accountrevenue").Value;

    //create contact record
    Entity eNewContact = new Entity("contact");
    eNewContact["ContactNumber"] = AccountNumber;
    service.Create(eNewContact);
    }
    }
    catch (Exception ex)
    {
    throw new InvalidPluginExecutionException(ex.Message);
    }
    }
    }

Update a row in entity using plugin

When an account record is created and if there is any contact record already exists with contact number same as the account number, then we will update that contact name of contact record to “Test 1234” using plugin.

To update a contact record in entity using CRM plugin follow these steps.

  1. Create a new class named as UpdateContactRecord.
  2. Replace the class code with the code below.
  3. public class UpdateContactRecord : IPlugin
        
    {

    //Main Execute Method.
    public void Execute(IServiceProvider serviceProvider)
    {
    //Initializing Service Context.
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

    IOrganizationService service = factory.CreateOrganizationService(context.UserId);
    try
    {
    //Defining Entity Object.
    Entity eTarget = null;

    if (context.MessageName == "Create")
    {
    //Stage 1 - Retrieving Target Entity.
    eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ? context.InputParameters["Target"] as Entity : null;

    //Stage 2 - Read Record Scenario.
    string AccountName = eTarget.GetAttributeValue("accountname");
    int AccountNumber = eTarget.GetAttributeValue("accountnumber");
    EntityReference ContactLookup = eTarget.GetAttributeValue("contact");
    DateTime AccountDate = eTarget.GetAttributeValue("accountdate");
    Money AccountRevenue = eTarget.GetAttributeValue("accountrevenue");
    int AccountOptionset = eTarget.GetAttributeValue("accountrevenue").Value;

    //Stage 3 - Creating Query Expression.
    QueryExpression qeContactUpdate = new QueryExpression("contact");
    qeContactUpdate.ColumnSet.AddColumns("contactnumber", "contactname", "contactid");
    FilterExpression filterUpdate = new FilterExpression(LogicalOperator.And);
    filterUpdate.AddCondition("contactnumber", ConditionOperator.Equal, AccountNumber);
    qeContactUpdate.Criteria.AddFilter(filterUpdate);

    EntityCollection entityCollectionUpdate = service.RetrieveMultiple(qeContactUpdate);

    if (entityCollectionUpdate.Entities.Count == 0)
    {
    // No Contact Found.
    }
    else
    {
    //Stage 4 - Fetched Entity Object Record.

    foreach (var entity in entityCollectionUpdate.Entities)
    {
    Entity eContactUpdate = new Entity("contact");

    //Stage 5 - Mapping Entity Id
    eContactUpdate.Id = entity.Id;
    eContactUpdate["contactname"] = "Test 1234";

    //Stage 6 - Generating Update Request.
    service.Update(eContactUpdate);
    }
    }
    }
    }
    catch (Exception ex)
    {
    throw new InvalidPluginExecutionException(ex.Message);
    }
    }
    }

Thank you for reading this article hope you find it useful.

Omar Iqbal

Technical Consultant

References:

Total
0
Shares
7 comments
  1. I haven’t checked in here for a while because I thought it was getting boring, but the last few posts are great quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂

  2. each time i used to read smaller articles or reviews thatas well clear their motive, and that is alsohappening with this paragraph which I am reading here.

Comments are closed.

Previous Article

Assign record owner to specific Team using Power Automate flow in Microsoft Dynamics CE (CRM)