Установка значений для полей - PullRequest
2 голосов
/ 13 декабря 2011

Я создал плагин, подсчитывающий количество записей сущности, связанной с другой, если существует более одной записи, я получаю последнюю запись. Если эта запись неактивна и значение определенного поля> 0, тогда я добавляю значение этого поля к вновь созданному ... Но не могу заставить его работать ...

Любая помощь будет отличной!

Edit: Плагин зарегистрирован в "new_lignecontrat", который содержит атрибуты "new_unitesutilisees" и "new_unitesrestantes".

Редактировать 2:

Хорошо, решил это! Все, что мне было нужно, это просто получить EntityReference для поля поиска и немного переставить мой код ...

Спасибо за вашу помощь!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Web;
using System.Collections;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Messages;

namespace ClassLibrary1
{
    public class StatusContrat : IPlugin
    {         
        public void Execute(IServiceProvider serviceProvider)
        {
            // Instanciation des services
            IPluginExecutionContext context     = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service        = factory.CreateOrganizationService(null);

            Entity statusEntité = (Entity)context.InputParameters["Target"];

                    // Récupération des lignes de contrat liées au contrat courant
                FetchExpression fetch   = new FetchExpression("<fetch distinct='false' mapping='logical'>" +
               "<entity name='new_contrats'>" +
               "<link-entity name='new_lignecontrat' alias='nombreligne' from='new_contratsid' to='new_contratsid'>" +
               "</link-entity>" +
               "</entity>" +
               "</fetch>");

                EntityCollection lines = service.RetrieveMultiple(fetch);

                    // Vérification qu'il y a au moins une ligne de contrat associée
                    if (lines.Entities.Count > 0)
                    {   
                        if (lines.Entities.Last().GetAttributeValue<OptionSetValue>("statecode").Value == 1)
                        {
                           if (lines.Entities.Last().GetAttributeValue<float>("new_unitesrestantes")<0)
                           {
                              var unitesRestantes = (statusEntité.GetAttributeValue<float>("new_unitesrestantes")) + (lines.Entities.Last().GetAttributeValue<float>("new_unitesrestantes"));
                              var unitesUtilisee =  (statusEntité.GetAttributeValue<float>("new_unitesutilisees")) - (lines.Entities.Last().GetAttributeValue<float>("new_unitesutilisees"));

                                statusEntité ["new_unitesutilisees"] = unitesUtilisee;
                                statusEntité ["new_unitesrestantes"] = unitesRestantes;

                                service.Update(statusEntité);
                           }
                        }
                    }
                    else
                    {

                        statusEntité["new_unitesutilisees"] = "0";
                        statusEntité["new_unitesrestantes"] = statusEntité["new_unitestotales"];

                        service.Update(statusEntité);
}                        

         }
      }
   }

Ответы [ 2 ]

1 голос
/ 14 декабря 2011

Пара мыслей:

Q: Вы уверены, что ваш плагин вообще выполняется?
Чтобы проверить это, вы можете изменить код, чтобы генерировать исключение InvalidPluginExecutionException, чтобы вы знали, что оно хотя бы выполняется.

В: Правильно ли зарегистрирован ваш плагин?
Проверьте, зарегистрирован ли ваш плагин в сообщении «Создание» и на любом из этапов предварительной проверки или подготовки к работе.

Q: Ваш плагин выполняется по путиты ожидал?
Я бы посоветовал вам выполнить некоторую отладку на сервере (при условии, что вы выполняете локальную разработку)

Редактировать:

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

        Entity target = (Entity)context.InputParameters["Target"];

        // Récupération des lignes de contrat liées au contrat courant
        FetchExpression fetch = new FetchExpression(@"
            <fetch distinct='false' mapping='logical'>
              <entity name='new_contrats'>
                <link-entity name='new_lignecontrat' alias='nombreligne' from='new_contratsid' to='new_contratsid'>
                </link-entity>
              </entity>
            </fetch>");

        // Note: Do you need some attribute fields so that the entities are actually returning some relevant data
        // Note: Do you want to retrieve ALL the 'new_contrats' or should you be adding a condition in here to the primary entity?
        //  <filter type='and'>
        //    <condition attribute='MyIdFieldHere' operator='eq' value='" + context.PrimaryEntityId + "' /> 
        //  </filter>

        EntityCollection lines = service.RetrieveMultiple(fetch);

        // Vérification qu'il y a au moins une ligne de contrat associée
        if (lines.Entities.Any())
        {
            // store last entity in variable so that the collection is enumerabled 4 seperate times
            var last = lines.Entities.Last();
            if (last.GetAttributeValue<OptionSetValue>("statecode").Value == 1)
            {
                if (last.GetAttributeValue<float>("new_unitesrestantes") < 0)
                {
                    var unitesRestantes = (target.GetAttributeValue<float>("new_unitesrestantes")) + (last.GetAttributeValue<float>("new_unitesrestantes"));
                    var unitesUtilisee = (target.GetAttributeValue<float>("new_unitesutilisees")) - (last.GetAttributeValue<float>("new_unitesutilisees"));

                    target["new_unitesutilisees"] = unitesUtilisee;
                    target["new_unitesrestantes"] = unitesRestantes;
                }
            }
        }
        else
        {
            // if 'new_unitesutilisees' is a float, then the value must also be a float
            target["new_unitesutilisees"] = 0f; 
            target["new_unitesrestantes"] = target["new_unitestotales"];
        }     

Редактировать2:

Кроме того, я предполагаю, что лучше выполнить запрос извлечения вместо извлечения всех сущностей, чем только с использованием последней.Не могли бы вы сузить найденный список, настроив запрос, чтобы установить обратный порядок и получить только первый элемент?В зависимости от количества объектов в системе эта небольшая оптимизация значительно сократит время выполнения этого плагина.

0 голосов
/ 14 декабря 2011

Если это код, который вы используете, это может быть потому, что ваш FetchXML не получает никаких атрибутов, в частности атрибутов new_unitesrestantes и new_unitesutilisees, поэтому любые объекты, полученные по запросу RetrieveMultiple, не будут не имеют значений для этих атрибутов.

<fetch distinct='false' mapping='logical'>
  <entity name='new_contrats'>
    <!-- no attributes listed here -->
    <link-entity name='new_lignecontrat' alias='nombreligne' from='new_contratsid' to='new_contratsid'>
      <!-- no attributes listed here either -->
    </link-entity>
  </entity>
</fetch>
...