Compartir a través de


Pasar datos entre complementos

 

Publicado: enero de 2017

Se aplica a: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

El modelo de canalización de mensajes para Microsoft Dynamics 365 define una colección de parámetros de valores de datos personalizados en el contexto de ejecución que se pasa a través de la canalización y se comparte entre los complementos registrados, incluso de diferentes desarrolladores de terceros. Esta colección de datos pueden usarla diferentes complementos para comunicar información entre complementos y habilitar el procesamiento en cadena donde los datos procesados por un complemento los puede procesar el siguiente en la secuencia, etc. Esta característica es especialmente útil en escenarios del motor de cálculo de precios donde varios complementos de precios se pasan datos entre ellos para calcular el precio total de un pedido de ventas o una factura. Otro uso potencial de esta característica es comunicar información entre un complemento registrado anterior al evento y un complemento registrado posterior al evento.

El nombre del parámetro que se usa para pasar información entre los complementos es SharedVariables. Esta es una colección de pares clave\valor. En tiempo de ejecución, los complementos pueden agregar, leer o modificar propiedades de la colección SharedVariables. Esto proporciona un método de comunicación de la información entre complementos.

Este ejemplo muestra cómo usar SharedVariables para transmitir datos de un complemento registrado anterior al evento a un complemento registrado posterior al evento.


using System;

// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;

namespace Microsoft.Crm.Sdk.Samples
{
    /// <summary>
    /// A plug-in that sends data to another plug-in through the SharedVariables
    /// property of IPluginExecutionContext.
    /// </summary>
    /// <remarks>Register the PreEventPlugin for a pre-operation stage and the 
    /// PostEventPlugin plug-in on a post-operation stage.
    /// </remarks>
    public class PreEventPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            // Create or retrieve some data that will be needed by the post event
            // plug-in. You could run a query, create an entity, or perform a calculation.
            //In this sample, the data to be passed to the post plug-in is
            // represented by a GUID.
            Guid contact = new Guid("{74882D5C-381A-4863-A5B9-B8604615C2D0}");

            // Pass the data to the post event plug-in in an execution context shared
            // variable named PrimaryContact.
            context.SharedVariables.Add("PrimaryContact", (Object)contact.ToString());
        }
    }

    public class PostEventPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            // Obtain the contact from the execution context shared variables.
            if (context.SharedVariables.Contains("PrimaryContact"))
            {
                Guid contact =
                    new Guid((string)context.SharedVariables["PrimaryContact"]);

                // Do something with the contact.
            }
        }
    }
}


' Microsoft Dynamics CRM namespace(s)
Imports Microsoft.Xrm.Sdk

Namespace Microsoft.Crm.Sdk.Samples

    ''' <summary>
    ''' A plug-in that sends data to another plug-in through the SharedVariables
    ''' property of IPluginExecutionContext.
    ''' </summary>
    ''' <remarks>Register the PreEventPlugin for a pre-operation stage and the 
    ''' PostEventPlugin plug-in on a post-operation stage.
    ''' </remarks>
    Public Class PreEventPlugin
        Implements IPlugin

        Public Sub Execute(ByVal serviceProvider As IServiceProvider) _
            Implements IPlugin.Execute

            ' Obtain the execution context from the service provider.
            Dim context As Microsoft.Xrm.Sdk.IPluginExecutionContext =
                CType(serviceProvider.GetService(
                        GetType(Microsoft.Xrm.Sdk.IPluginExecutionContext)), 
                    Microsoft.Xrm.Sdk.IPluginExecutionContext)

            ' Create or retrieve some data that will be needed by the post event
            ' plug-in. You could run a query, create an entity, or perform a calculation.
            'In this sample, the data to be passed to the post plug-in is
            ' represented by a GUID.
            Dim contact As New Guid("{74882D5C-381A-4863-A5B9-B8604615C2D0}")

            ' Pass the data to the post event plug-in in an execution context shared
            ' variable named PrimaryContact.
            context.SharedVariables.Add("PrimaryContact", CType(contact.ToString(),
                                        Object))

        End Sub
    End Class

    Public Class PostEventPlugin
        Implements IPlugin

        Public Sub Execute(ByVal serviceProvider As IServiceProvider) _
            Implements IPlugin.Execute

            ' Obtain the execution context from the service provider.
            Dim context As Microsoft.Xrm.Sdk.IPluginExecutionContext =
                CType(serviceProvider.GetService(
                        GetType(Microsoft.Xrm.Sdk.IPluginExecutionContext)), 
                    Microsoft.Xrm.Sdk.IPluginExecutionContext)

            ' Obtain the contact from the execution context shared variables.
            If context.SharedVariables.Contains("PrimaryContact") Then

                Dim contact As New Guid(CStr(context.SharedVariables("PrimaryContact")))

                ' Do something with the contact.

            End If

        End Sub
    End Class

End Namespace

Es importante que cualquier tipo de datos agregado a la colección de variables compartidas sea serializable; en caso contrario, el servidor no sabrá como serializar los datos y la ejecución de complementos no se realizará correctamente.

Para un complemento registrado en la fase 20 ó 40, para tener acceso a las variables compartidas de un complemento registrado en la fase 10 que se ejecuta al crear, actualizar, eliminar o por una clase RetrieveExchangeRateRequest, debe tener acceso a la colección ParentContext.SharedVariables. Para el resto de los casos, IPluginExecutionContext.SharedVariables contiene la colección.

Ver también

IPluginExecutionContext
Desarrollo de complementos
Suplantación en complementos
Canalización de ejecución del evento

Microsoft Dynamics 365

© 2017 Microsoft. Todos los derechos reservados. Copyright