Добрый день!
Есть две сущности - Агент (родитель) и Операция (дочерняя). При создании дочерней записи агрегировать суммы дочерних записей, и результат записывать в родительскую.
Инфо. о плагине:
Цитата:
Isolation mode: Sandbox
Message: Create
Pipeline Stage: Post-Operation
Execution mode: Synchronous
Execution Order: 1
В SDK написано для
похожего примера:
Цитата:
Register this plug-in for an account entity, on the Create message, and in asynchronous mode. Alternately, you can register the plug-in on a post-event in the sandbox.
Написал плагин на Update event - без проблем, на Create event валиться, говорит, что нет такого Агента:
Цитата:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Agents_ins With Id = a763c7e1-f3b3-e311-ae18-00155d02050e Does Not Exist, Stack trace :
Server stack trace:
в System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
в System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
в System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
в System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
в Microsoft.Crm.Sandbox.SandboxOrganizationService.Execute(String operation, Byte[] serializedRequest)
в System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
в System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [1]:
в System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
в System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
в Microsoft.Crm.Sandbox.ISandboxOrganizationService.Execute(String operation, Byte[] serializedRequest)
в Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.ExecuteInternal(OrganizationRequest request)
в PackageAgentCreate.CountTransactionAmountCreateEvent.TransactionAmountCreateEvent.Execute(IServiceProvider ServiceProvider)Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220891</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>OperationStatus</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">0</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>Agents_ins With Id = a763c7e1-f3b3-e311-ae18-00155d02050e Does Not Exist, Stack trace :
Server stack trace:
в System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
в System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
в System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
в System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
в Microsoft.Crm.Sandbox.SandboxOrganizationService.Execute(String operation, Byte[] serializedRequest)
в System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
в System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [1]:
в System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
в System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
в Microsoft.Crm.Sandbox.ISandboxOrganizationService.Execute(String operation, Byte[] serializedRequest)
в Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.ExecuteInternal(OrganizationRequest request)
в PackageAgentCreate.CountTransactionAmountCreateEvent.TransactionAmountCreateEvent.Execute(IServiceProvider ServiceProvider)</Message>
<Timestamp>2014-03-25T08:03:03.3706706Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText>
[PackageAgentCreate.CountTransactionAmountCreateEvent: PackageAgentCreate.CountTransactionAmountCreateEvent.TransactionAmountCreateEvent]
[4553f29d-3fb3-e311-83fc-00155d02050e: PostОперацияCreate]
</TraceText>
</OrganizationServiceFault>
Вот сам код:
PHP код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Globalization;
namespace PackageAgentCreate.CountTransactionAmountCreateEvent
{
public class TransactionAmountCreateEvent : 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));
if (Context.InputParameters.Contains("Target") && Context.InputParameters["Target"] is Entity)
//if (Context.PostEntityImages.Contains("PostImage") && Context.PostEntityImages["PostImage"] is Entity)
{
try
{
//Entity Agent = (Entity)Context.PostEntityImages["PostImage"];
Entity Agent = (Entity)Context.InputParameters["Target"];
if (Agent.LogicalName != "erpc__financial_transaction") { return; }
Guid getAgent_id = (Guid)((Entity)Context.InputParameters["Target"]).Id;
decimal AgentAccrued_n = FetchAccrued_n(getAgent_id, Service);
Entity AgentsObj = new Entity("agents_ins");
AgentsObj.Id = getAgent_id;
AgentsObj["agents_accrued_n"] = new Money(AgentAccrued_n);
Service.Update(AgentsObj);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message + ", Stack trace : " + ex.StackTrace);
}
}
}
private static decimal FetchAccrued_n(Guid getAgent_id, IOrganizationService service)
{
decimal TotalValue = 0;
QueryExpression Transaction = new QueryExpression { EntityName = "erpc__financial_transaction", ColumnSet = new ColumnSet("erpc_amount") };
Transaction.Criteria.AddCondition("erpc_agent", ConditionOperator.Equal, getAgent_id);
Transaction.Criteria.AddCondition("erpc_transaction_type", ConditionOperator.Equal, 127770001);
Transaction.Criteria.AddCondition("erpc_documenttype", ConditionOperator.Equal, 127770000);
EntityCollection RetrieveTransaction = service.RetrieveMultiple(Transaction);
if (RetrieveTransaction.Entities.Count > 0)
{
foreach (var c in RetrieveTransaction.Entities)
{
decimal aggregate2 = 0;
if (c.Attributes.Contains("erpc_amount"))
{
aggregate2 += ((Money)c.Attributes["erpc_amount"]).Value;
}
else
{
aggregate2 += 0;
}
TotalValue += aggregate2;
}
}
return TotalValue;
}
}