Ejemplo n.º 1
0
        private static bool TryEvaluateExpression(string expressionString, Type locationValueType, LocationReferenceEnvironment locationReferenceEnvironment, ActivityContext context, out object result)
        {
            Type type;

            expressionString = string.Format(CultureInfo.InvariantCulture, "[{0}]", new object[] { expressionString });
            if (locationValueType != null)
            {
                type = typeof(Activity <>).MakeGenericType(new Type[] { typeof(Location <>).MakeGenericType(new Type[] { locationValueType }) });
            }
            else
            {
                type = typeof(Activity <object>);
            }
            ActivityWithResultConverter converter = new ActivityWithResultConverter(type);
            TypeDescriptorContext       context2  = new TypeDescriptorContext {
                LocationReferenceEnvironment = locationReferenceEnvironment
            };
            ActivityWithResult expression = converter.ConvertFromString(context2, expressionString) as ActivityWithResult;

            if (locationValueType != null)
            {
                LocationHelper helper = (LocationHelper)Activator.CreateInstance(typeof(LocationHelper).MakeGenericType(new Type[] { locationValueType }));
                return(helper.TryGetValue(expression, locationReferenceEnvironment, context, out result));
            }
            return(TryEvaluateExpression <object>(expression, locationReferenceEnvironment, context, out result));
        }
        internal static Argument MorphArgument(ModelItem originalValue, Type targetType)
        {
            Argument           morphed            = null;
            Argument           original           = (Argument)originalValue.GetCurrentValue();
            ActivityWithResult originalExpression = original.Expression;

            if (originalExpression != null)
            {
                Type expressionType        = originalExpression.GetType();
                Type expressionGenericType = expressionType.IsGenericType ? expressionType.GetGenericTypeDefinition() : null;

                if (expressionGenericType != null)
                {
                    bool isLocation = ExpressionHelper.IsGenericLocationExpressionType(originalExpression);
                    ActivityWithResult morphedExpression;
                    EditingContext     context = originalValue.GetEditingContext();
                    morphed = Argument.Create(targetType, original.Direction);
                    if (ExpressionHelper.TryMorphExpression(originalExpression, isLocation, targetType,
                                                            context, out morphedExpression))
                    {
                        morphed.Expression = morphedExpression;
                    }
                    //[....]
                }
            }
            return(morphed);
        }
Ejemplo n.º 3
0
        public static string ToString(ActivityWithResult activity)
        {
            if (activity == null)
            {
                return(null);
            }

            if (activity.GetType().IsConstructedGenericTypeOf(typeof(Literal <>)) && CSharpConvert.IsCodePrimitive(activity.ResultType))
            {
                return(CSharpConvert.ToString(((dynamic)activity).Value));
            }

            var serializableExpression = activity as IValueSerializableExpression;

            if (serializableExpression != null && serializableExpression.CanConvertToString(null))
            {
                return(serializableExpression.ConvertToString(null));
            }

            var textExpression = activity as ITextExpression;

            if (textExpression != null)
            {
                return(textExpression.ExpressionText);
            }

            return(null);
        }
Ejemplo n.º 4
0
        // Recompile the VBReference passed in, with its current LocationReferenceEnvironment context
        // in a weakly-typed manner (the argument VBReference's type argument is ignored)
        //[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters,
        //    Justification = "Design has been approved")]
        public static Activity RecompileVisualBasicReference(ActivityWithResult visualBasicReference,
                                                             out Type returnType,
                                                             out SourceExpressionException compileError,
                                                             out VisualBasicSettings vbSettings)
        {
            ITextExpression textExpression = visualBasicReference as ITextExpression;

            if (textExpression == null || textExpression.Language != VisualBasicHelper.Language)
            {
                // the argument must be of type VisualBasicReference<>
                throw FxTrace.Exception.AsError(new ArgumentException());
            }
            string expressionText = textExpression.ExpressionText;
            LocationReferenceEnvironment environment = visualBasicReference.GetParentEnvironment();

            List <string> namespaces;
            List <string> referencedAssemblies;

            GetAllImportReferences(visualBasicReference, out namespaces, out referencedAssemblies);

            return(CreatePrecompiledVisualBasicReference(
                       null,
                       expressionText,
                       namespaces,
                       referencedAssemblies,
                       environment,
                       out returnType,
                       out compileError,
                       out vbSettings));
        }
 public override bool TryMorphExpression(ActivityWithResult expression, bool isLocationExpression, Type newType, 
     EditingContext context, out ActivityWithResult newExpression)
 {
     string expressionText = ExpressionHelper.GetExpressionString(expression);            
     newExpression = VisualBasicEditor.CreateExpressionFromString(newType, expressionText, isLocationExpression, new ParserContext());
     return true;
 }
Ejemplo n.º 6
0
        public override bool TryMorphExpression(ActivityWithResult expression, bool isLocationExpression, Type newType,
                                                EditingContext context, out ActivityWithResult newExpression)
        {
            Fx.Assert(expression != null, "Original expression shouldn't be null in morph helper");
            Fx.Assert(context != null, "EditingContext shouldn't be null in morph helper");
            newExpression = null;
            if (expression.ResultType == newType &&
                (ExpressionHelper.IsGenericLocationExpressionType(expression) == isLocationExpression))
            {
                newExpression = expression;
                return(true);
            }

            if (context != null)
            {
                string        expressionEditor = ExpressionHelper.GetRootEditorSetting(context.Services.GetService <ModelTreeManager>(), WorkflowDesigner.GetTargetFramework(context));
                ParserContext parserContext    = new ParserContext();
                string        expressionText   = ExpressionHelper.GetExpressionString(expression, parserContext);
                if (!string.IsNullOrEmpty(expressionEditor))
                {
                    return(ExpressionTextBox.TryConvertFromString(expressionEditor, expressionText, isLocationExpression, newType, out newExpression));
                }
            }

            return(false);
        }
        protected override void OnExecute(NativeActivityContext context, object objectToValidate, ValidationContext objectToValidateContext)
        {
            bool foundMultiple;
            ActivityWithResult boundExpression;
            LocationReference  locationReference;
            ActivityWithResult activity = (ActivityWithResult)objectToValidate;

            foreach (RuntimeArgument runtimeArgument in activity.RuntimeArguments)
            {
                boundExpression = runtimeArgument.BoundArgument.Expression;

                if (boundExpression != null && boundExpression is ILocationReferenceWrapper)
                {
                    locationReference = ((ILocationReferenceWrapper)boundExpression).LocationReference;

                    if (locationReference != null)
                    {
                        foundMultiple = FindLocationReferencesFromEnvironment(objectToValidateContext.Environment, locationReference.Name);
                        if (foundMultiple)
                        {
                            Constraint.AddValidationError(context, new ValidationError(SR.AmbiguousVBVariableReference(locationReference.Name)));
                        }
                    }
                }
            }
        }
        public override bool TryMorphExpression(ActivityWithResult expression, bool isLocationExpression, Type newType, 
            EditingContext context, out ActivityWithResult newExpression)
        {
            Fx.Assert(expression != null, "Original expression shouldn't be null in morph helper");
            Fx.Assert(context != null, "EditingContext shouldn't be null in morph helper");
            newExpression = null;
            if (expression.ResultType == newType && 
                (ExpressionHelper.IsGenericLocationExpressionType(expression) == isLocationExpression))
            {
                newExpression = expression;
                return true;
            }

            if (context != null)
            {
                string expressionEditor = ExpressionHelper.GetRootEditorSetting(context.Services.GetService<ModelTreeManager>(), WorkflowDesigner.GetTargetFramework(context));
                ParserContext parserContext = new ParserContext();
                string expressionText = ExpressionHelper.GetExpressionString(expression, parserContext);
                if (!string.IsNullOrEmpty(expressionEditor))
                {
                    return ExpressionTextBox.TryConvertFromString(expressionEditor, expressionText, isLocationExpression, newType, out newExpression);
                }
            }

            return false;
        }
Ejemplo n.º 9
0
        public CompiledExpressionInvoker(ITextExpression expression, bool isReference, CodeActivityMetadata metadata)
        {
            if (metadata == null)
            {
                throw FxTrace.Exception.ArgumentNull(nameof(metadata));
            }

            this.expressionId       = -1;
            this.textExpression     = expression ?? throw FxTrace.Exception.ArgumentNull(nameof(expression));
            this.expressionActivity = expression as Activity;
            this.isReference        = isReference;
            this.locationReferences = new List <LocationReference>();
            this.metadata           = metadata;
            this.accessor           = CodeActivityPublicEnvironmentAccessor.Create(this.metadata);

            if (this.expressionActivity == null)
            {
                throw FxTrace.Exception.Argument(nameof(expression), SR.ITextExpressionParameterMustBeActivity);
            }

            ActivityWithResult resultActivity = this.expressionActivity as ActivityWithResult;

            this.metadataRoot = metadata.Environment.Root;

            this.ProcessLocationReferences();
        }
Ejemplo n.º 10
0
        public override bool TryMorphExpression(ActivityWithResult expression, bool isLocationExpression, Type newType,
                                                EditingContext context, out ActivityWithResult newExpression)
        {
            string expressionText = ExpressionHelper.GetExpressionString(expression);

            newExpression = VisualBasicEditor.CreateExpressionFromString(newType, expressionText, isLocationExpression, new ParserContext());
            return(true);
        }
        private void GenerateExpression()
        {
            //TODO: Enhance the type infering logic
            if (ExpressionType == null)
            {
                // Get the variables in scope
                List <ModelItem> declaredVariables = CSharpExpressionHelper.GetVariablesInScope(OwnerActivity);

                if (declaredVariables.Count > 0)
                {
                    InferredType = ((LocationReference)declaredVariables[0].GetCurrentValue()).Type;
                }
            }

            Type resultType = ExpressionType != null ? ExpressionType : InferredType;

            ////This could happen when:
            ////1) No ExpressionType is specified and
            ////2) The expression is invalid so that the inferred type equals to null
            if (resultType == null)
            {
                resultType = typeof(object);
            }

            // If the text is null we don't need to bother generating the expression (this would be the case the
            // first time you enter an ETB. We still need to generate the expression when it is EMPTY however - otherwise
            // the case where you had an expression (valid or invalid), then deleted the whole thing will not be evaluated.
            if (Text != null)
            {
                using (ModelEditingScope scope = OwnerActivity.BeginEdit("Property Change"))
                    if (OwnerActivity != null)
                    {
                        EditingState = EditingState.Validating;
                        // we set the expression to null
                        // a) when the expressionText is empty AND it's a reference expression or
                        // b) when the expressionText is empty AND the DefaultValue property is null
                        if (Text.Length == 0 &&
                            (UseLocationExpression || DefaultValue == null))
                        {
                            Expression = null;
                        }
                        else
                        {
                            if (Text.Length == 0)
                            {
                                Text = DefaultValue;
                            }

                            ModelTreeManager   modelTreeManager = Context.Services.GetService <ModelTreeManager>();
                            ActivityWithResult newExpression    = CSharpExpressionHelper.CreateExpressionFromString(Text, UseLocationExpression, resultType);
                            ModelItem          expressionItem   = modelTreeManager.CreateModelItem(null, newExpression);

                            Expression = expressionItem;
                        }
                        scope.Complete();
                    }
            }
        }
        /// <summary>
        /// Fix up activity reference after persistence
        /// </summary>
        /// <param name="activity">The persisted activity reference</param>
        /// <param name="instanceMap">The map containing persisted activity references</param>
        void ActivityInstanceMap.IActivityReference.Load(Activity activity, ActivityInstanceMap instanceMap)
        {
            if (!(activity is ActivityWithResult activityWithResult))
            {
                throw FxTrace.Exception.AsError(
                          new ValidationException(SR.ActivityTypeMismatch(activity.DisplayName, typeof(ActivityWithResult).Name)));
            }

            this.expressionActivity = activityWithResult;
        }
        internal void ValidateEntry(DynamicArgumentWrapperObject entry, DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == DynamicArgumentWrapperObject.NameProperty)
            {
                if (this.IsDictionary.Value)
                {
                    DataGridRow row     = entry.Row;
                    string      newName = e.NewValue as string;

                    bool duplicates =
                        this.DynamicArguments.Any <DynamicArgumentWrapperObject>(
                            p => string.Equals(p.Name, newName) && p != entry);
                    if (duplicates || string.IsNullOrEmpty(newName))
                    {
                        entry.Name = e.OldValue as string;
                        if (duplicates)
                        {
                            ErrorReporting.ShowErrorMessage(string.Format(CultureInfo.CurrentCulture, SR.DuplicateArgumentName, newName));
                        }
                        else
                        {
                            ErrorReporting.ShowErrorMessage(string.Format(CultureInfo.CurrentCulture, SR.EmptyArgumentName));
                        }
                    }
                    entry.IsValidating = false;
                }
            }
            else
            {
                if (e.Property == DynamicArgumentWrapperObject.DirectionProperty)
                {
                    entry.UseLocationExpression = (entry.Direction != ArgumentDirection.In);
                }
                if ((e.Property != DynamicArgumentWrapperObject.ExpressionProperty) && (entry.Expression != null))
                {
                    ActivityWithResult expression = entry.Expression.GetCurrentValue() as ActivityWithResult;
                    if (expression != null)
                    {
                        ActivityWithResult newExpression;
                        if (ExpressionHelper.TryMorphExpression(expression, entry.UseLocationExpression, entry.Type, this.Context, out newExpression))
                        {
                            entry.Expression = (this.OwnerActivity as IModelTreeItem).ModelTreeManager.WrapAsModelItem(newExpression);
                        }
                        else
                        {
                            //Microsoft

                            entry.Expression = null;
                        }
                    }
                }
                entry.IsValidating = false;
            }
        }
        /// <summary>
        /// Release work item back to pool
        /// </summary>
        /// <param name="executor">Executor that owns the work item.</param>
        protected override void ReleaseToPool(ActivityExecutor executor)
        {
            this.ClearForReuse();

            this.expressionActivity   = null;
            this.instanceId           = 0;
            this.resultLocation       = null;
            this.nextArgumentWorkItem = null;

            executor.ExecuteSynchronousExpressionWorkItemPool.Release(this);
        }
            public ExpressionReplacement(ActivityWithResult expressionToReplace, Argument oldArgument, Argument newArgument, ArgumentAccessor argumentAccessor)
            {
                Fx.Assert(expressionToReplace != null, "expressionToReplace cannot be null.");
                Fx.Assert(oldArgument != null, "oldArgument cannot be null.");
                Fx.Assert(newArgument != null, "newArgument cannot be null.");
                Fx.Assert(argumentAccessor != null, "argumentAccessor cannot be null.");

                this.ExpressionToReplace = expressionToReplace;
                this.OldArgument         = oldArgument;
                this.NewArgument         = newArgument;
                this.ArgumentAccessor    = argumentAccessor;
            }
        /// <summary>
        /// Called each time a work item is acquired from the pool
        /// </summary>
        /// <param name="parentInstance">The ActivityInstance containin the variable or argument that contains this expression</param>
        /// <param name="expressionActivity">The expression to evaluate</param>
        /// <param name="instanceId">The ActivityInstanceID to use for expressionActivity</param>
        /// <param name="resultLocation">Location where the result of expressionActivity should be placed</param>
        /// <param name="nextArgumentWorkItem">WorkItem to execute after this one</param>
        public void Initialize(ActivityInstance parentInstance, ActivityWithResult expressionActivity, long instanceId, Location resultLocation, ResolveNextArgumentWorkItem nextArgumentWorkItem)
        {
            this.Reinitialize(parentInstance);

            Fx.Assert(resultLocation != null, "We should only use this work item when we are resolving arguments/variables and therefore have a result location.");
            Fx.Assert(expressionActivity.IsFastPath, "Should only use this work item for fast path expressions");

            this.expressionActivity = expressionActivity;
            this.instanceId = instanceId;
            this.resultLocation = resultLocation;
            this.nextArgumentWorkItem = nextArgumentWorkItem;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Fix up activity reference after persistence
        /// </summary>
        /// <param name="activity">The persisted activity reference</param>
        /// <param name="instanceMap">The map containing persisted activity references</param>
        void ActivityInstanceMap.IActivityReference.Load(Activity activity, ActivityInstanceMap instanceMap)
        {
            ActivityWithResult activityWithResult = activity as ActivityWithResult;

            if (activityWithResult == null)
            {
                throw Microsoft.CoreWf.Internals.FxTrace.Exception.AsError(
                          new ValidationException(SR.ActivityTypeMismatch(activity.DisplayName, typeof(ActivityWithResult).Name)));
            }

            _expressionActivity = activityWithResult;
        }
        /// <summary>
        /// Called each time a work item is acquired from the pool
        /// </summary>
        /// <param name="parentInstance">The ActivityInstance containin the variable or argument that contains this expression</param>
        /// <param name="expressionActivity">The expression to evaluate</param>
        /// <param name="instanceId">The ActivityInstanceID to use for expressionActivity</param>
        /// <param name="resultLocation">Location where the result of expressionActivity should be placed</param>
        /// <param name="nextArgumentWorkItem">WorkItem to execute after this one</param>
        public void Initialize(ActivityInstance parentInstance, ActivityWithResult expressionActivity, long instanceId, Location resultLocation, ResolveNextArgumentWorkItem nextArgumentWorkItem)
        {
            this.Reinitialize(parentInstance);

            Fx.Assert(resultLocation != null, "We should only use this work item when we are resolving arguments/variables and therefore have a result location.");
            Fx.Assert(expressionActivity.IsFastPath, "Should only use this work item for fast path expressions");

            this.expressionActivity   = expressionActivity;
            this.instanceId           = instanceId;
            this.resultLocation       = resultLocation;
            this.nextArgumentWorkItem = nextArgumentWorkItem;
        }
        internal static bool TryMorphExpression(ActivityWithResult originalExpression, bool isLocation, Type targetType,
                                                EditingContext context, out ActivityWithResult morphedExpression)
        {
            bool succeeded = false;

            morphedExpression = null;
            if (originalExpression != null)
            {
                Type resultType = originalExpression.ResultType;
                if ((isLocation) && (ExpressionHelper.IsGenericLocationExpressionType(originalExpression) && (targetType == resultType.GetGenericArguments()[0])) ||
                    (!isLocation) && (resultType == targetType))
                {
                    //no need to morph
                    succeeded         = true;
                    morphedExpression = originalExpression;
                }
                else
                {
                    Type expressionType = originalExpression.GetType();
                    if (expressionType.IsGenericType)
                    {
                        expressionType = expressionType.GetGenericTypeDefinition();
                    }

                    ExpressionMorphHelperAttribute morphHelperAttribute = ExtensibilityAccessor.GetAttribute <ExpressionMorphHelperAttribute>(expressionType);
                    if (morphHelperAttribute != null)
                    {
                        ExpressionMorphHelper morphHelper = Activator.CreateInstance(morphHelperAttribute.ExpressionMorphHelperType) as ExpressionMorphHelper;
                        if (morphHelper != null)
                        {
                            succeeded = morphHelper.TryMorphExpression(originalExpression, isLocation, targetType, context, out morphedExpression);
                            if (succeeded && morphedExpression != null)
                            {
                                string editorName = ExpressionActivityEditor.GetExpressionActivityEditor(originalExpression);
                                if (!string.IsNullOrWhiteSpace(editorName))
                                {
                                    ExpressionActivityEditor.SetExpressionActivityEditor(morphedExpression, editorName);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                succeeded = true;
            }
            return(succeeded);
        }
 private int GetResultId(ActivityWithResult activity)
 {
     if (activity.Result != null)
     {
         return(activity.Result.Id);
     }
     for (int i = 0; i < activity.RuntimeArguments.Count; i++)
     {
         RuntimeArgument argument = activity.RuntimeArguments[i];
         if (argument.IsResult)
         {
             return(argument.Id);
         }
     }
     return(-1);
 }
        private void OnExpressionChanged()
        {
            IsSupportedExpression = true;
            if (Expression == null)
            {
                Text = null;
            }
            else
            {
                // This is a necessary work-around for design-time validation to work properly on Variable/Argument designer. For ETB in Variable/Argument designer,
                // this.Expression is actually a FakeModelItemImpl. For non-editing scenario, when the validation is done, it actually updates the validation related
                // attached properties of the real ModelItem. So if we hook on this.Expression.PropertyChanged directly, we cannot get the property change notification.
                // As the result, the UI of Variable/Argument designer won't be updated when the validation status is changed.

                ActivityWithResult expression = Expression.GetCurrentValue() as ActivityWithResult;
                Text = ExpressionHelper.GetExpressionString(expression);
            }
        }
        internal static ExpressionReplacement ComputeExpressionReplacement(ActivityWithResult expression, Activity parentActivity, EditingContext context, ArgumentAccessorWrapperCache argumentAccessorWrapperCache, Type preferredReturnType = null)
        {
            Fx.Assert(expression != null, "expressions cannot be null.");
            Fx.Assert(parentActivity != null, "parentActivity cannot be null.");
            Fx.Assert(context != null, "context cannot be null.");
            Fx.Assert(argumentAccessorWrapperCache != null, "argumentAccessorWrapperCache cannot be null.");

            IEnumerable <ArgumentAccessorWrapper> argumentAccessorWrappers = argumentAccessorWrapperCache.GetArgumentAccessorWrappers(parentActivity);

            if (argumentAccessorWrappers != null)
            {
                ArgumentAccessorWrapper argumentAccessorWrapper = argumentAccessorWrappers.FirstOrDefault(wrapper => object.ReferenceEquals(wrapper.Argument.Expression, expression));
                if (argumentAccessorWrapper != null)
                {
                    bool isLocationExpression = ExpressionHelper.IsGenericLocationExpressionType(expression);
                    bool canInferType         = true;
                    Type expectedReturnType;
                    ActivityWithResult morphedExpression;
                    if (preferredReturnType != null)
                    {
                        expectedReturnType = preferredReturnType;
                    }
                    else
                    {
                        canInferType = ExpressionHelper.TryInferReturnType(expression, context, out expectedReturnType);
                    }

                    if (canInferType && expectedReturnType != null && ExpressionHelper.TryMorphExpression(expression, isLocationExpression, expectedReturnType, context, out morphedExpression))
                    {
                        Type expressionResultType = isLocationExpression ? expression.ResultType.GetGenericArguments()[0] : expression.ResultType;
                        if (expressionResultType != expectedReturnType)
                        {
                            Argument newArgument = Argument.Create(expectedReturnType, argumentAccessorWrapper.Argument.Direction);
                            newArgument.Expression = morphedExpression;
                            return(new ExpressionReplacement(expression, argumentAccessorWrapper.Argument, newArgument, argumentAccessorWrapper.ArgumentAccessor));
                        }
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 23
0
        protected override void GatherOutputs(ActivityInstance completedInstance)
        {
            int resultId = -1;

            if (completedInstance.Activity.HandlerOf != null)
            {
                DelegateOutArgument resultArgument = completedInstance.Activity.HandlerOf.GetResultArgument();
                if (resultArgument != null)
                {
                    resultId = resultArgument.Id;
                }
                else
                {
                    ActivityWithResult activity = completedInstance.Activity as ActivityWithResult;
                    // for auto-generated results, we should bind the value from the Handler if available
                    if (activity != null && TypeHelper.AreTypesCompatible(activity.ResultType, typeof(T)))
                    {
                        resultId = GetResultId(activity);
                    }
                }
            }
            else
            {
                Fx.Assert(completedInstance.Activity is ActivityWithResult, "should only be using FuncCompletionCallbackWrapper with ActivityFunc and ActivityWithResult");
                resultId = GetResultId((ActivityWithResult)completedInstance.Activity);
            }

            if (resultId >= 0)
            {
                Location     location      = completedInstance.Environment.GetSpecificLocation(resultId);
                Location <T> typedLocation = location as Location <T>;

                if (typedLocation != null)
                {
                    _resultValue = typedLocation.Value;
                }
                else if (location != null)
                {
                    _resultValue = TypeHelper.Convert <T>(location.Value);
                }
            }
        }
Ejemplo n.º 24
0
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string errorMessage = string.Empty;

            if (owner.Expression != value)
            {
                if (value != null)
                {
                    ActivityWithResult expression = (value as ModelItem).GetCurrentValue() as ActivityWithResult;
                    if (expression == null)
                    {
                        errorMessage = string.Format(CultureInfo.CurrentUICulture, SR.ExpressionTypeDonnotMatch,
                                                     expression.GetType().FullName, typeof(ActivityWithResult).FullName);
                    }
                    else if ((owner.UseLocationExpression) && (!ExpressionHelper.IsGenericLocationExpressionType(expression)))
                    {
                        errorMessage = string.Format(CultureInfo.CurrentUICulture, SR.ExpressionTypeDonnotMatch,
                                                     expression.GetType().FullName, typeof(Activity <Location>).FullName);
                    }
                    else if ((!owner.UseLocationExpression && (owner.ExpressionType != null) && (expression.ResultType != owner.ExpressionType)) ||
                             (owner.UseLocationExpression && (owner.ExpressionType != null) && (expression.ResultType != typeof(Location <>).MakeGenericType(owner.ExpressionType))))
                    {
                        errorMessage = string.Format(CultureInfo.CurrentUICulture, SR.ExpressionTypeDonnotMatch,
                                                     expression.GetType().FullName, typeof(Activity <>).MakeGenericType(owner.ExpressionType).FullName);
                    }
                }
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                //Disable ToolTip on inner editor if it has
                ToolTipService.SetIsEnabled(owner.Editor, false);
                owner.ToolTip = errorMessage;
                return(new ValidationResult(false, errorMessage));
            }
            else
            {
                ToolTipService.SetIsEnabled(owner.Editor, true);
                owner.ToolTip = null;
                return(new ValidationResult(true, null));
            }
        }
Ejemplo n.º 25
0
        public static Activity RecompileVisualBasicValue(ActivityWithResult visualBasicValue, out Type returnType, out SourceExpressionException compileError, out VisualBasicSettings vbSettings)
        {
            IVisualBasicExpression expression = visualBasicValue as IVisualBasicExpression;

            if (expression == null)
            {
                throw FxTrace.Exception.AsError(new ArgumentException());
            }
            string expressionText = expression.ExpressionText;
            LocationReferenceEnvironment         parentEnvironment   = visualBasicValue.GetParentEnvironment();
            HashSet <VisualBasicImportReference> allImportReferences = VisualBasicHelper.GetAllImportReferences((parentEnvironment != null) ? parentEnvironment.Root : null);
            HashSet <string> namespaces           = new HashSet <string>();
            HashSet <string> referencedAssemblies = new HashSet <string>();

            foreach (VisualBasicImportReference reference in allImportReferences)
            {
                namespaces.Add(reference.Import);
                referencedAssemblies.Add(reference.Assembly);
            }
            return(CreatePrecompiledVisualBasicValue(null, expressionText, namespaces, referencedAssemblies, parentEnvironment, out returnType, out compileError, out vbSettings));
        }
Ejemplo n.º 26
0
        public override bool TryInferReturnType(ActivityWithResult expression, EditingContext context, out Type returnType)
        {
            bool succeeded = false;

            Fx.Assert(expression.GetType().GetGenericTypeDefinition() == typeof(VisualBasicValue <>) ||
                      expression.GetType().GetGenericTypeDefinition() == typeof(VisualBasicReference <>), "VisualBasicExpressionMorphHelper should only apply to VB expression.");

            SourceExpressionException compileError;
            VisualBasicSettings       settings;

            if (ExpressionHelper.IsGenericLocationExpressionType(expression))
            {
                VisualBasicDesignerHelper.RecompileVisualBasicReference(
                    expression,
                    out returnType,
                    out compileError,
                    out settings);
            }
            else
            {
                VisualBasicDesignerHelper.RecompileVisualBasicValue(
                    expression,
                    out returnType,
                    out compileError,
                    out settings);
            }
            if (compileError == null)
            {
                succeeded = true;
                if (settings != null)
                {
                    //merge with import designer
                    foreach (VisualBasicImportReference reference in settings.ImportReferences)
                    {
                        ImportDesigner.AddImport(reference.Import, context);
                    }
                }
            }
            return(succeeded);
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            Argument          target          = null;
            ArgumentDirection direction       = ArgumentDirection.In;
            string            directionString = parameter as string;

            if (!string.IsNullOrEmpty(directionString))
            {
                direction = (ArgumentDirection)Enum.Parse(typeof(ArgumentDirection), directionString);
            }

            Activity  expression = null;
            ModelItem valueExpressionModelItem = value as ModelItem;

            if (valueExpressionModelItem != null && typeof(Activity).IsAssignableFrom(valueExpressionModelItem.ItemType))
            {
                expression = (Activity)valueExpressionModelItem.GetCurrentValue();
            }
            ActivityWithResult activityWithResult = expression as ActivityWithResult;

            if (expression != null && activityWithResult != null)
            {
                // In the In case the expression is of type Activity<T> so we want to create InArgument<T>
                // In Out and InOut case the expresion is Activity<Location<T>> we want to create OutArgument<T>,InOutArgument<T>
                Type argumentType;
                if (direction == ArgumentDirection.In)
                {
                    argumentType = activityWithResult.ResultType;
                }
                else
                {
                    // if expression type is Location<T> argument type is T
                    argumentType = activityWithResult.ResultType.GetGenericArguments()[0];
                }
                target            = Argument.Create(argumentType, direction);
                target.Expression = activityWithResult;
            }
            return(new object[] { target });
        }
        // this method may has side effect, it may modify model.
        internal static bool TryInferReturnType(ActivityWithResult expression, EditingContext context, out Type returnType)
        {
            bool succeeded = false;

            returnType = null;
            Type expressionType = expression.GetType();

            if (expressionType.IsGenericType)
            {
                expressionType = expressionType.GetGenericTypeDefinition();
                ExpressionMorphHelperAttribute morphHelperAttribute = ExtensibilityAccessor.GetAttribute <ExpressionMorphHelperAttribute>(expressionType);
                if (morphHelperAttribute != null)
                {
                    ExpressionMorphHelper morphHelper = Activator.CreateInstance(morphHelperAttribute.ExpressionMorphHelperType) as ExpressionMorphHelper;
                    if (morphHelper != null)
                    {
                        succeeded = morphHelper.TryInferReturnType(expression, context, out returnType);
                    }
                }
            }
            return(succeeded);
        }
Ejemplo n.º 29
0
        static bool TryEvaluateExpression(
            string expressionString,
            Type locationValueType,                             // Non null for Reference type (location)
            LocationReferenceEnvironment locationReferenceEnvironment,
            CodeActivityContext context,
            out object result)
        {
            expressionString = string.Format(CultureInfo.InvariantCulture, "[{0}]", expressionString);

            Type activityType;

            if (locationValueType != null)
            {
                activityType = typeof(Activity <>).MakeGenericType(typeof(Location <>).MakeGenericType(locationValueType));
            }
            else
            {
                activityType = typeof(Activity <object>);
            }

            // General expression.
            ActivityWithResultConverter converter  = new ActivityWithResultConverter(activityType);
            ActivityWithResult          expression = converter.ConvertFromString(
                new TypeDescriptorContext {
                LocationReferenceEnvironment = locationReferenceEnvironment
            },
                expressionString) as ActivityWithResult;

            if (locationValueType != null)
            {
                Type           locationHelperType = typeof(LocationHelper <>).MakeGenericType(locationValueType);
                LocationHelper helper             = (LocationHelper)Activator.CreateInstance(locationHelperType);
                return(helper.TryGetValue(expression, locationReferenceEnvironment, context, out result));
            }
            else
            {
                return(TryEvaluateExpression(expression, locationReferenceEnvironment, context, out result));
            }
        }
Ejemplo n.º 30
0
        static bool TryEvaluateExpression(
            ActivityWithResult element,
            LocationReferenceEnvironment locationReferenceEnvironment,
            CodeActivityContext context,
            out object result)
        {
            // value is some expression type and needs to be opened
            context.Reinitialize(context.CurrentInstance, context.CurrentExecutor, element, context.CurrentInstance.InternalId);
            if (element != null && !element.IsRuntimeReady)
            {
                WorkflowInspectionServices.CacheMetadata(element, locationReferenceEnvironment);
            }

            if (element == null || !element.IsFastPath)
            {
                result = SR.DebugInfoNotSkipArgumentResolution;
                return(false);
            }

            result = element.InternalExecuteInResolutionContextUntyped(context);
            return(true);
        }
 public override bool TryInferReturnType(ActivityWithResult expression, EditingContext context, out Type returnType)
 {
     bool succeeded = false;
     Fx.Assert(expression.GetType().GetGenericTypeDefinition() == typeof(VisualBasicValue<>) ||
         expression.GetType().GetGenericTypeDefinition() == typeof(VisualBasicReference<>), "VisualBasicExpressionMorphHelper should only apply to VB expression.");
                     
     SourceExpressionException compileError;
     VisualBasicSettings settings;
     if (ExpressionHelper.IsGenericLocationExpressionType(expression))
     {
         VisualBasicDesignerHelper.RecompileVisualBasicReference(
                 expression,
                 out returnType,
                 out compileError,
                 out settings);
     }
     else
     {
         VisualBasicDesignerHelper.RecompileVisualBasicValue(
              expression,
              out returnType,
              out compileError,
              out settings);
     }
     if (compileError == null)
     {
         succeeded = true;                    
         if (settings != null)
         {
             //merge with import designer
             foreach (VisualBasicImportReference reference in settings.ImportReferences)
             {
                 ImportDesigner.AddImport(reference.Import, context);
             }
         }
     }
     return succeeded;
 }
        protected override void GatherOutputs(System.Activities.ActivityInstance completedInstance)
        {
            int id = -1;

            if (completedInstance.Activity.HandlerOf != null)
            {
                DelegateOutArgument resultArgument = completedInstance.Activity.HandlerOf.GetResultArgument();
                if (resultArgument != null)
                {
                    id = resultArgument.Id;
                }
                else
                {
                    ActivityWithResult activity = completedInstance.Activity as ActivityWithResult;
                    if ((activity != null) && TypeHelper.AreTypesCompatible(activity.ResultType, typeof(T)))
                    {
                        id = this.GetResultId(activity);
                    }
                }
            }
            else
            {
                id = this.GetResultId((ActivityWithResult)completedInstance.Activity);
            }
            if (id >= 0)
            {
                System.Activities.Location specificLocation = completedInstance.Environment.GetSpecificLocation(id);
                Location <T> location2 = specificLocation as Location <T>;
                if (location2 != null)
                {
                    this.resultValue = location2.Value;
                }
                else if (specificLocation != null)
                {
                    this.resultValue = TypeHelper.Convert <T>(specificLocation.Value);
                }
            }
        }
 // Recompile the VBReference passed in, with its current LocationReferenceEnvironment context
 // in a weakly-typed manner (the argument VBReference's type argument is ignored)
 //[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters,
 //    Justification = "Design has been approved")]
 public static Activity RecompileVisualBasicReference(ActivityWithResult visualBasicReference, out Type returnType, out SourceExpressionException compileError, out VisualBasicSettings vbSettings) =>
 Impl.RecompileReference(visualBasicReference, out returnType, out compileError, out vbSettings);
Ejemplo n.º 34
0
        static bool TryEvaluateExpression(
            ActivityWithResult element,
            LocationReferenceEnvironment locationReferenceEnvironment,
            CodeActivityContext context,
            out object result)
        {
            // value is some expression type and needs to be opened
            context.Reinitialize(context.CurrentInstance, context.CurrentExecutor, element, context.CurrentInstance.InternalId);
            if (element != null && !element.IsRuntimeReady)
            {
                WorkflowInspectionServices.CacheMetadata(element, locationReferenceEnvironment);
            }

            if (element == null || !element.IsFastPath)
            {
                result = SR.DebugInfoNotSkipArgumentResolution;
                return false;
            }

            result = element.InternalExecuteInResolutionContextUntyped(context);
            return true;
        }
        /// <summary>
        /// Fix up activity reference after persistence
        /// </summary>
        /// <param name="activity">The persisted activity reference</param>
        /// <param name="instanceMap">The map containing persisted activity references</param>
        void ActivityInstanceMap.IActivityReference.Load(Activity activity, ActivityInstanceMap instanceMap)
        {
            ActivityWithResult activityWithResult = activity as ActivityWithResult;
            if (activityWithResult == null)
            {
                throw FxTrace.Exception.AsError(
                    new ValidationException(SR.ActivityTypeMismatch(activity.DisplayName, typeof(ActivityWithResult).Name)));
            }

            this.expressionActivity = activityWithResult;
        }
        internal static ExpressionReplacement ComputeExpressionReplacement(ActivityWithResult expression, Activity parentActivity, EditingContext context, ArgumentAccessorWrapperCache argumentAccessorWrapperCache, Type preferredReturnType = null)
        {
            Fx.Assert(expression != null, "expressions cannot be null.");
            Fx.Assert(parentActivity != null, "parentActivity cannot be null.");
            Fx.Assert(context != null, "context cannot be null.");
            Fx.Assert(argumentAccessorWrapperCache != null, "argumentAccessorWrapperCache cannot be null.");

            IEnumerable<ArgumentAccessorWrapper> argumentAccessorWrappers = argumentAccessorWrapperCache.GetArgumentAccessorWrappers(parentActivity);
            if (argumentAccessorWrappers != null)
            {
                ArgumentAccessorWrapper argumentAccessorWrapper = argumentAccessorWrappers.FirstOrDefault(wrapper => object.ReferenceEquals(wrapper.Argument.Expression, expression));
                if (argumentAccessorWrapper != null)
                {
                    bool isLocationExpression = ExpressionHelper.IsGenericLocationExpressionType(expression);
                    bool canInferType = true;
                    Type expectedReturnType;
                    ActivityWithResult morphedExpression;
                    if (preferredReturnType != null)
                    {
                        expectedReturnType = preferredReturnType;
                    }
                    else
                    {
                        canInferType = ExpressionHelper.TryInferReturnType(expression, context, out expectedReturnType);
                    }

                    if (canInferType && expectedReturnType != null && ExpressionHelper.TryMorphExpression(expression, isLocationExpression, expectedReturnType, context, out morphedExpression))
                    {
                        Type expressionResultType = isLocationExpression ? expression.ResultType.GetGenericArguments()[0] : expression.ResultType;
                        if (expressionResultType != expectedReturnType)
                        {
                            Argument newArgument = Argument.Create(expectedReturnType, argumentAccessorWrapper.Argument.Direction);
                            newArgument.Expression = morphedExpression;
                            return new ExpressionReplacement(expression, argumentAccessorWrapper.Argument, newArgument, argumentAccessorWrapper.ArgumentAccessor);
                        }
                    }
                }
            }

            return null;
        }
 public abstract bool TryMorphExpression(ActivityWithResult expression, bool isLocationExpression, Type newType, 
     EditingContext context, out ActivityWithResult newExpression);
 //By default expression cannot infer the type.
 public virtual bool TryInferReturnType(ActivityWithResult expression, EditingContext context, out Type returnType)
 {
     returnType = null;
     return false;
 }        
Ejemplo n.º 39
0
        internal static bool TryMorphExpression(ActivityWithResult originalExpression, bool isLocation, Type targetType, 
            EditingContext context, out ActivityWithResult morphedExpression)
        {
            bool succeeded = false;            
            morphedExpression = null;
            if (originalExpression != null)
            {
                Type resultType = originalExpression.ResultType;
                if ((isLocation) && (ExpressionHelper.IsGenericLocationExpressionType(originalExpression) && (targetType == resultType.GetGenericArguments()[0])) ||
                    (!isLocation) && (resultType == targetType))
                {
                    //no need to morph
                    succeeded = true;
                    morphedExpression = originalExpression;
                }
                else
                {
                    Type expressionType = originalExpression.GetType();
                    if (expressionType.IsGenericType)
                    {
                        expressionType = expressionType.GetGenericTypeDefinition();
                    }

                    ExpressionMorphHelperAttribute morphHelperAttribute = ExtensibilityAccessor.GetAttribute<ExpressionMorphHelperAttribute>(expressionType);
                    if (morphHelperAttribute != null)
                    {
                        ExpressionMorphHelper morphHelper = Activator.CreateInstance(morphHelperAttribute.ExpressionMorphHelperType) as ExpressionMorphHelper;
                        if (morphHelper != null)
                        {
                            succeeded = morphHelper.TryMorphExpression(originalExpression, isLocation, targetType, context, out morphedExpression);
                            if (succeeded && morphedExpression != null)
                            {
                                string editorName = ExpressionActivityEditor.GetExpressionActivityEditor(originalExpression);
                                if (!string.IsNullOrWhiteSpace(editorName))
                                {
                                    ExpressionActivityEditor.SetExpressionActivityEditor(morphedExpression, editorName);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                succeeded = true;
            }
            return succeeded;
        }
Ejemplo n.º 40
0
 internal static bool TryConvertString(string targetEditor, string expressionText, bool isLocationExpression, Type resultType, out ActivityWithResult expression)
 {
     expression = null;
     if (targetEditor != null)
     {
         CreateExpressionFromStringCallback convertFromStringAction;
         if (ConvertFromStringDelegates.TryGetValue(targetEditor, out convertFromStringAction))
         {
             if (convertFromStringAction != null)
             {
                 expression = convertFromStringAction(expressionText, isLocationExpression, resultType);
                 return true;
             }
         }
     }
     return false;
 }
        internal static bool IsGenericLocationExpressionType(ActivityWithResult expression)
        {
            Type expressionType = expression.ResultType;

            return(expressionType.IsGenericType && typeof(Location <>) == expressionType.GetGenericTypeDefinition());
        }
        /// <summary>
        /// Release work item back to pool
        /// </summary>
        /// <param name="executor">Executor that owns the work item.</param>
        protected override void ReleaseToPool(ActivityExecutor executor)
        {
            this.ClearForReuse();

            this.expressionActivity = null;
            this.instanceId = 0;
            this.resultLocation = null;
            this.nextArgumentWorkItem = null;

            executor.ExecuteSynchronousExpressionWorkItemPool.Release(this);
        }
Ejemplo n.º 43
0
 internal static bool IsGenericLocationExpressionType(ActivityWithResult expression)
 {
     Type expressionType = expression.ResultType;
     return expressionType.IsGenericType && typeof(Location<>) == expressionType.GetGenericTypeDefinition();
 }
            public ExpressionReplacement(ActivityWithResult expressionToReplace, Argument oldArgument, Argument newArgument, ArgumentAccessor argumentAccessor)
            {
                Fx.Assert(expressionToReplace != null, "expressionToReplace cannot be null.");
                Fx.Assert(oldArgument != null, "oldArgument cannot be null.");
                Fx.Assert(newArgument != null, "newArgument cannot be null.");
                Fx.Assert(argumentAccessor != null, "argumentAccessor cannot be null.");

                this.ExpressionToReplace = expressionToReplace;
                this.OldArgument = oldArgument;
                this.NewArgument = newArgument;
                this.ArgumentAccessor = argumentAccessor;
            }
Ejemplo n.º 45
0
 // this method may has side effect, it may modify model.
 internal static bool TryInferReturnType(ActivityWithResult expression, EditingContext context, out Type returnType)
 {
     bool succeeded = false;
     returnType = null;
     Type expressionType = expression.GetType();
     if (expressionType.IsGenericType)
     {
         expressionType = expressionType.GetGenericTypeDefinition();
         ExpressionMorphHelperAttribute morphHelperAttribute = ExtensibilityAccessor.GetAttribute<ExpressionMorphHelperAttribute>(expressionType);
         if (morphHelperAttribute != null)
         {
             ExpressionMorphHelper morphHelper = Activator.CreateInstance(morphHelperAttribute.ExpressionMorphHelperType) as ExpressionMorphHelper;
             if (morphHelper != null)
             {
                 succeeded = morphHelper.TryInferReturnType(expression, context, out returnType);
             }
         }
     }
     return succeeded;   
 }
Ejemplo n.º 46
0
 internal static bool TryConvertFromString(string targetEditor, string expressionText, bool isLocationExpression, Type resultType, out ActivityWithResult expression)
 {
     return ExpressionTextBoxViewModel.TryConvertString(targetEditor, expressionText, isLocationExpression, resultType, out expression);
 }