Thursday 26 April 2012

updating numbers when delete a record in dynamic crm 2011 by using plugin

create a early bond,
for this require PreImage.

take the preimage and caluculate the value of the field.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xrm;
using System.Diagnostics;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Windows.Browser;
using System.Net;
using System.IO;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;

namespace Super.Plugin.TimeCaluculation
{
   public class TimeCaluculationDelete:IPlugin
    {
        public int totaltime;

        //public Entity entity1;

        public IOrganizationService service;
        public IPluginExecutionContext context;

        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);          

            // Check if the input parameters property bag contains a target
            // of the create operation and that target is of type Entity.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
            {

                if (context.PreEntityImages.Contains("new_item") && context.PreEntityImages["new_item"] is Entity)
                {

                    Entity slaitem = (Entity)context.PreEntityImages["new_item"];
                    int time = (int)slaitem.Attributes["new_time"];
                    EntityReference slaid = (EntityReference)slaitem.Attributes["new_laid"];

                    ColumnSet cols = new ColumnSet(new String[] { "new_maxtime", "new_name" });
                    var contact1 = service.Retrieve("slk_sla", slaid.Id, cols);

                    int timeofitems = Convert.ToInt32(contact1["new_maxtime"]);
                    totaltime = timeofitems - time;
                    contact1["new_maxtime"] = totaltime;
                    service.Update(contact1);

                }
            }
            else return;
        }
    }
}

No comments:

Post a Comment