Пример #1
0
        /// <summary>
        /// Create an argument wrapper for a property
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        private ArgumentViewModel CreateArgument(DynamicActivityProperty prop)
        {
            Type innerType = prop.Type.GetGenericArguments().FirstOrDefault() ?? prop.Type;

            if (innerType == typeof(bool))
            {
                return new BooleanArgumentViewModel()
                       {
                           Title = prop.Name, Property = prop
                       }
            }
            ;
            if (innerType == typeof(DateTime))
            {
                return new DateTimeArgumentViewModel()
                       {
                           Title = prop.Name, Property = prop
                       }
            }
            ;
            if (innerType == typeof(int))
            {
                return new IntArgumentViewModel()
                       {
                           Title = prop.Name, Property = prop
                       }
            }
            ;

            return(new TextArgumentViewModel()
            {
                Title = prop.Name + " (" + innerType.Name + ")", Property = prop
            });
        }
Пример #2
0
        public static Activity CreateSalutationRules(List <SalutationAssignmentRule> rules)
        {
            var inProperty = new DynamicActivityProperty
            {
                Name = "Person",
                Type = typeof(InArgument <Person>)
            };
            var activity = new DynamicActivity()
            {
                Properties = { inProperty }
            };

            Common.AddVbSetting(activity);

            var sequence = new Sequence();

            activity.Implementation = () => sequence;

            // Sort descending - those added first are lowest priority
            var sortedRules = rules.OrderByDescending(p => p.Priority).ToList();

            // Convert to if-activities and add to sequence
            foreach (var inRule in sortedRules)
            {
                var outRule = RuleConverter.ToIfActivity(inRule);
                sequence.Activities.Add(outRule);
            }

            return(activity);
        }
        /// <summary>
        /// Validates the arguments in ChildArguments property against the arguments of specified dynamicActivity instance by adding a validation error
        /// to supplied metadata if the argument is wrong type, direction or does not exist.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="dynamicActivity">The dynamic activity.</param>
        private void Validate(NativeActivityMetadata metadata, DynamicActivity dynamicActivity)
        {
            foreach (string argumentKey in this.ChildArguments.Keys)
            {
                if (dynamicActivity.Properties.Contains(argumentKey))
                {
                    DynamicActivityProperty dynamicActivityProperty = dynamicActivity.Properties[argumentKey];
                    Argument arg = this.ChildArguments[argumentKey];
                    if (dynamicActivityProperty.Type.GetGenericTypeDefinition() == typeof(InArgument <>) && arg.Direction != ArgumentDirection.In)
                    {
                        metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidInArgumentDirectionValidationErrorText, argumentKey)));
                    }
                    else if (dynamicActivityProperty.Type.GetGenericTypeDefinition() == typeof(OutArgument <>) && arg.Direction != ArgumentDirection.Out)
                    {
                        metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidOutArgumentDirectionValidationErrorText, argumentKey)));
                    }
                    else if (dynamicActivityProperty.Type.GetGenericTypeDefinition() == typeof(InOutArgument <>) && arg.Direction != ArgumentDirection.InOut)
                    {
                        metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidInOutArgumentDirectionValidationErrorText, argumentKey)));
                    }

                    if (dynamicActivityProperty.Type.GetGenericArguments()[0] != arg.ArgumentType)
                    {
                        metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidIArgumentTypeValidationErrorText, argumentKey, dynamicActivityProperty.Type.GetGenericArguments()[0])));
                    }
                }
                else
                {
                    metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidIArgumentValidationErrorText, argumentKey)));
                }
            }
        }
Пример #4
0
        internal static Variable GetVariableFromProperty(DynamicActivityProperty property)
        {
            Type     variableType = null;
            Variable autoVariable = null;

            if (property.Type != null)
            {
                Type propertyType = property.Type;

                // if the property is an Argument<T> create a variable of type T
                if (propertyType != null && typeof(Argument).IsAssignableFrom(propertyType))
                {
                    if (propertyType.IsGenericType)
                    {
                        variableType = propertyType.GetGenericArguments()[0];
                    }
                    else
                    {
                        variableType = typeof(object);
                    }
                }
            }
            if (variableType != null)
            {
                autoVariable = Variable.Create(property.Name, variableType, VariableModifiers.None);
                Argument argument = property.Value as Argument;
                if (argument != null)
                {
                    autoVariable.Default = argument.Expression;
                }
            }
            return(autoVariable);
        }
        public static Activity CreateSalutationRules()
        {
            var inProperty = new DynamicActivityProperty
            {
                Name = "Person",
                Type = typeof(InArgument <Person>)
            };
            var activity = new DynamicActivity()
            {
                Properties = { inProperty }
            };

            Common.AddVbSetting(activity);

            var sequence = new Sequence();

            activity.Implementation = () => sequence;

            // First rule
            var condition1 = new VisualBasicValue <bool>("Person.Gender = \"Male\"");
            var if1        = new If(new InArgument <bool>(condition1));

            if1.Then = new Assign <string>
            {
                To    = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")),
                Value = new InArgument <string>("Mr")
            };
            if1.Else = new Assign <string>
            {
                To    = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")),
                Value = new InArgument <string>("Miss")
            };

            // Second rule
            var condition2 = new VisualBasicValue <bool>("Person.Gender = \"Female\" AND Person.Married");
            var if2        = new If(new InArgument <bool>(condition2));

            if2.Then = new Assign <string>
            {
                To    = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")),
                Value = new InArgument <string>("Mrs")
            };

            // Third rule
            var condition3 = new VisualBasicValue <bool>("Person.Minor");
            var if3        = new If(new InArgument <bool>(condition3));

            if3.Then = new Assign <string>
            {
                To    = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")),
                Value = new InArgument <string>("To the parents of")
            };

            // Priority is implicitly defined by the order in which we add the IF-activites
            sequence.Activities.Add(if1);
            sequence.Activities.Add(if2);
            sequence.Activities.Add(if3);

            return(activity);
        }
        internal static Variable GetVariableFromProperty(DynamicActivityProperty property)
        {
            Type variableType = null;
            Variable autoVariable = null;

            if (property.Type != null)
            {
                Type propertyType = property.Type;

                // if the property is an Argument<T> create a variable of type T
                if (propertyType != null && typeof(Argument).IsAssignableFrom(propertyType))
                {
                    if (propertyType.IsGenericType)
                    {
                        variableType = propertyType.GetGenericArguments()[0];
                    }
                    else
                    {
                        variableType = typeof(object);
                    }
                }
            }
            if (variableType != null)
            {
                autoVariable = Variable.Create(property.Name, variableType, VariableModifiers.None);
                Argument argument = property.Value as Argument;
                if (argument != null)
                {
                    autoVariable.Default = argument.Expression;
                }
            }
            return autoVariable;
        }
Пример #7
0
        public void UpdateDropDownItems()
        {
            if (this.IsUpdatingDropDownItems)
            {
                return;
            }

            List <DynamicActivityProperty> list = new List <DynamicActivityProperty>();
            bool currentSelectionFound          = false;

            if (this.Properties != null)
            {
                foreach (ModelItem modelItem in this.Properties)
                {
                    DynamicActivityProperty property = modelItem.GetCurrentValue() as DynamicActivityProperty;

                    if (property != null)
                    {
                        if (this.Filter == null || this.Filter(property))
                        {
                            DynamicActivityProperty clone = new DynamicActivityProperty();
                            clone.Name = property.Name;
                            clone.Type = property.Type;
                            list.Add(clone);
                            if (StringComparer.Ordinal.Equals(this.SelectedPropertyName, property.Name))
                            {
                                currentSelectionFound = true;
                            }
                        }
                    }
                }
            }

            string savedSelectedPropertyName = this.SelectedPropertyName;

            if (!currentSelectionFound)
            {
                if (!string.IsNullOrEmpty(this.SelectedPropertyName))
                {
                    DynamicActivityProperty unresolvedProperty = new DynamicActivityProperty();
                    unresolvedProperty.Name = this.SelectedPropertyName;
                    list.Add(unresolvedProperty);
                }
            }

            list.Sort(new DynamicaActivityPropertyComparer());

            this.IsUpdatingDropDownItems = true;
            this.DropDownItems           = new ReadOnlyCollection <DynamicActivityProperty>(list);
            this.SelectedPropertyName    = savedSelectedPropertyName;
            this.IsUpdatingDropDownItems = false;
        }
Пример #8
0
        public static DynamicActivityProperty Find(ModelItemCollection properties, string propertyName)
        {
            foreach (ModelItem entry in properties)
            {
                DynamicActivityProperty property = (DynamicActivityProperty)entry.GetCurrentValue();

                if (StringComparer.Ordinal.Equals(property.Name, propertyName))
                {
                    return(property);
                }
            }

            return(null);
        }
Пример #9
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DynamicActivityProperty property = value as DynamicActivityProperty;

            if (property == null)
            {
                return(null);
            }

            if (property.Type == null)
            {
                return(string.Format(CultureInfo.CurrentUICulture, SR.PropertyReferenceNotResolved, property.Name));
            }
            else
            {
                return(TypeNameHelper.GetDisplayName(property.Type, false));
            }
        }
        private void FillArguments()
        {
            string propertyName = PropertyReferenceUtilities.GetPropertyReference(this.ModelItem.GetCurrentValue(), DelegatePropertyName);

            if (string.IsNullOrEmpty(propertyName))
            {
                return;
            }

            ModelTreeManager        manager  = this.Context.Services.GetService <ModelTreeManager>();
            DynamicActivityProperty property = DynamicActivityPropertyUtilities.Find(manager.Root.Properties["Properties"].Collection, propertyName);

            if (property == null || !property.Type.IsSubclassOf(typeof(ActivityDelegate)))
            {
                return;
            }

            ActivityDelegateMetadata metadata = ActivityDelegateUtilities.GetMetadata(property.Type);

            ModelItemCollection collection = this.ModelItem.Properties[DelegateArgumentsPropertyName].Value.Properties["ItemsCollection"].Collection;

            Type underlyingArgumentType = this.ModelItem.Properties[DelegateArgumentsPropertyName].Value.GetCurrentValue().GetType().GetGenericArguments()[1];

            if (!typeof(Argument).IsAssignableFrom(underlyingArgumentType))
            {
                return;
            }

            if (collection.Count == 0)
            {
                using (ModelEditingScope change = collection.BeginEdit(SR.FillDelegateArguments))
                {
                    Type dictionaryEntryType = typeof(ModelItemKeyValuePair <,>).MakeGenericType(new Type[] { typeof(string), underlyingArgumentType });
                    foreach (ActivityDelegateArgumentMetadata arg in metadata)
                    {
                        Argument  argument       = Argument.Create(arg.Type, arg.Direction == ActivityDelegateArgumentDirection.In ? ArgumentDirection.In : ArgumentDirection.Out);
                        object    mutableKVPair  = Activator.CreateInstance(dictionaryEntryType, new object[] { arg.Name, argument });
                        ModelItem argumentKVPair = collection.Add(mutableKVPair);
                    }

                    change.Complete();
                }
            }
        }
Пример #11
0
        public static ActivityBuilder ToBuilder(DynamicActivity dynamicActivity)
        {
            var activityBuilder = new ActivityBuilder
            {
                Implementation                       = dynamicActivity.Implementation != null?dynamicActivity.Implementation() : null,
                                                Name = dynamicActivity.Name
            };

            foreach (var item in dynamicActivity.Attributes)
            {
                activityBuilder.Attributes.Add(item);
            }

            foreach (var item in dynamicActivity.Constraints)
            {
                activityBuilder.Constraints.Add(item);
            }

            foreach (var item in dynamicActivity.Properties)
            {
                var property = new DynamicActivityProperty
                {
                    Name  = item.Name,
                    Type  = item.Type,
                    Value = null
                };

                foreach (var attribute in item.Attributes)
                {
                    property.Attributes.Add(attribute);
                }

                activityBuilder.Properties.Add(property);
            }

            VisualBasic.SetSettings(activityBuilder, VisualBasic.GetSettings(dynamicActivity));

            return(activityBuilder);
        }
    private void populateDynamicActivity()
    {
        //get the list of rules from repository
        var rules =
            ObjectFactory
            .Container
            .GetInstance <IRuleRepository>()
            .Rules
            .ToList();

        //Declare a dynamic property as the view model
        var inProperty = new DynamicActivityProperty
        {
            Name = "Model",
            Type = typeof(InArgument <HomeIndexViewModel>)
        };

        _dynamicActivity = new DynamicActivity()
        {
            Properties = { inProperty }
        };

        //Import references
        Common.AddVbSetting(activity);

        var sequence = new Sequence();

        activity.Implementation = () => sequence

                                  //Sort Descending - those added first are lowest priority
                                  var sortedRules = rules.OrderBy(x => x.Priority).ToList();

        foreach (var inRule in rules)
        {
            var outRule = RuleConverter.ToIfActivity(inRule);
            sequence.Activities.Add(outRule);
        }
    }
        public bool CreateNewArgumentWrapper()
        {
            bool result = false;

            if (null != this.ActivitySchema)
            {
                DynamicActivityProperty property = new DynamicActivityProperty()
                {
                    Name = this.GetDefaultName(),
                    Type = this.GetDefaultType(),
                };
                DesignTimeArgument wrapper = null;
                using (ModelEditingScope scope = this.ActivitySchema.BeginEdit((string)this.FindResource("addNewArgumentDescription")))
                {
                    ModelItem argument = this.GetArgumentCollection().Add(property);
                    wrapper = new DesignTimeArgument(argument, this);
                    this.argumentWrapperCollection.Add(wrapper);
                    scope.Complete();
                    result = true;
                }
                this.dgHelper.BeginRowEdit(wrapper);
            }
            return result;
        }
 private static bool IsActivityDelegate(DynamicActivityProperty instance)
 {
     return(instance.Type == typeof(ActivityDelegate) || instance.Type.IsSubclassOf(typeof(ActivityDelegate)));
 }
            protected override void Execute(NativeActivityContext context)
            {
                StringBuilder  errorBuilder = new StringBuilder();
                InvokeDelegate activity     = this.Activity.Get(context);

                string reference = PropertyReferenceUtilities.GetPropertyReference(activity, "Delegate");

                if (reference != null)
                {
                    DynamicActivityProperty property = null;

                    ModelTreeManager manager = this.EditingContext.Services.GetService <ModelTreeManager>();
                    if (manager.Root.ItemType == typeof(ActivityBuilder))
                    {
                        property = DynamicActivityPropertyUtilities.Find(manager.Root.Properties["Properties"].Collection, reference);
                    }

                    if (property == null)
                    {
                        this.EmitValidationError(context, string.Format(CultureInfo.CurrentUICulture, SR.PropertyReferenceNotResolved, reference));
                        return;
                    }

                    if (property.Type == typeof(ActivityDelegate))
                    {
                        this.EmitValidationWarning(context, string.Format(CultureInfo.CurrentUICulture, SR.PropertyIsNotAConcreteActivityDelegate, reference));
                        return;
                    }

                    if (!property.Type.IsSubclassOf(typeof(ActivityDelegate)))
                    {
                        this.EmitValidationError(context, string.Format(CultureInfo.CurrentUICulture, SR.PropertyIsNotAnActivityDelegate, reference));
                        return;
                    }

                    if (property.Type.IsAbstract)
                    {
                        this.EmitValidationWarning(context, string.Format(CultureInfo.CurrentUICulture, SR.PropertyIsNotAConcreteActivityDelegate, reference));
                        return;
                    }

                    ActivityDelegateMetadata metadata = ActivityDelegateUtilities.GetMetadata(property.Type);

                    if (activity.DelegateArguments.Count != metadata.Count)
                    {
                        this.EmitValidationWarning(context, SR.WrongNumberOfArgumentsForActivityDelegate);
                        return;
                    }

                    foreach (ActivityDelegateArgumentMetadata expectedArgument in metadata)
                    {
                        Argument delegateArgument = null;

                        if (activity.DelegateArguments.TryGetValue(expectedArgument.Name, out delegateArgument))
                        {
                            if ((expectedArgument.Direction == ActivityDelegateArgumentDirection.In && delegateArgument.Direction != ArgumentDirection.In) ||
                                (expectedArgument.Direction == ActivityDelegateArgumentDirection.Out && delegateArgument.Direction != ArgumentDirection.Out))
                            {
                                errorBuilder.AppendFormat(CultureInfo.CurrentUICulture, SR.DelegateArgumentsDirectionalityMismatch, expectedArgument.Name, delegateArgument.Direction, expectedArgument.Direction);
                            }

                            if (delegateArgument.ArgumentType != expectedArgument.Type)
                            {
                                if (expectedArgument.Direction == ActivityDelegateArgumentDirection.In)
                                {
                                    if (!TypeHelper.AreTypesCompatible(delegateArgument.ArgumentType, expectedArgument.Type))
                                    {
                                        errorBuilder.AppendFormat(CultureInfo.CurrentUICulture, SR.DelegateInArgumentTypeMismatch, expectedArgument.Name, expectedArgument.Type, delegateArgument.ArgumentType);
                                    }
                                }
                                else
                                {
                                    if (!TypeHelper.AreTypesCompatible(expectedArgument.Type, delegateArgument.ArgumentType))
                                    {
                                        errorBuilder.AppendFormat(CultureInfo.CurrentUICulture, SR.DelegateOutArgumentTypeMismatch, expectedArgument.Name, expectedArgument.Type, delegateArgument.ArgumentType);
                                    }
                                }
                            }
                        }
                        else
                        {
                            errorBuilder.AppendFormat(CultureInfo.CurrentUICulture, SR.DelegateArgumentMissing, expectedArgument.Name);
                        }
                    }

                    if (errorBuilder.Length > 0)
                    {
                        this.EmitValidationWarning(context, errorBuilder.ToString());
                    }
                }
            }
        private object TransformAndGetPropertySourceLocation(XamlReader reader, SourceTextScanner sourceTextScanner, SourceLocationFoundCallback sourceLocationFoundCallback)
        {
            // <property name, value's start location>
            Dictionary <string, SourceLocation> propertyValueLocationMapping = new Dictionary <string, SourceLocation>();

            object deserializedObject = null;
            object earlyResult        = null;

            UsingXamlWriter(
                new XamlObjectWriter(reader.SchemaContext),
                delegate(XamlObjectWriter objectWriter)
            {
                if (this.XamlSchemaContext.HasLocalAssembly)
                {
                    this.CopyNamespacesAndAddLocalAssembly(reader, objectWriter);
                }

                if (!(reader is IXamlLineInfo))
                {
                    XamlServices.Transform(reader, objectWriter);
                    earlyResult = objectWriter.Result;
                    return;
                }

                XamlType dynamicActivityPropertyType = this.XamlSchemaContext.GetXamlType(typeof(DynamicActivityProperty));
                while (reader.Read())
                {
                    // read SubTree will moves the reader pointed to
                    // element after its EO. So, we need to use a while
                    while (!reader.IsEof && reader.NodeType == XamlNodeType.StartObject &&
                           dynamicActivityPropertyType == reader.Type)
                    {
                        KeyValuePair <string, SourceLocation> nameSourceLocation = this.TransformDynamicActivityProperty(reader.ReadSubtree(), objectWriter, sourceTextScanner);
                        if (nameSourceLocation.Key != null && nameSourceLocation.Value != null && !propertyValueLocationMapping.ContainsKey(nameSourceLocation.Key))
                        {
                            propertyValueLocationMapping.Add(nameSourceLocation.Key, nameSourceLocation.Value);
                        }
                    }

                    if (!reader.IsEof)
                    {
                        objectWriter.WriteNode(reader);
                    }
                }

                deserializedObject = objectWriter.Result;
            });

            if (earlyResult != null)
            {
                return(earlyResult);
            }

            ActivityBuilder activityBuilder = deserializedObject as ActivityBuilder;

            if (activityBuilder == null)
            {
                return(deserializedObject);
            }

            foreach (KeyValuePair <string, SourceLocation> propertyValueLocation in propertyValueLocationMapping)
            {
                string         propertyName     = propertyValueLocation.Key;
                SourceLocation propertyLocation = propertyValueLocation.Value;
                if (!activityBuilder.Properties.Contains(propertyName))
                {
                    SharedFx.Assert(string.Format(CultureInfo.CurrentCulture, "no such property:{0}", propertyName));
                    continue;
                }

                DynamicActivityProperty property = activityBuilder.Properties[propertyName];

                if (property == null || property.Value == null)
                {
                    SharedFx.Assert(string.Format(CultureInfo.CurrentCulture, "no such property value:{0}", propertyName));
                    continue;
                }

                object expression = (property.Value is Argument) ? ((Argument)property.Value).Expression : null;
                if (expression != null)
                {
                    sourceLocationFoundCallback(expression, propertyLocation);
                }
                else
                {
                    sourceLocationFoundCallback(property.Value, propertyLocation);
                }
            }

            return(deserializedObject);
        }
Пример #17
0
        private void menuRun_Click(object sender, RoutedEventArgs e)
        {
#if RUNWF
            try
            {
                wd.Flush();
                Activity activity = null;
                using (StringReader reader = new StringReader(wd.Text))
                {
                    activity = ActivityXamlServices.Load(reader);
                }

                if (activity != null)
                {
#if LISTARGS
                    //list any defined arguments
                    messageListBox.Items.Clear();
                    ModelService ms =
                        wd.Context.Services.GetService <ModelService>();
                    ModelItemCollection items =
                        ms.Root.Properties["Properties"].Collection;
                    foreach (var item in items)
                    {
                        if (item.ItemType == typeof(DynamicActivityProperty))
                        {
                            DynamicActivityProperty prop =
                                item.GetCurrentValue() as DynamicActivityProperty;
                            if (prop != null)
                            {
                                Argument arg = prop.Value as Argument;
                                if (arg != null)
                                {
                                    messageListBox.Items.Add(String.Format(
                                                                 "Name={0} Type={1} Direction={2} Exp={3}",
                                                                 prop.Name, arg.ArgumentType,
                                                                 arg.Direction, arg.Expression));
                                }
                            }
                        }
                    }
#endif

                    StringBuilder sb = new StringBuilder();
                    using (StringWriter writer = new StringWriter(sb))
                    {
                        Console.SetOut(writer);
                        try
                        {
                            WorkflowInvoker.Invoke(activity);
                        }
                        catch (Exception exception)
                        {
                            MessageBox.Show(this,
                                            exception.Message, "Exception",
                                            MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        finally
                        {
                            MessageBox.Show(this,
                                            sb.ToString(), "Results",
                                            MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }

                    StreamWriter standardOutput =
                        new StreamWriter(Console.OpenStandardOutput());
                    Console.SetOut(standardOutput);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(this,
                                exception.Message, "Outer Exception",
                                MessageBoxButton.OK, MessageBoxImage.Error);
            }
#endif
        }