Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Se aplica a: Dynamics 365 Customer Service y Dynamics 365 Contact Center—únicamente en la versión independiente
En este artículo se describen los detalles de esquema necesarios para asignar información de proveedores de datos externos a las entidades del artículo de conocimientos y cómo puede preparar su propio archivo JSON de asignación de esquema mediante varios campos y atributos.
Campos
En la tabla siguiente se enumeran los campos y los detalles de los campos que debe utilizar en el esquema JSON.
| Nombre del campo | Definición | Obligatorio | Value |
|---|---|---|---|
| Nombre | Nombre de la definición de campo | No | Cadena que indica el nombre del campo. |
| NombreÚnicoDelCampoObjetivo | Identificador único o clave alternativa de la entidad del artículo de conocimiento. Normalmente, este campo es el ID en el lado del proveedor de contenido. | Sí | Cadena que indica el nombre del campo. Puede establecer el valor en "msydn_externalreferenceid" |
| ContentTargetFieldNameContentTargetFieldName | El valor del campo no se debe cambiar. | Sí | Establezca el valor en "contenido". |
| ApiPathLeafName | El valor del campo no se debe cambiar. | Sí | Establezca el valor en "knowledgearticles". |
| Lista<DefinicionesDeCampos> | Es una lista de definiciones de campo. | Sí | Conjunto de definiciones para los campos. Consulte la siguiente tabla para ver la lista de campos admitidos para establecer definiciones de campo. |
Definiciones de campo
En la tabla siguiente se enumeran los atributos obligatorios y opcionales que puede utilizar en el esquema de asignación de metadatos.
| Nombre del campo | Definición | Obligatorio | Value |
|---|---|---|---|
| NombreDelCampoObjetivo | Es el nombre de campo logico del atributo de destino en la entidad del artículo de conocimientos. | Sí | Cualquier cadena que indique el nombre del campo de destino |
| TargetFieldType | Indica el tipo de campo de destino. | Sí | Cadena que indica el tipo del campo. |
| DocFieldSource | Indica cómo se identifica y resuelve el valor del campo de origen en tiempo de ejecución | Sí | Establezca el valor en uno de los siguientes tipos de origen:
|
| DocFieldPattern | Indica la naturaleza del campo de destino que se va a recuperar. | No | Establezca este valor en función del valor de DocFieldSource. Consulte los ejemplos siguientes sobre cómo establecer DocFieldPatterns. |
| Longitud máxima | Es la longitud máxima de la cadena que se puede almacenar en el campo de destino. | N. º Se puede usar cuando el atributo TargetFieldType es de tipo String | Int |
| UseRegexCapture | Almacena el patrón de expresiones regulares que se puede aplicar a la dirección URL. | N. º Se puede usar cuando el atributo TargetFieldType es de tipo String y el atributo DocFieldSource es de tipo Url. | URL o cadena. |
Tipos de fuentes de campo
Los datos de los proveedores de búsqueda externos se pueden establecer en cualquiera de los siguientes tipos de fuentes de campo:
- Regex: se utiliza para indicar un tipo de expresión regular de datos.
- Meta: se utiliza para indicar que el valor del campo de destino se obtiene de una <metaetiqueta> en el artículo de origen
- Constante: se utiliza para establecer un valor estático para el campo de destino.
- URL: Se utiliza para indicar la URL del documento fuente externo.
- Documento: Usar para indicar el contenido HTML del artículo.
Consideraciones para construir su propia plantilla de mapeo de metadatos
Cuando desarrolle su propio esquema de mapeo, debe asegurarse de configurar algunos campos obligatorios y establecer valores predeterminados para algunas definiciones de campo.
La plantilla de mapeo debe incluir:
Los campos UniqueTargetFieldName, ContentTargetFieldName y ApiPathLeafName . Estos campos deben establecerse en sus valores obligatorios de la siguiente manera:
- Establezca UniqueTargetFieldName en el campo predeterminado msdyn_externalreferenceid o en un campo personalizado. Si usas un campo personalizado, asegúrate de agregar el campo como una clave alternativa. Más información: Definir claves alternativas para hacer referencia a registros de Dynamics 365.
- Incluya el campo ContentTargetFieldName y establezca su valor en "content".
- Incluya el campo ApiPathLeafName y establezca su valor en "knowledgearticles".
- Asegúrese de proporcionar asignaciones para UniqueTargetField y ContentTargetFieldContentTargetField en la lista Definiciones de campo.
Su esquema de mapeo se vería así:
{ "Name": "{To be filled by you}", "UniqueTargetFieldName": "msdyn_externalreferenceid", "ContentTargetFieldName": "content", "ApiPathLeafName": "knowledgearticles" "FieldDefinitions": [] }Debe incluir la siguiente lista de FieldDefinitions y rellenar sus atributos, como FieldUse, DocFieldSource, TargetFieldName y TargetFieldType , con valores predeterminados. Asegúrese de incluir los siguientes campos y atributos con sus valores, "as-is", en la plantilla. Sin embargo, puede establecer Docfieldsource y Docfieldpattern para los campos de título y valor de contenido en Regex, Meta, Document, Constant o Url.
{ "FieldUse": "Create", "DocFieldSource": "ArticlePublicNumber", "TargetFieldName": "articlepublicnumber", "TargetFieldType": "String" }, { "DocFieldSource": "Constant", "DocFieldPattern": "true", "TargetFieldName": "msdyn_isingestedarticle", "TargetFieldType": "Boolean" }, { "DocFieldSource": "Url", "TargetFieldName": "msdyn_ingestedarticleurl", "TargetFieldType": "String" }, { "DocFieldSource": "DataProvider", "TargetFieldName": "msdyn_integratedsearchproviderid@odata.bind", "TargetFieldType": "String" }, { "DocFieldSource": "Regex", "DocFieldPattern": "<title>(.*?)</title>", "TargetFieldName": "title", "TargetFieldType": "String" }, { "DocFieldSource": "Url", "TargetFieldName": "msdyn_externalreferenceid", "TargetFieldType": "String", "UseRegexCapture": "^https://.*?/(.*?)/.*/.*?([0-9A-F]{8}[-](?:[0-9A-F]{4}[-]){3}[0-9A-F]{12})$" }, { "DocFieldSource": "Document", "TargetFieldName": "content", "TargetFieldType": "String" }Después de enumerar los campos obligatorios y la información de atributos, puede incluir asignaciones de metadatos adicionales y establecer sus propios valores personalizados para ellos. Por ejemplo, puede incluir un tipo Meta de DocFieldSource y establecer los valores personalizados para el atributo, como se indica a continuación.
{ "DocFieldSource": "Meta", "DocFieldPattern": "description", "TargetFieldName": "description", "TargetFieldType": "String", "MaxLength": 155 }
Ejemplo de plantilla de mapeo de metadatos
Puede utilizar el siguiente ejemplo JSON de asignación de metadatos como plantilla para crear su propia plantilla de asignación personalizada.
{
"Name": "Integrated Search Data Provider Name",
"UniqueTargetFieldName": "msdyn_externalreferenceid",
"ContentTargetFieldName": "content",
"ApiPathLeafName": "knowledgearticles",
"FieldDefinitions": [
{
"FieldUse": "Create",
"DocFieldSource": "ArticlePublicNumber",
"TargetFieldName": "articlepublicnumber",
"TargetFieldType": "String"
},
{
"DocFieldSource": "Constant",
"DocFieldPattern": "true",
"TargetFieldName": "msdyn_isingestedarticle",
"TargetFieldType": "Boolean"
},
{
"DocFieldSource": "Url",
"TargetFieldName": "msdyn_ingestedarticleurl",
"TargetFieldType": "String"
},
{
"DocFieldSource": "DataProvider",
"TargetFieldName": "msdyn_integratedsearchproviderid@odata.bind",
"TargetFieldType": "String"
},
{
"DocFieldSource": "Regex",
"DocFieldPattern": "<title>(.*?)</title>",
"TargetFieldName": "title",
"TargetFieldType": "String"
},
{
"DocFieldSource": "Meta",
"DocFieldPattern": "description",
"TargetFieldName": "description",
"TargetFieldType": "String",
"MaxLength": 155
},
{
"DocFieldSource": "Document",
"TargetFieldName": "content",
"TargetFieldType": "String"
},
{
"DocFieldSource": "Url",
"TargetFieldName": "msdyn_externalreferenceid",
"TargetFieldType": "String",
"UseRegexCapture": "^https://.*?/(.*?)/.*/.*?([0-9A-F]{8}[-](?:[0-9A-F]{4}[-]){3}[0-9A-F]{12})$"
}
]
}
Transformar, mapear datos de fuentes externas a campos de conocimiento
Al asignar información de proveedores de datos externos a entidades de artículo de conocimiento, si el valor de origen es de un tipo de datos diferente, debe transformar el valor para poder asignarlo al atributo de conocimiento de destino. Puede crear un complemento y registrarlo en Create y Update mensajes para que los atributos del artículo de conocimiento de destino tengan valores alineados con los artículos de los proveedores externos.
Para transformar y mapear los valores de origen, realice los siguientes pasos:
- Cree un campo personalizado en la
KnowledgeArticleentidad. Obtenga más información en Creación y edición de columnas. - Asigne el valor de origen externo necesario al campo personalizado recién creado. Obtenga más información en Configurar la asignación de esquemas del artículo de conocimiento (versión preliminar). Se trata de un mapeo temporal del cual el plugin extrae el valor de origen.
- Cree un complemento. Obtenga más información en Creación de un proyecto de complemento.
- Puede escribir su propio código para convertir el valor de origen externo y asignarlo al atributo de artículo de conocimiento de destino necesario.
En este ejemplo, se muestra cómo se puede asignar un valor de origen del tipo String a un atributo de campo de artículo de tipo OptionSet. En el complemento que creó, reemplace toda la clase por el código de ejemplo siguiente.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Services;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace PowerApps.Samples
{
/// <summary>
/// The plug-in shows the sample code to map the external source value to the target attribute, when they're of different types
/// </summary>
/// <remarks>
/// To showcase the capabilities of the plugin, we have added 2 new attributes to the KnowledgeArticle entity.
/// The first attribute new_documentationcentersourcevalue is a String attribute that is mapped to the external source value. This is a temporary mapping that stores the source value.
/// The plugin picks up the source value from new_documentationcentersourcevalue. The source value can take the following values: Develop, Content, and Test.
///The second attribute, new_documentationcenter, is the target attribute of type OptionSet to which the source value must actually be mapped to.
/// Develop with value 100000000, Content with value 100000001, and Test with value 100000002
/// The goal of this plugin to read the value from the new_documentationcentersourcevalue, retrieve the option set metadata of the target attribute new_documentationcenter, and map it to the value in new_documentationcentersourcevalue.
/// </remarks>
public sealed class KnowledgePlugin : IPlugin
{
/// <summary>
/// Execute method that is required by the IPlugin interface.
/// </summary>
/// <param name="serviceProvider">The service provider from which you can obtain the
/// tracing service, plug-in execution context, organization service, and more.</param>
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
// Verify that the target entity represents knowledgearticle.
if (entity.LogicalName != "knowledgearticle")
{
tracingService.Trace("KnowledgePlugin: Plugin is incorrectly called for the entity: " + entity.LogicalName);
return;
}
//Skip the plugin for RootArticles
const string isRootArticleAttributeName = "isrootarticle";
bool isRootArticle = entity.GetAttributeValue<bool>(isRootArticleAttributeName);
if (isRootArticle)
{
tracingService.Trace("KnowledgePlugin: Returning for Root Article");
return;
}
try
{
const string sourceValueAttributeName = "new_documentationcentersourcevalue";
const string targetValueAttributeName = "new_documentationcenter";
//Get the source value
string sourceValue = entity.GetAttributeValue<string>(sourceValueAttributeName);
if (string.IsNullOrEmpty(sourceValue))
{
tracingService.Trace("KnowledgePlugin: " + sourceValueAttributeName + " is not set");
return;
}
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
// Retrieve the option set metadata of the target field.
OptionSetMetadata retrievedOptionSetMetadata = RetrieveOptionSet(service, entity, targetValueAttributeName, tracingService);
// Check if the source data value is present in the retrieved target option set metadata.
OptionMetadata matchedOptionMetadata = retrievedOptionSetMetadata?.Options?.First(optionMetadata => optionMetadata.Label.UserLocalizedLabel.Label == sourceValue);
if (matchedOptionMetadata == null || matchedOptionMetadata.Value == null)
{
tracingService.Trace("KnowledgePlugin: Matching OptionMetadata is not found");
return;
}
// Map the option set value of the string new_documentationcentersourcevalue to the target option set new_documentationcenter.
int optionSetValue = (int)matchedOptionMetadata.Value;
entity[targetValueAttributeName] = new OptionSetValue(optionSetValue);
tracingService.Trace("KnowledgePlugin: Successfully set the value.");
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the KnowledgePlugin plug-in." + ex + "\n InnerException: " + ex.InnerException);
}
catch (Exception ex)
{
tracingService.Trace("Exception in KnowledgePlugin: {0}", ex);
throw ex;
}
}
}
/// <summary>
/// Fetch the optionset metadata from the entity metadata
/// </summary>
/// <param name="service">Organization Details</param>
/// <param name="entity">Entity record</param>
/// <param name="targetValueAttributeName">Optionset Attribute Name</param>
/// <param name="tracingService">Tracing Service</param>
private OptionSetMetadata RetrieveOptionSet(IOrganizationService service, Entity entity, string targetValueAttributeName, ITracingService tracingService)
{
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
{
LogicalName = entity.LogicalName,
EntityFilters = EntityFilters.Attributes,
RetrieveAsIfPublished = true
};
RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
EntityMetadata metadata = retrieveEntityResponse.EntityMetadata;
PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => string.Equals(attribute.LogicalName, targetValueAttributeName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata;
return picklistMetadata.OptionSet;
}
}
}
- Registre los mensajes del complemento
CreateyUpdatedel SDK de la entidad KnowledgeArticle en la fase PreOperation. Más información: Registro de un complemento
Información relacionada
Administrar proveedores de búsquedas integrados
Ver y usar información valiosa para los proveedores de búsqueda