Trabalhando com dados complexos em um fluxo de trabalho

 

Publicado: julho de 2016

<_caps3a_sxs _xmlns3a_caps="https://schemas.microsoft.com/build/caps/2013/11"><_caps3a_sxstarget locale="pt-BR">O DynamicValue permite que você crie, armazene e consuma estruturas de dados. Esses dados podem ser recursivos, ou seja, o DynamicValue pode conter outros DynamicValues. As regras de composição do DynamicValue são muito simples: suas propriedades podem ser primitivos, matrizes ou outros DynamicValues, semelhante a um recipiente de propriedades recursivo ou formato de serialização JSON. O DynamicValue fornece o mecanismo de um contêiner e a manipulação de dados compostos com a superfície de associação de primeira classe do WF.Como um DynamicValue armazena os dadosEssencialmente, você pode pensar no DynamicValue como uma lista recursiva de pares chave-valor. A tabela a seguir representa um simples DynamicValue:NomeValor do tipo de dados primitivo subjacenteIdade42NomeJohn DoeNa tabela anterior, o DynamicValue tem duas propriedades: Age tem um valor de 42 e Name tem um valor de John Doe. O nome de uma propriedade do DynamicValue é uma cadeia de caracteres e o valor pode ser qualquer um dos tipos na lista a seguir ou null (Nothing no Visual Basic). Se qualquer outro tipo for passado para um DynamicValue, será emitida uma exceção.Cadeia de caracteresInt32DoubleGuidBoolianoDateTimeTimeSpanIList<T>, onde T é um dos tipos nessa listaIDictionary<string, T>, onde T é um dos tipos nessa listaDynamicValueObserve que o DynamicValue está na lista de tipos compatíveis. Isso significa que o valor de um DynamicValue pode ser outro DynamicValue, como mostrado na tabela a seguir.NomeValorClienteNomeValorIdade42NomeJon DoeEmpresaContoso CorporationO Customer contém um DynamicValue como seu valor e esse DynamicValue contém Age e Name. Para referenciar o valor para Name, você pode usar Customer/Name. Se o valor de Customer/Name for referenciado e ainda não tiver sido criado, ele será adicionado. Isso é chamado de upsert.O DynamicValue também é compatível com o conceito de matrizes. Uma matriz é um conjunto de valores primitivos contido como o valor para um DynamicValue. A principal diferença conceitual entre um DynamicValue como uma matriz, em vez de um DynamicValue aninhado, é que os itens na matriz não têm um nome e são acessados por índice. Observe que as matrizes podem conter diferentes tipos. No valor de matriz para Numbers, os tipos são Int32 e Double. No valor de matriz para Items, os valores são um DynamicValue aninhado e um Int32.NomeValorNúmeros4633.142.71ItensNomeValorPrimeiro4Segundo56Endereçamento de valores em um DynamicValueOs valores são definidos e recuperados de um DynamicValue usando uma notação de caminho. Os caminhos são cadeias de caracteres parecidas com Uri que indicam uma determinada propriedade, similar a uma representação plana de uma estrutura. Os caminhos são compostos usando o nome de uma propriedade, uma cadeia de caracteres ou um índice de um item dentro de um valor de matriz, usando um número entre parênteses.Para obter exemplos de como trabalhar com caminhos de DynamicValue, consulte a amostra Avaliador de caminho de DynamicValuehttps://go.microsoft.com/fwlink/?LinkId=257469. A amostra Avaliador de caminho de DynamicValuehttps://go.microsoft.com/fwlink/?LinkId=257469 permite que você insira um ponto de extremidade de um serviço REST que retorna JSON, para experimentar e ficar familiarizado com o DynamicValue e os caminhos dos dados retornados.Na seção anterior, foram dados diversos exemplos de DynamicValue. O primeiro exemplo era de um DynamicValue com dois valores, como mostrado na tabela a seguir.NomeValorIdade42NomeJohn DoePara acessar o primeiro valor, um caminho que consiste em Age é usado, o qual retorna o valor de 42. Um caminho de Name retorna o valor John Doe.O segundo exemplo da seção anterior incluía alguns valores aninhados, como mostrado na tabela a seguir.NomeValorClienteNomeValorIdade42NomeJon DoeEmpresaContoso CorporationO caminho Customer retorna um DynamicValue (que contém dois valores). O caminho de Company retorna Contoso Corporation. Para acessar os valores aninhados, um / é usado para delinear as propriedades. Usando essa notação, o caminho Customer/Age retorna o valor 42 e Customer/Name retorna John Doe.Para acessar os valores armazenados em uma matriz, são usados índices no caminho. A tabela a seguir representa o DynamicValue da seção anterior que continha matrizes e DynamicValues aninhados.NomeValorNúmeros4633.142.71ItensNomeValorPrimeiro4Segundo56No DynamicValue representado pela tabela anterior, um caminho de Numbers retorna a primeira matriz. As matrizes de DynamicValue são baseadas em zero, e Numbers(0) retorna o primeiro elemento da matriz, e Numbers(3) retorna o quarto elemento da matriz.Items retorna a segunda matriz e Items(0) retorna o primeiro item na matriz, que é um DynamicValue. Para acessar os valores nesse DynamicArray aninhado, os nomes de propriedades são combinados com o caminho que produz a matriz.Items(0)/First retorna 4 e Items(0)/Second retorna 5.Você pode usar os caminhos para construir declarativamente uma estrutura de dados composta. Os valores podem ser conhecidos no momento de projeção ou dinamicamente associados ao tempo de execução. O exemplo a seguir mostra um conjunto de caminhos e valores que representam uma composição de um cliente que tem um endereço.Caminho (Para)Valor (De)Primeiro nomeJohnSobrenomeDoeEndereço/CidadeRedmondEndereço/EstadoWAOs caminhos e valores na tabela anterior criariam o DynamicValue representado pela tabela a seguir.NomeValorPrimeiro nomeJohnSobrenomeDoeEndereçoNomeValorCidadeRedmondEstadoWAO tipo DynamicValue fornece um método Parse que pode ser usado para analisar uma cadeia de caracteres JSON em um DynamicValue. Além disso, existe uma atividade ParseDynamicValue que pode ser usada nos fluxos de trabalho para analisar uma cadeia de caracteres JSON em um DynamicValue.As atividades Http também são compatíveis com o DynamicValue. Se você atribuir um DynamicValue à resposta de uma atividade Http*, os resultados serão obtidos como um JSON e um DynamicValue será construído com o resultado. Se você passar um DynamicValue para o corpo de solicitação ou usá-lo como o conteúdo de resposta, os cabeçalhos apropriados serão adicionados para indicar que um JSON é usado.Usando o DynamicValue em fluxos de trabalhoAlém do tipo DynamicValue, o Workflow Manager 1.0 também fornece atividades para criar e trabalhar com DynamicValue em fluxos de trabalho.AtividadeDescriçãoArgumentosT:Microsoft.Activities.BuildDynamicValueConstrói uma instância de DynamicValue. Recebe um dicionário de caminhos e valores como entrada e retorna o DynamicValue resultante. Usa uma abordagem de multiatribuição para construir o DynamicValue (aceita vários caminhos e valores).Essa atividade pode ser usada para criar um novo DynamicValue ou para modificar um existente.Propriedades de InArgument<IDictionary<string,InArgument>>Resultado de InOutArgument<DynamicValue>T:Microsoft.Activities.ContainsDynamicValuePropertyRetorna verdadeiro se um DynamicValue contiver uma propriedade representada pelo caminho especificadoOrigem de InOutArgument<DynamicValue>PropertyName InOutArgument<DynamicValue>Resultado de OutArgument<bool>T:Microsoft.Activities.CopyDynamicValueCopia as propriedades de um DynamicValue para outro DynamicValuePropertyMapping InArgument<IDictionary<string,string>>Origem de InOutArgument<DynamicValue>Resultado de OutArgument<DynamicValue>T:Microsoft.Activities.CountDynamicValueItemsRetorna a contagem de filhos em um caminho de DynamicValueOrigem de InOutArgument<DynamicValue>Resultado de OutArgument<int>T:Microsoft.Activities.CreateDynamicValueCria uma instância de um DynamicValue passando apenas um caminho e um valor (semântica de não multiatribuição)PropertyName InArgument<string>PropertyValue InArgumentResultado de OutArgument<DynamicValue>T:Microsoft.Activities.CreateDynamicValueFromMessageCria um DynamicValue a partir de uma mensagem SOAPCabeçalhos <DynamicValue>Valor de InArgument<XElement>Versão InArgument<MessageVersion>Resultado de OutArgument<DynamicValue>T:Microsoft.Activities.CreateMessageFromDynamicValueCria uma mensagem SOAP a partir de um DynamicValue especialmente formatadoAção InArgument<string>Cabeçalhos <DynamicValue>Corpo de InOutArgument<DynamicValue>Versão InArgument<MessageVersion>Resultado de OutArgument<XElement>T:Microsoft.Activities.CreateUriFromDynamicValueCria um URI a partir de um DynamicValueOpções de InOutArgument<DynamicValue>Resultado de OutArgument<string>T:Microsoft.Activities.GetDynamicValuePropertiesObtém diversas propriedades de um DynamicValue existente. Dado um DynamicValue, um usuário pode consultar múltiplas propriedades (passando múltiplos caminhos) usando uma única atividade.Origem de InOutArgument<DynamicValue>Propriedades de InArgument<IDictionary<string,OutArgument>>T:Microsoft.Activities.GetDynamicValueProperty`1Obtém uma propriedade de um DynamicValue, onde T é um dos tipos na lista dada anteriormente.Origem de InOutArgument<DynamicValue>PropertyName InArgument<string>Resultado de OutArgument<T>T:Microsoft.Activities.ParseDynamicValueAnalisa uma cadeia de caracteres JSON para um DynamicValueJSON InArgument<string>Resultado de OutArgument<DynamicValue>Usando o DynamicValueO DynamicValue e as suas atividades de suporte permitem a representação e manipulação de dados em um host de um modo agnóstico. Portanto, o DynamicValue é um recurso de fluxo de trabalho que pode ser usado com qualquer host de fluxo de trabalho, não sendo limitado ao Workflow Manager 1.0. Pode ser usado com qualquer um dos outros hosts de fluxo de trabalho existentes, como o WorkflowInvoker, o WorkflowApplication e o WorkflowServiceHost.A amostra Trabalhando com dados complexos em um fluxo de trabalho usando DynamicValuehttps://go.microsoft.com/fwlink/?LinkId=257468 demonstra como usar o recurso com o WorkflowApplication. Várias das outras amostras de Using DynamicValue mostram como usar DynamicValue nos fluxos de trabalho de Workflow Manager 1.0. O uso do DynamicValue é o mesmo independentemente do host; o que muda para cada host é o modo como os dados são carregados para o DynamicValue (por exemplo, no Workflow Manager 1.0 é muito comum criar um DynamicValue como resultado de uma operação Http usando atividades Http).Para obter mais informações sobre as amostras do Workflow Manager 1.0 e onde encontrá-las, consulte Workflow 1.0 Beta Samples.<_caps3a_sxssource locale="en-US">DynamicValue allows you to create, store, and consume data structures. This data can be recursive, meaning that a DynamicValue can contain other DynamicValues.DynamicValue composition rules are very simple: its properties can be primitives, arrays, or other DynamicValues, similar to a recursive property bag or JSON serialization format.DynamicValue provides both a container and manipulation mechanism for compound data with first class binding surface for WF.How DynamicValue Stores its DataAt the very core, you can think of DynamicValue as a recursive list of key-value pairs. The following table represents a simple DynamicValue:NameValue of Underlying Primitive Data TypeAge42NameJohn DoeIn the previous table, the DynamicValue has two properties: Age has a value of 42 and Name has a value of John Doe. The name of a DynamicValue property is a string, and the value can be any one of the types in the following list, or null (Nothing in Visual Basic). If any other type is passed to a DynamicValue an exception will be thrown.StringInt32DoubleGuidBooleanDateTimeTimeSpanIList<T>, where T is one of the types in this listIDictionary<string, T>, where T is one of the types in this listDynamicValueNote that DynamicValue is in the list of supported types. This means that the value of a DynamicValue can be another DynamicValue, as shown in the following table.NameValueCustomerNameValueAge42NameJon DoeCompanyContoso CorporationCustomer contains a DynamicValue as its value, and that DynamicValue contains Age and Name. To reference the value for Name, you can use Customer/Name. If Customer/Name value is referred to and it has not yet been created, it will be added. This is referred to as an upsert.DynamicValue also supports the notion of arrays. An array is a set of primitive values contained as the value for a DynamicValue. The main conceptual difference between a DynamicValue as an array instead of nested DynamicValue is that the items in the array do not have a name and are accessed by index. Note that the arrays can contain different types. In the array value for Numbers, the types are Int32 and Double. In the array value for Items, the values are a nested DynamicValue and an Int32.NameValueNumbers4633.142.71ItemsNameValueFirst4Second56Addressing Values in a DynamicValueValues are set and retrieved from a DynamicValue using a path notation. Paths are Uri-like strings that point to a given property, similar to the flattened representation of a structure. Paths are composed using the name of a property, using a string, or an index into an item within an array value, using a number surrounded by parenthesis.To see examples of working with DynamicValue paths, see the DynamicValue Path Evaluatorhttps://go.microsoft.com/fwlink/?LinkId=257469 sample. The DynamicValue Path Evaluatorhttps://go.microsoft.com/fwlink/?LinkId=257469 sample allows you to enter the endpoint of a REST service that returns JSON, and experiment and become familiar with DynamicValue and paths of the returned data.In the previous section, several examples of DynamicValue were given. The first example was for a DynamicValue with two values, as shown in the following table.NameValueAge42NameJohn DoeTo access the first value, a path consisting of Age is used, which returns a value of 42. A path of Name returns the value John Doe.The second example from the previous section included some nested values, as shown in the following table.NameValueCustomerNameValueAge42NameJon DoeCompanyContoso CorporationThe path Customer returns a DynamicValue (which itself contains two values). The path of Company returns Contoso Corporation. In order to access nested values, a / is used to delineate properties. Using this notation, the path Customer/Age returns a value of 42, and Customer/Name returns John Doe.To access values stored in an array, indexes are used in the path. The following table represents the DynamicValue from the previous section that contained booth arrays and nested DynamicValues.NameValueNumbers4633.142.71ItemsNameValueFirst4Second56In the DynamicValue represented by the previous table, a path of Numbers returns the first array.DynamicValue arrays are zero based, and Numbers(0) returns the first element of the array, and Numbers(3) returns the fourth element of the array.Items returns the second array, and Items(0) returns the first item in the array, which is a DynamicValue. To access the values in that nested DynamicArray, the property names are combined with the path that yields the array.Items(0)/First returns 4 and Items(0)/Second returns 5.You can use paths to declaratively build a compound data structure. The values can be known at design time or dynamically bound at runtime. The following example shows a set of paths and values that represent a composition of a customer that has an address.Path (To)Value (From)FirstNameJohnLastNameDoeAddress/CityRedmondAddress/StateWAThe paths and values in the previous table would create the DynamicValue represented by the following table.NameValueFirstNameJohnLastNameDoeAddressNameValueCityRedmondStateWAThe DynamicValue type provides a Parse method that can be used to parse a JSON string into a DynamicValue. In addition, there is a ParseDynamicValue activity that can be used in workflows to parse a JSON string into a DynamicValue.Http activities can also understand DynamicValue. If you assign a DynamicValue to the response of an Http* activity, it will get the results as JSON and build a DynamicValue with that result. If you pass a DynamicValue to the request body or use it as the response content, the appropriate headers will be added to indicate that JSON is used.Using DynamicValue in WorkflowsIn addition to the DynamicValue type, Workflow Manager 1.0 also provides activities for creating and working with DynamicValue in workflows.ActivityDescriptionArgumentsT:Microsoft.Activities.BuildDynamicValueBuilds a DynamicValue instance. It receives a dictionary of paths and values as input and returns the resulting DynamicValue. It uses a multi-assign approach to build the DynamicValue (it accepts multiple paths and values).This activity can be used to create a new DynamicValue or to modify an existing one.InArgument<IDictionary<string,InArgument>> PropertiesInOutArgument<DynamicValue> ResultT:Microsoft.Activities.ContainsDynamicValuePropertyReturns true if a DynamicValue contains a property represented by the specified pathInArgument<DynamicValue> SourceInArgument<DynamicValue> PropertyNameOutArgument<bool> ResultT:Microsoft.Activities.CopyDynamicValueCopies properties from one DynamicValue to another DynamicValueInArgument<IDictionary<string,string>> PropertyMappingInArgument<DynamicValue> SourceOutArgument<DynamicValue> ResultT:Microsoft.Activities.CountDynamicValueItemsReturns the count of children in a DynamicValue pathInArgument<DynamicValue> SourceOutArgument<int> ResultT:Microsoft.Activities.CreateDynamicValueCreate an instance of a DynamicValue passing only one path and one value (no multi-assign semantics)InArgument<string> PropertyNameInArgument PropertyValueOutArgument<DynamicValue> ResultT:Microsoft.Activities.CreateDynamicValueFromMessageCreates a DynamicValue from a SOAP messageInArgument<DynamicValue> HeadersInArgument<XElement> ValueInArgument<MessageVersion> VersionOutArgument<DynamicValue> ResultT:Microsoft.Activities.CreateMessageFromDynamicValueCreates a SOAP message from a specially formatted DynamicValueInArgument<string> ActionInArgument<DynamicValue> HeadersInArgument<DynamicValue> BodyInArgument<MessageVersion> VersionOutArgument<XElement> ResultT:Microsoft.Activities.CreateUriFromDynamicValueCreates a URI from a DynamicValueInArgument<DynamicValue> OptionsOutArgument<string> ResultT:Microsoft.Activities.GetDynamicValuePropertiesGet several properties of an existing DynamicValue. Given a DynamicValue a user can query multiple properties (passing multiple paths) using a single activity.InArgument<DynamicValue> SourceInArgument<IDictionary<string,OutArgument>> PropertiesT:Microsoft.Activities.GetDynamicValueProperty`1Get one property of a DynamicValue, where T is one of the types in previously given list.InArgument<DynamicValue> SourceInArgument<string> PropertyNameOutArgument<T> ResultT:Microsoft.Activities.ParseDynamicValueParse a JSON string into a DynamicValueInArgument<string> JSONOutArgument<DynamicValue> ResultUsing DynamicValueDynamicValue and its supporting activities allow for representing and manipulating data in a host agnostic way. Hence, DynamicValue is a workflow feature that can be used with any workflow host, so it is not limited to Workflow Manager 1.0. It can be used with any of the other existing workflow hosts like WorkflowInvoker, WorkflowApplication, and WorkflowServiceHost.The Working with complex data in a workflow using DynamicValuehttps://go.microsoft.com/fwlink/?LinkId=257468 sample demonstrates how to use the feature with WorkflowApplication. Several of the other Using DynamicValue samples show how to use DynamicValue in Workflow Manager 1.0 workflows.DynamicValue usage is the same regardless of the host; what changes for every host is how the data is loaded into the DynamicValue (for example in Workflow Manager 1.0 it is very common to create the DynamicValue as the result of an Http operation using Http activities).For information about the Workflow Manager 1.0 samples and where to locate them, see Workflow 1.0 Beta Samples.