Oct 30, 2012

Sample Plug-in code: Create and Update

This is a sample code which can be used for create and update of a record. Here I have used a custom entity called new_office.

using System;
using System.Collections.Generic;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel;

namespace TestCompany.CRM.Plugin
{
public class officePreCreate : IPlugin
{
  public void Execute(IServiceProvider serviceProvider)
  {
    IPluginExecutionContext context;
    IOrganizationServiceFactory factory;
    IOrganizationService service;
    Entity TargetEnt;

    try
    {
     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
     if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
     {
       TargetEnt = (Entity)context.InputParameters["Target"];
       if (TargetEnt.LogicalName != "new_office")
           return;

       factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
       service = factory.CreateOrganizationService(context.UserId);

       // Do the logic as required

      }
     }
     catch (FaultException<OrganizationServiceFault> e)
     {
       throw e;
     }
     finally
     {
       service = null;
       factory = null;
       context = null;
       TargetEnt = null;
     }
  }
}
}

Create message

In both Pre and Post stages we have all the attributes of the record to be used in our logic. We got to select either pre or post stages depending on business logic.

In pre stage (both Create and Update) we have an extra facility of changing attributes before Creating / Updating the record. For example, if I need to add some postfix to a string fields, I can do as below;

if (TargetEnt.Contains("new_name"))
{
    TargetEnt["new_name"] = TargetEnt.Attributes["new_name"] + " Pvt Ltd";
}

Consider the settings of the plug-in registration;

Pre Create;



Post Create;


Only difference would be the stage of execution.

Update message

When updating, in both Pre and Post stages, we get only modified attributes and primarkey. In Pre stage it is possible to amend those available values before updating. For example we can do the adding of postfix explained above if that field is available (i.e. modified) in target entity.

Consider the settings of the plug-in registration;

Pre Update;


Post Update;


Now message is Update instead of Create and stages are varied as Pre and Post.

Related posts;
Plug-in concerns: synchronous or asynchronous, transactional or not …
Sample Plug-in: Delete
Sample Plug-in: State change
Sample Plug-in: Compare Pre and Post images on Update
Retrieve attributes of entity object

1 comment:

  1. By the way, if you happen to update same entity through a update plug-in add below code to avoide infinite loop;

    if (context.Depth > 1)
    {
    return;
    }

    ReplyDelete