25 Jan 2016

Sample PlugIn to perform CRUD operation- Late Bound


Sample Program to illustrate CRUD operations using Late bond.

Entities:
Department- Parent entity
Employee- Child entity

Task: 
Update Employee count filed in Department entity when a create, update  and delete Employee entity.

Note: Here I used fetchXML to retrieve multiple records(used resource file)

FetchXML query:

 <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false" aggregate="true">  
  <entity name="cit_employee">  
   <attribute name="cit_employeeid" aggregate="count" alias="empCount" />  
   <filter type="and">  
    <condition attribute="cit_department" operator="eq" value="{0}" />  
   </filter>  
  </entity>  
 </fetch>  

coding is

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.Runtime.Serialization;  
 using System.Globalization;  
 using System.ServiceModel;  
 using Microsoft.Xrm.Sdk;  
 using Microsoft.Xrm.Sdk.Query;  
 namespace EmployeeCountDepartmentWise  
 {  
   public class EmployeeCount : IPlugin  
   {  
     public void Execute(IServiceProvider _serviceProvider)  
     {  
       IPluginExecutionContext _context = (IPluginExecutionContext)_serviceProvider.GetService(typeof(IPluginExecutionContext));  
       IOrganizationServiceFactory _factory = (IOrganizationServiceFactory)_serviceProvider.GetService(typeof(IOrganizationServiceFactory));  
       IOrganizationService _service = _factory.CreateOrganizationService(_context.UserId);  
       if(_context.InputParameters.Contains("Target"))  
       {  
         if (_context.InputParameters["Target"] is Entity)  
         {  
           Entity _empEntity = (Entity)_context.InputParameters["Target"];  
           if (_empEntity.LogicalName.ToLower() == "cit_employee")  
           {  
             switch (_context.MessageName)  
             {    
               case "Create":  
                 try  
                 {  
                   Guid _deptId = ((EntityReference)_empEntity.Attributes["cit_department"]).Id;  
                   PostEventOperation(_service, _deptId);  
                 }  
                 catch (FaultException<OrganizationServiceFault> ex)  
                 {  
                   throw new InvalidPluginExecutionException("An error occurred in CFR13.DemoPlugin plug-in.", ex);  
                 }  
                 break;  
               case "Update":  
                 try  
                 {  
                   Guid _deptPreImageId = Guid.Empty; Guid _deptPostImageId = Guid.Empty;  
                   if (_context.PreEntityImages.Contains("PreImage"))  
                   {  
                     Entity _preEntityImage = (Entity)_context.PreEntityImages["PreImage"];  
                     if (_preEntityImage.Contains("cit_department"))  
                     {  
                       _deptPreImageId = ((EntityReference)_preEntityImage.Attributes["cit_department"]).Id;  
                     }  
                     if (_empEntity.Attributes.Contains("cit_department"))  
                     {  
                       _deptPostImageId = ((EntityReference)_empEntity.Attributes["cit_department"]).Id;  
                     }  
                     Guid[] ar = new Guid[] { _deptPreImageId, _deptPostImageId };  
                     int i = 0;  
                     while (i < 2)  
                     {  
                       PostEventOperation(_service, ar[i]);  
                       i++;  
                     }  
                   }  
                 }  
                 catch (FaultException<OrganizationServiceFault> ex)  
                 {  
                   throw new InvalidPluginExecutionException("An error occurred in CFR13.DemoPlugin plug-in.", ex);  
                 }  
                 break;  
             }  
           }  
         }  
         else if (_context.InputParameters["Target"] is EntityReference)  
         {  
           EntityReference _empEntity = (EntityReference)_context.InputParameters["Target"];  
           if (_empEntity.LogicalName.ToLower() == "cit_employee")  
           {  
             if (_context.MessageName == "Delete")  
             {  
               try  
               {  
                 if (_context.PreEntityImages.Contains("PreImage"))  
                 {  
                   Entity _preImage = (Entity)_context.PreEntityImages["PreImage"];  
                   if (_preImage.Contains("cit_department"))  
                   {  
                     Guid _deptId = ((EntityReference)_preImage.Attributes["cit_department"]).Id;  
                     PostEventOperation(_service, _deptId);  
                   }  
                 }  
               }  
               catch (FaultException<OrganizationServiceFault> ex)  
               {  
                 throw new InvalidPluginExecutionException("An error occurred in CFR13.DemoPlugin plug-in.", ex);  
               }  
             }  
           }  
         }  
       }  
     }  
     public void PostEventOperation(IOrganizationService _service, Guid depId)  
     {  
       Entity _deptEntity = new Entity("cit_department");  
       _deptEntity["cit_departmentid"] = depId;  
       string _getEmployeeCount = string.Format(CultureInfo.CurrentCulture, FetchXML.getEmployeeCount, depId);  
       EntityCollection _entityCollection = (EntityCollection)_service.RetrieveMultiple(new FetchExpression(_getEmployeeCount));  
       if (_entityCollection.Entities.Count == 1)  
       {  
         int val = (int)((AliasedValue)_entityCollection.Entities[0]["empCount"]).Value;  
         _deptEntity["cit_employeecount"] = Convert.ToString(val);  
         _service.Update(_deptEntity);  
       }  
     }  
   }  
 }  

Expecting Suggestions......

No comments:

Post a Comment