Auto-copy field on save/recalculate.
using System;
using System.ServiceModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm;
using Microsoft.Xrm.Sdk.Query;
#endregion
namespace AutoCopyOpportunityQuote
{
public class AutoCopytoQuote:IPlugin
{
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);
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
Guid OpportunityID = Guid.Empty;
try
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "opportunity")
return;
if (entity.Attributes.Contains("opportunityid"))
{
OpportunityID = ((Guid)entity.Attributes["opportunityid"]);
}
string FetchOpportunity = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='opportunity'>
<attribute name='ti_totalamtlessfreight' />
<attribute name='ti_quoteamount' />
<filter type='and'>
<condition attribute='opportunityid' operator='eq' value='{0}' />
</filter>
</entity>
</fetch>";
decimal TotalAmtlessfreight = 0; // Total Amt Less freight
//decimal Quoteamt = 0; // Quote Amt
FetchOpportunity = string.Format(FetchOpportunity, OpportunityID);
EntityCollection result = (EntityCollection)service.RetrieveMultiple(new FetchExpression(FetchOpportunity));
if (result.Entities.Count > 0)
{
foreach (Entity c in result.Entities)
{
if (c.Attributes.Contains("ti_totalamtlessfreight"))
{
TotalAmtlessfreight = ((Money)c.Attributes["ti_totalamtlessfreight"]).Value;
}
}
}
Boolean IsUpdated = false;
Entity opportunityobj = new Entity("opportunity");
opportunityobj.Attributes.Add("opportunityid", OpportunityID);
opportunityobj.Attributes.Add("ti_quoteamount", new Money(TotalAmtlessfreight));
if (!IsUpdated)
{
IsUpdated = true;
}
if (IsUpdated)
{
try
{
service.Update(opportunityobj);
}
catch (Exception ex)
{
tracingService.Trace("Exception generated :" + ex.Message);
}
}
}
}
catch (Exception ex)
{
tracingService.Trace("Exception generated :" + ex.Message);
}
}
}
}
No comments:
Post a Comment