RSS

Category Archives: SDK Messages

Use of Shared Variables in Plugin

Introduction

Shared Variables will be useful for sharing the data during complex Plug-in development by sharing the data between Plugins registered on both the pre and post events.

Any value stored in the Plug-in context of Pre-event will be available in the Post-event of the Plug-in. This way, we can avoid storing the values in a custom attribute. Certain data validation which needs to be done at post-event can be achieved by passing the value from Pre-event of the Plug-in. This also helps for performing business logic like updating related records asynchronously.

Using the Code

The below code snippet illustrates the usage of Shared Variable. This sample explains the data validation done at Post-event operation based on the value received from the Pre-event operation where a flag is updated with a value at the Pre-event level and sent to the Post-event through shared variable.

//Pre-Create (Entity Name) Plug-in
if (pluginContext.MessageName == "Create")
{
    if (pluginContext.InputParameters.ContainsKey("Target")
                             && 
        pluginContext.InputParameters["Target"] is Entity)
    {
        Entity targetEntity = context.InputParameters["Target"] as Entity;
        if (targetEntity != null)
        {
            bool setFlag = false;

            //Check data validation for attributes
            string country = targetEntity.Attributes["address1_country"];
            OptionSetValue industryCode = (OptionSetValue)target.Attributes["industrycode"];

            // Country is US and Industry Type is Accounting are Preferred
            if (country.ToLower() == "us" && industryCode.Value == 1)
            {
                setFlag = true;
            }
            
            pluginContext.SharedVariables.Add("flag", setFlag);
        }
    }
}

//Post-Create (Entity Name) Plug-in
if (pluginContext.MessageName == "Create")
{
    if (pluginContext.InputParameters.ContainsKey("Target")
                           && 
        pluginContext.InputParameters["Target"] is Entity)
    {
        Entity targetEntity = pluginContext.InputParameters["Target"] as Entity;
        if (targetEntity != null)
        {
            if (pluginContext.SharedVariables.ContainsKey("flag"))
            {
                bool recievedFlag = (bool)pluginContext.SharedVariables["flag"];
                if (recievedFlag)
                {
                    // Do whatever you want to do
                }
             }
         }
    }
}

This method lets you to pass data between Plug-ins without having to customize the system by creating hidden fields on entities.

Note: SharedVariables (collection of key/value pairs) property is available in the IPluginExecutionContext of the execution pipeline.

By Gitanjali
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

Advertisements
 

Tags: , , , , , , , , , , , , , , , , , ,

ExecuteMultipleRequest For Bulk Operation

Introduction

In the Microsoft Dynamics CRM 2011 Update Rollup 12, a new message request named ExecuteMultipleRequest is added. Let’s explore more about the usage.

What it does?

It accepts Collection of Requests as input and returns Collection of Responses. The request is executed batch by batch.

For Online CRM, maximum Batch Size is 1000. So, for Online CRM, maximum 1000 requests can be executed at a time.

For On Premise, Batch Size can be increased.

Example

Below are the examples of the ExecuteMultipleRequest.

  • Bulk Lead Creation

    //The method takes IOrganization service and total number of records to be created as input
     private void CreateLeadMultiple(IOrganizationService service, int batchSize)
     {
         //To execute the request we have to add the Microsoft.Xrm.Sdk of the latest SDK as reference
         ExecuteMultipleRequest req = new ExecuteMultipleRequest();
         req.Requests = new OrganizationRequestCollection();
         req.Settings = new ExecuteMultipleSettings();
         req.Settings.ContinueOnError = true;
         req.Settings.ReturnResponses = true;
    
         try
         {
             for (int i = 0; i < batchSize; i++)
             {
                 Entity lead = new Entity("lead");
                 lead["subject"] = "Test Lead";
                 lead["firstname"] = "Requested Lead";
                 lead["lastname"] = "Name " + i;
                 var createRequest = new CreateRequest();
    
                 createRequest.Target = lead;
                 req.Requests.Add(createRequest);
              }
    
              var res = service.Execute(req) as ExecuteMultipleResponse;  //Execute the collection of requests
          }
    
          //If the BatchSize exceeds 1000 fault will be thrown.In the catch block divide the records into batchable records and create
          catch (FaultException<OrganizationServiceFault> fault)
          {
              if (fault.Detail.ErrorDetails.Contains("MaxBatchSize"))
              {
                  var allowedBatchSize = Convert.ToInt32(fault.Detail.ErrorDetails["MaxBatchSize"]);
                  int remainingCreates = batchSize;
    
                  while (remainingCreates > 0)
                  {
                      var recordsToCreate = Math.Min(remainingCreates, allowedBatchSize);
                      CreateLeadMultiple(service, recordsToCreate);
                      remainingCreates -= recordsToCreate;
                  }
              }
          }
    }
    
  • Bulk Entity State and Status Change

    Here is another example of changing the State and Status of records by ExecuteMultipleRequest.

    This code will work, if the total Records <=1000, otherwise we have to break the records into batches to execute one by one.

    for (int i = count; i < ent.Entities.Count; i++)
    {
        SetStateRequest changeState = new SetStateRequest();
        changeState.EntityMoniker = new EntityReference();
        changeState.EntityMoniker.Id = ent.Entities[i].Id;
        changeState.EntityMoniker.LogicalName = ent.Entities[i].LogicalName;
        changeState.State = new OptionSetValue(0);
        changeState.Status = new OptionSetValue(1);
        req.Requests.Add(changeState);
    }
    
    // Here req is the object of ExecuteMultipleRequest class.
    var res = service.Execute(req) as ExecuteMultipleResponse;
    

By Ranjan Parhi
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 
1 Comment

Posted by on August 7, 2013 in SDK Messages

 

Tags: , , , , , , , , , , , , , , , ,

 
%d bloggers like this: