AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Разработка
CRM
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 25.03.2014, 12:17   #1  
Ion is offline
Ion
Участник
 
332 / 16 (1) ++
Регистрация: 19.12.2012
Update parent record on Create child record
Добрый день!


Есть две сущности - Агент (родитель) и Операция (дочерняя). При создании дочерней записи агрегировать суммы дочерних записей, и результат записывать в родительскую.

Инфо. о плагине:

Цитата:
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&amp; 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[]&amp; 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&amp; 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_idService);

                
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_idIOrganizationService service)
        {
            
decimal TotalValue 0;
            
QueryExpression Transaction = new QueryExpression EntityName "erpc__financial_transaction"ColumnSet = new ColumnSet("erpc_amount") };
            
Transaction.Criteria.AddCondition("erpc_agent"ConditionOperator.EqualgetAgent_id);
            
Transaction.Criteria.AddCondition("erpc_transaction_type"ConditionOperator.Equal127770001);
            
Transaction.Criteria.AddCondition("erpc_documenttype"ConditionOperator.Equal127770000);
            
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;
          }


Последний раз редактировалось Ion; 25.03.2014 в 12:20.
Старый 25.03.2014, 14:51   #2  
Konstantin Katsovich is offline
Konstantin Katsovich
Участник
Аватар для Konstantin Katsovich
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
 
243 / 57 (2) ++++
Регистрация: 22.10.2008
Адрес: Israel
Это Guid не "agents_ins", а "erpc__financial_transaction"
Вы подставляете не тот Guid для обновления сущности.
Вытащите из "Target" нужное поле, которое и используйте для обновления сущности "agents_ins"
__________________
Читайте SDK!!!
За это сообщение автора поблагодарили: Ion (1).
Старый 27.03.2014, 13:23   #3  
g.Naukovych is offline
g.Naukovych
Участник
MCBMSS
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
 
405 / 130 (5) +++++
Регистрация: 23.03.2011
А на что Вы этот плагин регистрируете?

Мне казалось, что если он синхронный, то он вообще работать не должен.
у Вас запись, которую Вы создаете еще в транзакции находится.

или я чего-то не понимаю?
__________________
Мой блог https://procrm.tv
Старый 31.03.2014, 12:18   #4  
Ion is offline
Ion
Участник
 
332 / 16 (1) ++
Регистрация: 19.12.2012
Цитата:
Сообщение от g.Naukovych Посмотреть сообщение
А на что Вы этот плагин регистрируете?

Мне казалось, что если он синхронный, то он вообще работать не должен.
у Вас запись, которую Вы создаете еще в транзакции находится.

или я чего-то не понимаю?
Все работает, глаза замылены были, вот и допустил простую ошибку

А почему не должен работать, если он синхронный? Он же в post-event in the sandbox.

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.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2011 Update Rollup 15 Blog bot Dynamics CRM: Blogs 1 10.02.2016 10:26
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2011 Update Rollup 16 Blog bot Dynamics CRM: Blogs 0 23.01.2014 03:15
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2011 Update Rollup 14 Blog bot Dynamics CRM: Blogs 0 12.07.2013 07:13
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2011 Update Rollup 13 Blog bot Dynamics CRM: Blogs 0 27.03.2013 22:12
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2011 Update Rollup 10 Blog bot Dynamics CRM: Blogs 0 17.08.2012 03:27

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 16:59.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.