Tuesday 10 July 2012

calculate a field based on child entity field values on delete



This on delete message.

here we need to take the preimage.

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 Kryptos.Est.Revenue.Calculation
{
    public class Estrevenueondelete:IPlugin
    {

        public Money totalestimatedamt;

        //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_opportunityitproduct") && context.PreEntityImages["new_opportunityitproduct"] is Entity)
                {

                    Entity slaitem = (Entity)context.PreEntityImages["new_opportunityitproduct"];
                    //int time = (int)slaitem.Attributes["slk_time"];
                    Money priceamt = (Money)slaitem.Attributes["new_price"];

                    EntityReference slaid = (EntityReference)slaitem.Attributes["new_opportunityid"];

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

                    Money estimatedamt = (Money)contact1["estimatedvalue"];

                    totalestimatedamt = new Money() { Value = (estimatedamt.Value - priceamt.Value) };
                    //int timeofitems = Convert.ToInt32(contact1["slk_maxtime"]);
                    //totaltime = timeofitems - time;
                    contact1["estimatedvalue"] = totalestimatedamt;//totaltime;
                    service.Update(contact1);

                }
            }
            else return;
        }
    }
}

No comments:

Post a Comment