Поделиться через


Конфигурация Workflow Manager 1.0 и внешние значения

 

Опубликовано: Июль 2016

<_caps3a_sxs _xmlns3a_caps="https://schemas.microsoft.com/build/caps/2013/11"><_caps3a_sxstarget locale="ru-RU">Диспетчер рабочих процессов 1.0 предоставляет возможность задавать значения конфигурации, используемые при выполнении, что позволяет применять распространенные рекомендации при моделировании процессов, например отказаться от жесткого кодирования параметров, способных меняться в определении программы (в данном случае рабочего процесса). Разработчики приложений с рабочими процессами могут задавать параметры приложений, связанные с определением рабочего процесса. Эти параметры приложений представляют собой список пар "ключ-значение", аналогичных AppSettings в .NET. Этот список может содержать произвольный набор ключей и значений, представляющих данные, необходимые для вашего рабочего процесса.В этом разделеSetting Configuration Using Configuration Information in a Workflow ExternalVariables and UserStatus ExternalVariables vs. Configuration Задание конфигурацииПараметры конфигурации приложений задаются на уровне определения рабочего процесса через WorkflowDescription.Configuration. Приведенный ниже код демонстрирует задание параметров приложений путем добавления элементов в коллекцию AppSettings в WorkflowConfiguration.sampleConfigValueWorkflow.Configuration = new WorkflowConfiguration(); sampleConfigValueWorkflow.Configuration.AppSettings.Add("configSetting1", "configuration value"); sampleConfigValueWorkflow.Configuration.AppSettings.Add("anotherConfigSetting", "another value"); WorkflowConfiguration предоставляет другие параметры конфигурации, не используемые напрямую в программной модели WF, например параметры регулирования.Конфигурацию рабочего процесса по умолчанию можно задать для всех рабочих процессов в заданной области, указать для объекта WorkflowConfiguration значение ScopeInfo.DefaultWorkflowConfiguration. Когда эта конфигурация по умолчанию задана, все WorkflowDefinitions в области действия будут использовать параметры из нее.WorkflowDefinitions могут переопределить их, задавая свои WorkflowConfiguration.Использование конфигурационных данных в рабочем процессеДействие GetConfigurationValue позволяет разработчикам рабочих процессов использовать параметры приложения из конфигурации для конкретного рабочего процесса.GetConfigurationValue принимает имя параметра приложения и выходной переменной для хранения параметра приложения. Также принимается необязательное значение по умолчанию, заносимое в переменную, если запрошенный параметр не найден. Рабочий процесс на следующем снимке экрана демонстрирует GetConfigurationActivity, использующий параметр configSetting1 из предыдущего примера.ExternalVariables и UserStatusExternalVariables позволяют разработчикам моделировать глобальное состояние в рабочем процессе. ExternalVariables добавляются в WorkflowDefinition с помощью свойства P:Microsoft.Workflow.Client.WorkflowDescription.ExternalVariables и доступны всем действиям в рамках этого рабочего процесса. Это значит, что эти переменные будут доступны всем дочерним реализациям рабочего процесса, включая реализацию пользовательских действий в нем. ExternalVariables могут иметь любой тип, допустимый для рабочих процессов (типы из разрешенного списка).Допустимые для Дополнительные сведения типы см. в статье Workflow 1.0 Beta Trusted Surface.ExternalVariables можно сопоставлять. Это означает, что при сохранении рабочего процесса доступ к ним возможен с помощью WorkflowInstanceInfo.MappedVariables. Если ExternalVariable не помечена как сопоставленная, она будет сохранена как часть состояния экземпляра, но не будет доступна через WorkflowInstanceInfo.Значения T:Microsoft.Activities.ExternalVariable доступны с помощью действия ExternalVariableValue<T>. Чтобы задать значение ExternalVariable, ExternalVariableReference<T> используется как L-значение (например, в Assign).T:Microsoft.Activities.ExternalVariableValue`1 поддерживается в конструкторе рабочих процессов, но сейчас T:Microsoft.Activities.ExternalVariableReference`1 поддерживается только в коде.В Диспетчер рабочих процессов 1.0 также есть первоклассная сопоставленная ExternalVariable с именем UserStatus (доступная через свойство P:Microsoft.Workflow.Client.WorkflowInstanceInfo.UserStatus) и действие для ее задания из рабочего процесса — T:Microsoft.Activities.SetUserStatus. Это простой способ начать использование ExternalVariables в самом распространенном случае, где требуется только одна ExternalVariable.Сравнение ExternalVariables и КонфигурацияВ следующей таблице сравниваются возможности конфигурации Workflow и ExternalVariables.CapabilityКонфигурацияExternalVariablesДетализацияОпределение или выше (например, область)ЭкземплярДопустимые типыСтрокаВсе разрешенные типыМожет изменяться экземпляром рабочего процессаНетдаКонтактная зона действияGetConfigurationValueExternalVariablesValue<T> ExternalVariableReference<T>Может сопоставлятьсяНетДа<_caps3a_sxssource locale="en-US">Диспетчер рабочих процессов 1.0 provides the capability of setting configuration values to be used during execution, enabling common and well established best practices when modeling processes such as avoiding hard coding parameters that may change within a program definition (in this case, a workflow). Workflow application authors can set application settings associated with a workflow definition. These application settings are a list of key-value pairs and are similar in concept to .NET AppSettings. This list can contain any set of keys and values to represent relevant information for your workflow.In this topicSetting Configuration Using Configuration Information in a Workflow ExternalVariables and UserStatus ExternalVariables vs. Configuration Setting ConfigurationConfiguration application settings are established at the workflow definition level via WorkflowDescription.Configuration. The code below demonstrates an example of how to set application settings (by adding items to the AppSettings collection of WorkflowConfiguration).sampleConfigValueWorkflow.Configuration = new WorkflowConfiguration(); sampleConfigValueWorkflow.Configuration.AppSettings.Add("configSetting1", "configuration value"); sampleConfigValueWorkflow.Configuration.AppSettings.Add("anotherConfigSetting", "another value"); WorkflowConfiguration provides other configuration settings that are not directly usable from the programming model in WF such as throttling options.A default workflow configuration can be set to all the workflows in a given scope by setting a WorkflowConfiguration object to ScopeInfo.DefaultWorkflowConfiguration. When this default configuration is set all the WorkflowDefinitions in the scope will use those configuration settings.WorkflowDefinitions can override them by providing their own WorkflowConfiguration.Using Configuration Information in a WorkflowThe GetConfigurationValue activity enables workflow authors to consume Application Settings from configuration for a given workflow.GetConfigurationValue accepts the name of the application setting and an output variable where to store the application setting. It also accepts an optional default value that is the value that will be assigned to the output variable in case that the requested application setting is not found. The workflow in the following screenshot demonstrates a GetConfigurationActivity that uses the configSetting1 setting specified in the previous example.ExternalVariables and UserStatusExternalVariables allow workflow authors to model global state within a workflow. ExternalVariables are added to a WorkflowDefinition using the P:Microsoft.Workflow.Client.WorkflowDescription.ExternalVariables property, and are visible to all activities within that workflow. This means that these variables are going to be visible to all implementation children of the workflow, including the implementation of the custom activities used in it. ExternalVariables can be of any type allowed within workflows (types in the allowed types list).Дополнительные сведения allowed types, see Workflow 1.0 Beta Trusted Surface.ExternalVariables can be mapped. This means that when the workflow is persisted they can be accessed using WorkflowInstanceInfo.MappedVariables. If an ExternalVariable is not marked as mapped, it will be saved as part of the instance state but will not be accessible using WorkflowInstanceInfo.T:Microsoft.Activities.ExternalVariable values are accessed using ExternalVariableValue<T> activity. In order to set the value of an ExternalVariable, ExternalVariableReference<T> is used as an L-Value (for example in Assign).T:Microsoft.Activities.ExternalVariableValue`1 is supported in the workflow designer, but currently T:Microsoft.Activities.ExternalVariableReference`1 is only supported in code.Диспетчер рабочих процессов 1.0 also introduces a first-class mapped ExternalVariable named UserStatus (accessed using the P:Microsoft.Workflow.Client.WorkflowInstanceInfo.UserStatus property) and an activity to set it from the workflow called T:Microsoft.Activities.SetUserStatus. This provides a simple start-up experience for using ExternalVariables in the most common case where only a single ExternalVariable is needed.ExternalVariables vs. ConfigurationThe following table compares the features of Workflow Configuration and ExternalVariables.CapabilityConfigurationExternalVariablesGranularityDefinition or higher (e.g. Scope)InstanceAllowed TypesStringAny type in the allowed types listCan be changed by workflow instanceNoYesActivity SurfaceGetConfigurationValueExternalVariablesValue<T> ExternalVariableReference<T>Can be mappedNoYes