检索工作流的参数(使用默认值)?

时间:2012-01-11 17:18:02

标签: workflow-foundation-4

给出了一个针对网站的Workflow Foundation 4运行时;)

我们需要获取工作流的参数,以向用户显示输入参数的编辑器。为此,我们需要所有带有名称,类型和 - 默认值的参数,以及是否需要参数的指示。

工作流程存储为XAML文件。

怎么做?数据似乎在活动元数据中,似乎在工作流之外是不可用的。此外,Workflow Engine ModelService适用于Designer,并且有很多开销。

检索此信息的简便方法是什么?

2 个答案:

答案 0 :(得分:2)

我已经做过类似的事了。如果你想要一个通用的方法,反射可能是你最好的(也是唯一的)选择。

// Just an holder for InArgument informations
class InArgumentInfo
{
    public string InArgumentName { get; set; }
    public string InArgumentDescription { get; set; }
    public bool InArgumentIsRequired { get; set; }
}

static ICollection<InArgumentInfo> GetInArgumentsInfos(Activity activity)
{
    var properties = activity.GetType()
        .GetProperties()
        .Where(p => typeof(InArgument).IsAssignableFrom(p.PropertyType))
        .ToList();

    var argumentsCollection = new Collection<InArgumentInfo>();

    foreach (var property in properties)
    {
        var descAttribute = property
            .GetCustomAttributes(false)
            .OfType<DescriptionAttribute>()
            .FirstOrDefault();

        string description = descAttribute != null && !string.IsNullOrEmpty(descAttribute.Description) ?
            descAttribute.Description :
            string.Empty;

        bool isRequired = property
            .GetCustomAttributes(false)
            .OfType<RequiredArgumentAttribute>()
            .Any();

        argumentsCollection.Add(new InArgumentInfo
        {
            InArgumentName = property.Name,
            InArgumentDescription = description,
            InArgumentIsRequired = isRequired
        });
    }

    return argumentsCollection;
}

这样,您不仅可以检索参数的名称,还可以检索参数属性所持有的其他信息。例如,我选择通过 [Description] 属性为参数提供一个用户友好的名称(例如,而不是MyPropertyName用户看到“我的属性名称”)。

注意:如果您可以确保您的活动是ActivityBuilderDynamicActivity,那么他们都可以使用Properties属性,但原则是同样的。

答案 1 :(得分:0)

将其加载为DynamicActivity并迭代Properties属性

var dynamicActivity = ActivityXamlServices.Load(foo) as DynamicActivity
foreach(DynamicActivityProperty prop in dynamicActivity.Properties)
{
   // ...
}

更新:错过默认值部分

foreach (var prop in dynamicActivity .Properties)
{
    object defaultValue;
    if (prop.Value == null)
    {
        defaultValue = null;
    }
    else
    {
        Type genericTypeDefinition = prop.Type.GetGenericTypeDefinition();
        if (genericTypeDefinition == typeof(InArgument<>) || genericTypeDefinition == typeof(InOutArgument<>))
        {
            var valueProp = prop.Value.GetType().GetProperty("Expression", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly);
            var expression = valueProp.GetValue(prop.Value, null);

            var expressionValueProp = expression.GetType().GetProperty("Value");
            defaultValue = expressionValueProp.GetValue(expression, null);
        }
    }
}

不完全保证,您需要做一些检查。