Exemple #1
0
        public void Add(string key, object value, Type type)
        {
            if (type == null)
            {
                throw FxTrace.Exception.ArgumentNull(nameof(type));
            }

            if (!TypeHelper.AreTypesCompatible(value, type))
            {
                throw FxTrace.Exception.Argument(nameof(value), SR.ValueMustBeAssignableToType);
            }

            // We don't need to check key for null since we want the exception to bubble up from the inner dictionary
            this.symbols.Add(key, new ExternalLocationReference(key, type, value));
        }
        internal void SetValueCore <T>(LocationReference locationReference, T value)
        {
            System.Activities.Location location = locationReference.GetLocation(this);
            Location <T> location2 = location as Location <T>;

            if (location2 != null)
            {
                location2.Value = value;
            }
            else
            {
                if (!TypeHelper.AreTypesCompatible(value, locationReference.Type))
                {
                    throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.CannotSetValueToLocation((value != null) ? value.GetType() : typeof(T), locationReference.Name, locationReference.Type)));
                }
                location.Value = value;
            }
        }
Exemple #3
0
        protected object[] EvaluateAndPackParameters(CodeActivityContext context, MethodInfo method,
                                                     bool usingAsyncPattern)
        {
            ParameterInfo[] formalParameters = method.GetParameters();
            int             formalParamCount = formalParameters.Length;

            object[] actualParameters = new object[formalParamCount];

            if (usingAsyncPattern)
            {
                formalParamCount -= 2;
            }

            bool haveParameterArray = HaveParameterArray(formalParameters);

            for (int i = 0; i < formalParamCount; i++)
            {
                if (i == formalParamCount - 1 && !usingAsyncPattern && haveParameterArray)
                {
                    int paramArrayCount = this.parameters.Count - formalParamCount + 1;

                    // If params are given explicitly, that's okay.
                    if (paramArrayCount == 1 && TypeHelper.AreTypesCompatible(this.parameters[i].ArgumentType,
                                                                              formalParameters[i].ParameterType))
                    {
                        actualParameters[i] = this.parameters[i].Get <object>(context);
                    }
                    else
                    {
                        // Otherwise, pack them into an array for the reflection call.
                        actualParameters[i] =
                            Activator.CreateInstance(formalParameters[i].ParameterType, paramArrayCount);
                        for (int j = 0; j < paramArrayCount; j++)
                        {
                            ((object[])actualParameters[i])[j] = this.parameters[i + j].Get <object>(context);
                        }
                    }
                    continue;
                }
                actualParameters[i] = parameters[i].Get <object>(context);
            }

            return(actualParameters);
        }
Exemple #4
0
        /// <summary>
        /// Sets the value core.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="locationReference">The location reference.</param>
        /// <param name="value">The value.</param>
        /// <exception cref="InvalidOperationException"></exception>
        internal void SetValueCore <T>(LocationReference locationReference, T value)
        {
            var location = locationReference.GetLocationForWrite(this);

            if (location is Location <T> typedLocation)
            {
                // If we hit this path we can avoid boxing value types
                typedLocation.Value = value;
            }
            else
            {
                if (!TypeHelper.AreTypesCompatible(value, locationReference.Type))
                {
                    throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CannotSetValueToLocation(value != null ? value.GetType() : typeof(T), locationReference.Name, locationReference.Type)));
                }

                location.Value = value;
            }
        }
Exemple #5
0
        protected override void CacheMetadata(CodeActivityMetadata metadata)
        {
            var arguments = new Collection <RuntimeArgument>();

            var valueType = TypeHelper.ObjectType;

            if (this.Value != null)
            {
                valueType = this.Value.ArgumentType;
            }

            var valueArgument = new RuntimeArgument("Value", valueType, ArgumentDirection.In, true);

            metadata.Bind(this.Value, valueArgument);

            var toType = TypeHelper.ObjectType;

            if (this.To != null)
            {
                toType = this.To.ArgumentType;
            }

            var toArgument = new RuntimeArgument("To", toType, ArgumentDirection.Out, true);

            metadata.Bind(this.To, toArgument);

            arguments.Add(valueArgument);
            arguments.Add(toArgument);

            metadata.SetArgumentsCollection(arguments);

            if (this.Value != null && this.To != null)
            {
                if (!TypeHelper.AreTypesCompatible(this.Value.ArgumentType, this.To.ArgumentType))
                {
                    metadata.AddValidationError(SR.TypeMismatchForAssign(
                                                    this.Value.ArgumentType,
                                                    this.To.ArgumentType,
                                                    this.DisplayName));
                }
            }
        }
Exemple #6
0
        protected override Location <TItem> Execute(CodeActivityContext context)
        {
            System.Array array = this.Array.Get(context);
            if (array == null)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.MemberCannotBeNull("Array", base.GetType().Name, base.DisplayName)));
            }
            Type elementType = array.GetType().GetElementType();

            if (!TypeHelper.AreTypesCompatible(typeof(TItem), elementType))
            {
                throw FxTrace.Exception.AsError(new InvalidCastException(System.Activities.SR.IncompatibleTypeForMultidimensionalArrayItemReference(typeof(TItem).Name, elementType.Name)));
            }
            int[] indices = new int[this.Indices.Count];
            for (int i = 0; i < this.Indices.Count; i++)
            {
                indices[i] = this.Indices[i].Get(context);
            }
            return(new MultidimensionArrayLocation <TItem>(array, indices));
        }
 protected override void CacheMetadata(CodeActivityMetadata metadata)
 {
     this.targetArgument = null;
     if (string.IsNullOrEmpty(this.ArgumentName))
     {
         metadata.AddValidationError(System.Activities.SR.ArgumentNameRequired);
     }
     else
     {
         this.targetArgument = ActivityUtilities.FindArgument(this.ArgumentName, this);
         if (this.targetArgument == null)
         {
             metadata.AddValidationError(System.Activities.SR.ArgumentNotFound(this.ArgumentName));
         }
         else if (!TypeHelper.AreTypesCompatible(this.targetArgument.Type, typeof(T)))
         {
             metadata.AddValidationError(System.Activities.SR.ArgumentTypeMustBeCompatible(this.ArgumentName, this.targetArgument.Type, typeof(T)));
         }
     }
 }
        public static Activity <TResult> FromVariable(Variable variable)
        {
            Type type;

            if (variable == null)
            {
                throw FxTrace.Exception.ArgumentNull("variable");
            }
            if (TypeHelper.AreTypesCompatible(variable.Type, typeof(TResult)))
            {
                return(new VariableValue <TResult> {
                    Variable = variable
                });
            }
            if (!ActivityUtilities.IsLocationGenericType(typeof(TResult), out type) || (type != variable.Type))
            {
                throw FxTrace.Exception.Argument("variable", System.Activities.SR.ConvertVariableToValueExpressionFailed(variable.GetType().FullName, typeof(Activity <TResult>).FullName));
            }
            return((Activity <TResult>)ActivityUtilities.CreateVariableReference(variable));
        }
Exemple #9
0
        protected override void CacheMetadata(CodeActivityMetadata metadata)
        {
            bool isRequired = false;

            if (typeof(TOperand).IsEnum)
            {
                metadata.AddValidationError(System.Activities.SR.TargetTypeCannotBeEnum(base.GetType().Name, base.DisplayName));
            }
            else if (typeof(TOperand).IsValueType)
            {
                metadata.AddValidationError(System.Activities.SR.TargetTypeIsValueType(base.GetType().Name, base.DisplayName));
            }
            if (string.IsNullOrEmpty(this.PropertyName))
            {
                metadata.AddValidationError(System.Activities.SR.ActivityPropertyMustBeSet("PropertyName", base.DisplayName));
            }
            else
            {
                this.propertyInfo = typeof(TOperand).GetProperty(this.PropertyName);
                if (this.propertyInfo == null)
                {
                    metadata.AddValidationError(System.Activities.SR.MemberNotFound(this.PropertyName, typeof(TOperand).Name));
                }
                else
                {
                    MethodInfo getMethod = this.propertyInfo.GetGetMethod();
                    MethodInfo setMethod = this.propertyInfo.GetSetMethod();
                    if ((setMethod == null) && !TypeHelper.AreTypesCompatible(this.propertyInfo.DeclaringType, typeof(System.Activities.Location)))
                    {
                        metadata.AddValidationError(System.Activities.SR.ReadonlyPropertyCannotBeSet(this.propertyInfo.DeclaringType, this.propertyInfo.Name));
                    }
                    if (((getMethod != null) && !getMethod.IsStatic) || ((setMethod != null) && !setMethod.IsStatic))
                    {
                        isRequired = true;
                    }
                }
            }
            MemberExpressionHelper.AddOperandArgument <TOperand>(metadata, this.Operand, isRequired);
        }
        protected override Location <TItem> Execute(CodeActivityContext context)
        {
            Array items = this.Array.Get(context);

            if (items == null)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.MemberCannotBeNull("Array", this.GetType().Name, this.DisplayName)));
            }

            Type realItemType = items.GetType().GetElementType();

            if (!TypeHelper.AreTypesCompatible(typeof(TItem), realItemType))
            {
                throw FxTrace.Exception.AsError(new InvalidCastException(SR.IncompatibleTypeForMultidimensionalArrayItemReference(typeof(TItem).Name, realItemType.Name)));
            }
            int[] itemIndex = new int[this.Indices.Count];
            for (int i = 0; i < this.Indices.Count; i++)
            {
                itemIndex[i] = this.Indices[i].Get(context);
            }
            return(new MultidimensionArrayLocation(items, itemIndex));
        }
 protected override void CacheMetadata(CodeActivityMetadata metadata)
 {
     if (this.Variable == null)
     {
         metadata.AddValidationError(System.Activities.SR.VariableMustBeSet);
     }
     else
     {
         if (!(this.Variable is Variable <T>) && !TypeHelper.AreTypesCompatible(this.Variable.Type, typeof(T)))
         {
             metadata.AddValidationError(System.Activities.SR.VariableTypeInvalid(this.Variable, typeof(T), this.Variable.Type));
         }
         if (!this.Variable.IsInTree)
         {
             metadata.AddValidationError(System.Activities.SR.VariableShouldBeOpen(this.Variable.Name));
         }
         if (!metadata.Environment.IsVisible(this.Variable))
         {
             metadata.AddValidationError(System.Activities.SR.VariableNotVisible(this.Variable.Name));
         }
     }
 }
 protected override void CacheMetadata(CodeActivityMetadata metadata)
 {
     if (this.DelegateArgument == null)
     {
         metadata.AddValidationError(System.Activities.SR.DelegateArgumentMustBeSet);
     }
     else
     {
         if (!this.DelegateArgument.IsInTree)
         {
             metadata.AddValidationError(System.Activities.SR.DelegateArgumentMustBeReferenced(this.DelegateArgument.Name));
         }
         if (!metadata.Environment.IsVisible(this.DelegateArgument))
         {
             metadata.AddValidationError(System.Activities.SR.DelegateArgumentNotVisible(this.DelegateArgument.Name));
         }
         if (!(this.DelegateArgument is DelegateInArgument <T>) && !TypeHelper.AreTypesCompatible(this.DelegateArgument.Type, typeof(T)))
         {
             metadata.AddValidationError(System.Activities.SR.DelegateArgumentTypeInvalid(this.DelegateArgument, typeof(T), this.DelegateArgument.Type));
         }
     }
 }
Exemple #13
0
        protected object[] EvaluateAndPackParameters(CodeActivityContext context, MethodInfo method, bool usingAsyncPattern)
        {
            ParameterInfo[] parameters = method.GetParameters();
            int             length     = parameters.Length;

            object[] objArray = new object[length];
            if (usingAsyncPattern)
            {
                length -= 2;
            }
            bool flag = HaveParameterArray(parameters);

            for (int i = 0; i < length; i++)
            {
                if (((i == (length - 1)) && !usingAsyncPattern) && flag)
                {
                    int num3 = (this.parameters.Count - length) + 1;
                    if ((num3 == 1) && TypeHelper.AreTypesCompatible(this.parameters[i].ArgumentType, parameters[i].ParameterType))
                    {
                        objArray[i] = this.parameters[i].Get <object>(context);
                    }
                    else
                    {
                        objArray[i] = Activator.CreateInstance(parameters[i].ParameterType, new object[] { num3 });
                        for (int j = 0; j < num3; j++)
                        {
                            ((object[])objArray[i])[j] = this.parameters[i + j].Get <object>(context);
                        }
                    }
                }
                else
                {
                    objArray[i] = this.parameters[i].Get <object>(context);
                }
            }
            return(objArray);
        }
 public static bool IsActivityDelegateType(Type propertyType)
 {
     return(TypeHelper.AreTypesCompatible(propertyType, activityDelegateType));
 }
        // Set methodExecutor, returning an error string if there are any problems (ambiguous match, etc.).
        public void DetermineMethodInfo(CodeActivityMetadata metadata, MruCache <MethodInfo, Func <object, object[], object> > funcCache, ReaderWriterLockSlim locker,
                                        ref MethodExecutor methodExecutor)
        {
            bool returnEarly = false;

            MethodExecutor oldMethodExecutor = methodExecutor;

            methodExecutor = null;
            if (string.IsNullOrEmpty(this.MethodName))
            {
                metadata.AddValidationError(SR.ActivityPropertyMustBeSet("MethodName", this.Parent.DisplayName));
                returnEarly = true;
            }

            Type targetType = this.TargetType;

            // If TargetType and the type of TargetObject are both set, it's an error.
            if (targetType != null && this.TargetObject != null && !this.TargetObject.IsEmpty)
            {
                metadata.AddValidationError(SR.TargetTypeAndTargetObjectAreMutuallyExclusive(this.Parent.GetType().Name, this.Parent.DisplayName));
                returnEarly = true;
            }

            // If TargetType was set, look for a static method. If TargetObject was set, look for an instance method. They can't both be set.
            BindingFlags bindingFlags = this.TargetType != null ? staticBindingFlags : instanceBindingFlags;
            string       bindingType  = bindingFlags == staticBindingFlags ? staticString : instanceString;

            if (targetType == null)
            {
                if (this.TargetObject != null && !this.TargetObject.IsEmpty)
                {
                    targetType = this.TargetObject.ArgumentType;
                }
                else
                {
                    metadata.AddValidationError(SR.OneOfTwoPropertiesMustBeSet("TargetObject", "TargetType", this.Parent.GetType().Name, this.Parent.DisplayName));
                    returnEarly = true;
                }
            }

            // We've had one or more constraint violations already
            if (returnEarly)
            {
                return;
            }

            // Convert OutArgs and InOutArgs to out/ref types before resolution
            Type[] parameterTypes =
                Parameters.Select(argument => argument.Direction == ArgumentDirection.In ? argument.ArgumentType : argument.ArgumentType.MakeByRefType())
                .ToArray();

            Type[] genericTypeArguments = this.GenericTypeArguments.ToArray();

            InheritanceAndParamArrayAwareBinder methodBinder = new InheritanceAndParamArrayAwareBinder(targetType, genericTypeArguments, this.Parent);

            // It may be possible to know (and check) the resultType even if the result won't be assigned anywhere.
            // Used 1.) for detecting async pattern, and 2.) to make sure we selected the correct MethodInfo.
            Type resultType = this.ResultType;

            if (this.RunAsynchronously)
            {
                int    formalParamCount          = parameterTypes.Length;
                Type[] beginMethodParameterTypes = new Type[formalParamCount + 2];
                for (int i = 0; i < formalParamCount; i++)
                {
                    beginMethodParameterTypes[i] = parameterTypes[i];
                }
                beginMethodParameterTypes[formalParamCount]     = typeof(AsyncCallback);
                beginMethodParameterTypes[formalParamCount + 1] = typeof(object);

                Type[] endMethodParameterTypes = { typeof(IAsyncResult) };

                this.beginMethod = Resolve(targetType, "Begin" + this.MethodName, bindingFlags,
                                           methodBinder, beginMethodParameterTypes, genericTypeArguments, true);
                if (this.beginMethod != null && !this.beginMethod.ReturnType.Equals(typeof(IAsyncResult)))
                {
                    this.beginMethod = null;
                }
                this.endMethod = Resolve(targetType, "End" + this.MethodName, bindingFlags,
                                         methodBinder, endMethodParameterTypes, genericTypeArguments, true);
                if (this.endMethod != null && resultType != null && !TypeHelper.AreTypesCompatible(this.endMethod.ReturnType, resultType))
                {
                    metadata.AddValidationError(SR.ReturnTypeIncompatible(this.endMethod.ReturnType.Name, MethodName, targetType.Name, this.Parent.DisplayName, resultType.Name));
                    this.endMethod = null;
                    return;
                }

                if (this.beginMethod != null && this.endMethod != null && this.beginMethod.IsStatic == this.endMethod.IsStatic)
                {
                    if (!(oldMethodExecutor is AsyncPatternMethodExecutor) ||
                        !((AsyncPatternMethodExecutor)oldMethodExecutor).IsTheSame(this.beginMethod, this.endMethod))
                    {
                        methodExecutor = new AsyncPatternMethodExecutor(metadata, this.beginMethod, this.endMethod, this.Parent,
                                                                        this.TargetType, this.TargetObject, this.Parameters, this.Result, funcCache, locker);
                    }
                    else
                    {
                        methodExecutor = new AsyncPatternMethodExecutor((AsyncPatternMethodExecutor)oldMethodExecutor,
                                                                        this.TargetType, this.TargetObject, this.Parameters, this.Result);
                    }
                    return;
                }
            }

            MethodInfo result;

            try
            {
                result = Resolve(targetType, this.MethodName, bindingFlags,
                                 methodBinder, parameterTypes, genericTypeArguments, false);
            }
            catch (AmbiguousMatchException)
            {
                metadata.AddValidationError(SR.DuplicateMethodFound(targetType.Name, bindingType, MethodName, this.Parent.DisplayName));
                return;
            }

            if (result == null)
            {
                metadata.AddValidationError(SR.PublicMethodWithMatchingParameterDoesNotExist(targetType.Name, bindingType, MethodName, this.Parent.DisplayName));
                return;
            }
            else if (resultType != null && !TypeHelper.AreTypesCompatible(result.ReturnType, resultType))
            {
                metadata.AddValidationError(
                    SR.ReturnTypeIncompatible(result.ReturnType.Name, MethodName,
                                              targetType.Name, this.Parent.DisplayName, resultType.Name));
                return;
            }
            else
            {
                this.syncMethod = result;
                if (this.RunAsynchronously)
                {
                    if (!(oldMethodExecutor is AsyncWaitCallbackMethodExecutor) ||
                        !((AsyncWaitCallbackMethodExecutor)oldMethodExecutor).IsTheSame(this.syncMethod))
                    {
                        methodExecutor = new AsyncWaitCallbackMethodExecutor(metadata, this.syncMethod, this.Parent,
                                                                             this.TargetType, this.TargetObject, this.Parameters, this.Result, funcCache, locker);
                    }
                    else
                    {
                        methodExecutor = new AsyncWaitCallbackMethodExecutor((AsyncWaitCallbackMethodExecutor)oldMethodExecutor,
                                                                             this.TargetType, this.TargetObject, this.Parameters, this.Result);
                    }
                }
                else if (!(oldMethodExecutor is SyncMethodExecutor) ||
                         !((SyncMethodExecutor)oldMethodExecutor).IsTheSame(this.syncMethod))
                {
                    methodExecutor = new SyncMethodExecutor(metadata, this.syncMethod, this.Parent, this.TargetType,
                                                            this.TargetObject, this.Parameters, this.Result, funcCache, locker);
                }
                else
                {
                    methodExecutor = new SyncMethodExecutor((SyncMethodExecutor)oldMethodExecutor, this.TargetType,
                                                            this.TargetObject, this.Parameters, this.Result);
                }
            }
        }
            private readonly LocationHelper locationHelper; // true if we're dealing with a Location

            public ExpressionConverterHelper()
                : this(TypeHelper.AreTypesCompatible(typeof(T), typeof(Location)))
            {
            }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            WorkflowServiceHost serviceHost = null;

            if (string.IsNullOrEmpty(constructorString))
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.WorkflowServiceHostFactoryConstructorStringNotProvided));
            }

            if (baseAddresses == null)
            {
                throw FxTrace.Exception.ArgumentNull("baseAddresses");
            }

            if (baseAddresses.Length == 0)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BaseAddressesNotProvided));
            }

            if (!HostingEnvironment.IsHosted)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Hosting_ProcessNotExecutingUnderHostedContext("WorkflowServiceHostFactory.CreateServiceHost")));
            }

            // We expect most users will use .xamlx file instead of precompiled assembly
            // Samples of xamlVirtualPath under all scenarios
            //                          constructorString  XamlFileBaseLocation    xamlVirtualPath
            // 1. Xamlx direct          ~/sub/a.xamlx      ~/sub/                  ~/sub/a.xamlx
            // 2. CBA with precompiled  servicetypeinfo    ~/sub/servicetypeinfo   ~/sub/servicetypeinfo  * no file will be found
            // 3. CBA with xamlx        sub/a.xamlx        ~/                      ~/sub/a.xamlx
            // 4. Svc with precompiled  servicetypeinfo    ~/sub/servicetypeinfo   ~/sub/servicetypeinfo  * no file will be found
            // 5. Svc with Xamlx        ../a.xamlx         ~/sub/                  ~/a.xamlx

            string xamlVirtualPath = VirtualPathUtility.Combine(AspNetEnvironment.Current.XamlFileBaseLocation, constructorString);
            Stream activityStream;
            string compiledCustomString;

            if (GetServiceFileStreamOrCompiledCustomString(xamlVirtualPath, baseAddresses, out activityStream, out compiledCustomString))
            {
                //

                BuildManager.GetReferencedAssemblies();
                //XmlnsMappingHelper.EnsureMappingPassed();

                this.xamlVirtualFile = xamlVirtualPath;

                WorkflowService service;
                using (activityStream)
                {
                    string serviceName      = VirtualPathUtility.GetFileName(xamlVirtualPath);
                    string serviceNamespace = String.Format(CultureInfo.InvariantCulture, "/{0}{1}", ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath));

                    service = CreatetWorkflowServiceAndSetCompiledExpressionRoot(null, activityStream, XName.Get(XmlConvert.EncodeLocalName(serviceName), serviceNamespace));
                }

                if (service != null)
                {
                    serviceHost = CreateWorkflowServiceHost(service, baseAddresses);
                }
            }
            else
            {
                Type activityType = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
                if (null == activityType)
                {
                    activityType = GetTypeFromCompileCustomString(compiledCustomString, constructorString);
                }
                if (null == activityType)
                {
                    //for file-less cases, try in referenced assemblies as CompileCustomString assemblies are empty.
                    BuildManager.GetReferencedAssemblies();
                    activityType = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
                }
                if (null != activityType)
                {
                    if (!TypeHelper.AreTypesCompatible(activityType, typeof(Activity)))
                    {
                        throw FxTrace.Exception.AsError(new InvalidOperationException(SR.TypeNotActivity(activityType.FullName)));
                    }

                    Activity activity = (Activity)Activator.CreateInstance(activityType);
                    serviceHost = CreateWorkflowServiceHost(activity, baseAddresses);
                }
            }
            if (serviceHost == null)
            {
                throw FxTrace.Exception.AsError(
                          new InvalidOperationException(SR.CannotResolveConstructorStringToWorkflowType(constructorString)));
            }

            //The Description.Name and Description.NameSpace aren't included intentionally - because
            //in farm scenarios the sole and unique identifier is the service deployment URL
            ((IDurableInstancingOptions)serviceHost.DurableInstancingOptions).SetScopeName(
                XName.Get(XmlConvert.EncodeLocalName(VirtualPathUtility.GetFileName(ServiceHostingEnvironment.FullVirtualPath)),
                          String.Format(CultureInfo.InvariantCulture, "/{0}{1}", ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath))));

            return(serviceHost);
        }
Exemple #18
0
        internal static void ValidateRootInputs(Activity rootActivity, IDictionary <string, object> inputs)
        {
            IList <ValidationError> validationErrors = null;

            ValidationHelper.ValidateArguments(rootActivity, rootActivity.EquivalenceInfo, rootActivity.OverloadGroups, rootActivity.RequiredArgumentsNotInOverloadGroups, inputs, ref validationErrors);

            // Validate if there are any extra arguments passed in the input dictionary
            if (inputs != null)
            {
                List <string> unusedArguments           = null;
                IEnumerable <RuntimeArgument> arguments = rootActivity.RuntimeArguments.Where((a) => ArgumentDirectionHelper.IsIn(a.Direction));

                foreach (string key in inputs.Keys)
                {
                    bool found = false;
                    foreach (RuntimeArgument argument in arguments)
                    {
                        if (argument.Name == key)
                        {
                            found = true;

                            // Validate if the input argument type matches the expected argument type.
                            if (inputs.TryGetValue(key, out object inputArgumentValue))
                            {
                                if (!TypeHelper.AreTypesCompatible(inputArgumentValue, argument.Type))
                                {
                                    ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.InputParametersTypeMismatch(argument.Type, argument.Name), rootActivity));
                                }
                            }
                            // The ValidateArguments will validate Required in-args and hence not duplicating that validation if the key is not found.

                            break;
                        }
                    }

                    if (!found)
                    {
                        if (unusedArguments == null)
                        {
                            unusedArguments = new List <string>();
                        }
                        unusedArguments.Add(key);
                    }
                }
                if (unusedArguments != null)
                {
                    ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.UnusedInputArguments(unusedArguments.AsCommaSeparatedValues()), rootActivity));
                }
            }

            if (validationErrors != null && validationErrors.Count > 0)
            {
                string          parameterName = "rootArgumentValues";
                ExceptionReason reason        = ExceptionReason.InvalidNonNullInputs;

                if (inputs == null)
                {
                    parameterName = "program";
                    reason        = ExceptionReason.InvalidNullInputs;
                }

                string exceptionString = GenerateExceptionString(validationErrors, reason);

                if (exceptionString != null)
                {
                    throw FxTrace.Exception.Argument(parameterName, exceptionString);
                }
            }
        }
        protected override void CacheMetadata(NativeActivityMetadata metadata)
        {
            Collection <RuntimeArgument> arguments = new Collection <RuntimeArgument>();

            foreach (KeyValuePair <string, Argument> entry in this.DelegateArguments)
            {
                RuntimeArgument argument = new RuntimeArgument(entry.Key, entry.Value.ArgumentType, entry.Value.Direction);
                metadata.Bind(entry.Value, argument);
                arguments.Add(argument);
            }

            metadata.SetArgumentsCollection(arguments);
            metadata.AddDelegate(this.Delegate);

            if (this.Delegate != null)
            {
                IList <RuntimeDelegateArgument> targetDelegateArguments = this.Delegate.RuntimeDelegateArguments;
                if (this.DelegateArguments.Count != targetDelegateArguments.Count)
                {
                    metadata.AddValidationError(SR.WrongNumberOfArgumentsForActivityDelegate);
                }

                // Validate that the names and directionality of arguments in DelegateArguments dictionary
                // match the names and directionality of arguments returned by the ActivityDelegate.GetDelegateParameters
                // call above.
                for (int i = 0; i < targetDelegateArguments.Count; i++)
                {
                    RuntimeDelegateArgument expectedParameter = targetDelegateArguments[i];
                    string parameterName = expectedParameter.Name;
                    if (this.DelegateArguments.TryGetValue(parameterName, out Argument delegateArgument))
                    {
                        if (delegateArgument.Direction != expectedParameter.Direction)
                        {
                            metadata.AddValidationError(SR.DelegateParameterDirectionalityMismatch(parameterName, delegateArgument.Direction, expectedParameter.Direction));
                        }

                        if (expectedParameter.Direction == ArgumentDirection.In)
                        {
                            if (!TypeHelper.AreTypesCompatible(delegateArgument.ArgumentType, expectedParameter.Type))
                            {
                                metadata.AddValidationError(SR.DelegateInArgumentTypeMismatch(parameterName, expectedParameter.Type, delegateArgument.ArgumentType));
                            }
                        }
                        else
                        {
                            if (!TypeHelper.AreTypesCompatible(expectedParameter.Type, delegateArgument.ArgumentType))
                            {
                                metadata.AddValidationError(SR.DelegateOutArgumentTypeMismatch(parameterName, expectedParameter.Type, delegateArgument.ArgumentType));
                            }
                        }
                    }
                    else
                    {
                        metadata.AddValidationError(SR.InputParametersMissing(expectedParameter.Name));
                    }

                    if (!this.hasOutputArguments && ArgumentDirectionHelper.IsOut(expectedParameter.Direction))
                    {
                        this.hasOutputArguments = true;
                    }
                }
            }

            metadata.AddChild(this.Default);
        }
            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());
                    }
                }
            }
 public static bool IsVariableType(Type propertyType)
 {
     return((propertyType.IsGenericType && (propertyType.GetGenericTypeDefinition() == variableGenericType)) || TypeHelper.AreTypesCompatible(propertyType, variableType));
 }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            WorkflowServiceHost host = null;
            Stream stream;
            string str2;

            if (string.IsNullOrEmpty(constructorString))
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.WorkflowServiceHostFactoryConstructorStringNotProvided));
            }
            if (baseAddresses == null)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.ArgumentNull("baseAddresses");
            }
            if (baseAddresses.Length == 0)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.BaseAddressesNotProvided));
            }
            if (!HostingEnvironment.IsHosted)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.Hosting_ProcessNotExecutingUnderHostedContext("WorkflowServiceHostFactory.CreateServiceHost")));
            }
            string virtualPath = VirtualPathUtility.Combine(AspNetEnvironment.Current.XamlFileBaseLocation, constructorString);

            if (this.GetServiceFileStreamOrCompiledCustomString(virtualPath, baseAddresses, out stream, out str2))
            {
                object obj2;
                using (stream)
                {
                    BuildManager.GetReferencedAssemblies();
                    XamlXmlReaderSettings settings = new XamlXmlReaderSettings {
                        ProvideLineInfo = true
                    };
                    XamlReader xamlReader = ActivityXamlServices.CreateReader(new XamlXmlReader(XmlReader.Create(stream), settings));
                    if (System.ServiceModel.Activation.TD.XamlServicesLoadStartIsEnabled())
                    {
                        System.ServiceModel.Activation.TD.XamlServicesLoadStart();
                    }
                    obj2 = XamlServices.Load(xamlReader);
                    if (System.ServiceModel.Activation.TD.XamlServicesLoadStopIsEnabled())
                    {
                        System.ServiceModel.Activation.TD.XamlServicesLoadStop();
                    }
                }
                WorkflowService service = null;
                if (obj2 is Activity)
                {
                    service = new WorkflowService {
                        Body = (Activity)obj2
                    };
                }
                else if (obj2 is WorkflowService)
                {
                    service = (WorkflowService)obj2;
                }
                if (service != null)
                {
                    if (service.Name == null)
                    {
                        string fileName      = VirtualPathUtility.GetFileName(virtualPath);
                        string namespaceName = string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) });
                        service.Name = XName.Get(XmlConvert.EncodeLocalName(fileName), namespaceName);
                        if ((service.ConfigurationName == null) && (service.Body != null))
                        {
                            service.ConfigurationName = XmlConvert.EncodeLocalName(service.Body.DisplayName);
                        }
                    }
                    host = this.CreateWorkflowServiceHost(service, baseAddresses);
                }
            }
            else
            {
                Type typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
                if (null == typeFromAssembliesInCurrentDomain)
                {
                    typeFromAssembliesInCurrentDomain = this.GetTypeFromCompileCustomString(str2, constructorString);
                }
                if (null == typeFromAssembliesInCurrentDomain)
                {
                    BuildManager.GetReferencedAssemblies();
                    typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
                }
                if (null != typeFromAssembliesInCurrentDomain)
                {
                    if (!TypeHelper.AreTypesCompatible(typeFromAssembliesInCurrentDomain, typeof(Activity)))
                    {
                        throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.TypeNotActivity(typeFromAssembliesInCurrentDomain.FullName)));
                    }
                    Activity activity = (Activity)Activator.CreateInstance(typeFromAssembliesInCurrentDomain);
                    host = this.CreateWorkflowServiceHost(activity, baseAddresses);
                }
            }
            if (host == null)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.CannotResolveConstructorStringToWorkflowType(constructorString)));
            }
            ((IDurableInstancingOptions)host.DurableInstancingOptions).SetScopeName(XName.Get(XmlConvert.EncodeLocalName(VirtualPathUtility.GetFileName(ServiceHostingEnvironment.FullVirtualPath)), string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) })));
            return(host);
        }
        protected override void CacheMetadata(CodeActivityMetadata metadata)
        {
            MethodInfo oldGetMethod = _getMethod;
            MethodInfo oldSetMethod = _setMethod;

            bool isRequired = false;

            if (typeof(TOperand).GetTypeInfo().IsEnum)
            {
                metadata.AddValidationError(SR.TargetTypeCannotBeEnum(this.GetType().Name, this.DisplayName));
            }
            else if (typeof(TOperand).GetTypeInfo().IsValueType)
            {
                metadata.AddValidationError(SR.TargetTypeIsValueType(this.GetType().Name, this.DisplayName));
            }

            if (string.IsNullOrEmpty(this.PropertyName))
            {
                metadata.AddValidationError(SR.ActivityPropertyMustBeSet("PropertyName", this.DisplayName));
            }
            else
            {
                Type operandType = typeof(TOperand);
                _propertyInfo = operandType.GetProperty(this.PropertyName);

                if (_propertyInfo == null)
                {
                    metadata.AddValidationError(SR.MemberNotFound(PropertyName, typeof(TOperand).Name));
                }
                else
                {
                    _getMethod = _propertyInfo.GetGetMethod();
                    _setMethod = _propertyInfo.GetSetMethod();

                    // Only allow access to public properties, EXCEPT that Locations are top-level variables
                    // from the other's perspective, not internal properties, so they're okay as a special case.
                    // E.g. "[N]" from the user's perspective is not accessing a nonpublic property, even though
                    // at an implementation level it is.
                    if (_setMethod == null && TypeHelper.AreTypesCompatible(_propertyInfo.DeclaringType, typeof(Location)) == false)
                    {
                        metadata.AddValidationError(SR.ReadonlyPropertyCannotBeSet(_propertyInfo.DeclaringType, _propertyInfo.Name));
                    }

                    if ((_getMethod != null && !_getMethod.IsStatic) || (_setMethod != null && !_setMethod.IsStatic))
                    {
                        isRequired = true;
                    }
                }
            }
            MemberExpressionHelper.AddOperandArgument(metadata, this.Operand, isRequired);
            if (_propertyInfo != null)
            {
                if (MethodCallExpressionHelper.NeedRetrieve(_getMethod, oldGetMethod, _getFunc))
                {
                    _getFunc = MethodCallExpressionHelper.GetFunc(metadata, _getMethod, s_funcCache, s_locker);
                }
                if (MethodCallExpressionHelper.NeedRetrieve(_setMethod, oldSetMethod, _setFunc))
                {
                    _setFunc = MethodCallExpressionHelper.GetFunc(metadata, _setMethod, s_funcCache, s_locker);
                }
            }
        }
Exemple #24
0
 internal static string GetPropertyName(Type handleType)
 {
     Fx.Assert(TypeHelper.AreTypesCompatible(handleType, typeof(Handle)), "must pass in a Handle-based type here");
     return(handleType.FullName);
 }
 public static bool IsRuntimeArgumentType(Type propertyType)
 {
     return(TypeHelper.AreTypesCompatible(propertyType, runtimeArgumentType));
 }