private void initializeCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e)
        {
            ReportFunctionActionNode reportFunctionActionNode = (ReportFunctionActionNode)ActionNode.Deserialize(this.Payload);

            Dictionary <string, string> piggybag = PiggybagSerializer.Deserialize(this.ExtraPayload);

            var replaceContext = new DynamicValuesHelperReplaceContext(this.EntityToken, piggybag);

            XElement markup = reportFunctionActionNode.FunctionMarkupDynamicValuesHelper.ReplaceValues(replaceContext);

            BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup);
            XDocument           result = baseRuntimeTreeNode.GetValue() as XDocument;

            if (result == null)
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.ReportFunctionAction.WrongReturnValue"), "XDocument");

                Log.LogError("TreeFacade", message);

                throw new InvalidOperationException(message);
            }

            this.Bindings.Add("Label", reportFunctionActionNode.DocumentLabelDynamicValueHelper.ReplaceValues(replaceContext));
            this.Bindings.Add("Icon", reportFunctionActionNode.DocumentIcon.ResourceName);
            this.Bindings.Add("HtmlBlob", result.ToString());
        }
Esempio n. 2
0
        public static IEnumerable GetOptions(string optionsDescriptorSerialized)
        {
            XElement optionsDescriptor = XElement.Parse(optionsDescriptorSerialized);

            string              keyFieldName    = optionsDescriptor.Attribute("KeyFieldName").Value;
            string              labelFieldName  = optionsDescriptor.Attribute("LabelFieldName").Value;
            XElement            treeNodeElement = optionsDescriptor.Element("TreeNode").Elements().First();
            BaseRuntimeTreeNode runtimeTreeNode = FunctionFacade.BuildTree(treeNodeElement);

            IEnumerable optionsSource = runtimeTreeNode.GetValue <IEnumerable>();

            if (optionsSource is IEnumerable <XElement> )
            {
                IEnumerable <XElement> optionElements = (IEnumerable <XElement>)optionsSource;
                foreach (XElement optionElement in optionElements)
                {
                    yield return(new
                    {
                        Key = optionElement.Attribute(keyFieldName).Value,
                        Label = optionElement.Attribute(labelFieldName).Value
                    });
                }
            }
            else if (optionsSource is IDictionary)
            {
                IDictionary optionsDictionary = (IDictionary)optionsSource;
                foreach (var optionKey in optionsDictionary.Keys)
                {
                    yield return(new { Key = optionKey, Label = optionsDictionary[optionKey] });
                }
            }
            else if (string.IsNullOrEmpty(keyFieldName) == false || string.IsNullOrEmpty(labelFieldName))
            {
                foreach (object optionObject in optionsSource)
                {
                    if (optionObject != null)
                    {
                        Type objectType = optionObject.GetType();

                        string key = (string.IsNullOrEmpty(keyFieldName) ?
                                      optionObject.ToString() :
                                      objectType.GetProperty(keyFieldName).GetValue(optionObject, null).ToString());

                        string label = (string.IsNullOrEmpty(labelFieldName) ?
                                        optionObject.ToString() :
                                        objectType.GetProperty(labelFieldName).GetValue(optionObject, null).ToString());

                        yield return(new { Key = key, Label = label });
                    }
                }
            }
            else
            {
                foreach (var option in optionsSource)
                {
                    yield return(new { Key = option, Label = option });
                }
            }
        }
        private void showConfirmCodeActivity_ExecuteFunction_ExecuteCode(object sender, EventArgs e)
        {
            ConfirmActionNode confirmActionNode = (ConfirmActionNode)ActionNode.Deserialize(this.Payload);

            DynamicValuesHelperReplaceContext dynamicValuesHelperReplaceContext = CreateDynamicValuesHelperReplaceContext();

            AttributeDynamicValuesHelper attributeDynamicValuesHelper = new AttributeDynamicValuesHelper(confirmActionNode.FunctionMarkup);

            attributeDynamicValuesHelper.Initialize(confirmActionNode.OwnerNode);
            XElement markup = confirmActionNode.FunctionMarkupDynamicValuesHelper.ReplaceValues(dynamicValuesHelperReplaceContext);

            BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup);
            object value = baseRuntimeTreeNode.GetValue();
        }
        private LambdaExpression GetLambdaExpression(BaseRuntimeTreeNode baseRuntimeTreeNode)
        {
            LambdaExpression expression = (LambdaExpression)baseRuntimeTreeNode.GetValue();

            if (expression == null)
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongReturnValue"), string.Format("Expression<Func<{0}, bool>>", this.OwnerNode.InterfaceType));

                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);

                throw new InvalidOperationException(message);
            }


            if (expression.ReturnType != typeof(bool))
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionReturnType"), expression.ReturnType, typeof(bool));

                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);

                throw new InvalidOperationException(message);
            }

            if (expression.Parameters.Count() != 1)
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionParameterCount"), expression.Parameters.Count());

                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);

                throw new InvalidOperationException(message);
            }

            ParameterExpression parameterExpression = expression.Parameters.Single();

            if (this.OwnerNode.InterfaceType.IsAssignableFrom(parameterExpression.Type) == false)
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionParameterType"), parameterExpression.Type, this.OwnerNode.InterfaceType);

                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);

                throw new InvalidOperationException(message);
            }

            return(expression);
        }
Esempio n. 5
0
        private void initalizeStateCodeActivity_Initialize_ExecuteCode(object sender, EventArgs e)
        {
            List <NamedFunctionCall> namedFunctionCalls = new List <NamedFunctionCall>();

            if (Payload != "")
            {
                IFunction function = FunctionFacade.GetFunction(Payload);

                BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionFacade.BuildTree(function, new Dictionary <string, object>());

                NamedFunctionCall namedFunctionCall = new NamedFunctionCall("", (BaseFunctionRuntimeTreeNode)baseRuntimeTreeNode);

                namedFunctionCalls.Add(namedFunctionCall);

                string layoutLabel = string.Format(StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "FunctionTesterWorkflow.Layout.Label"), function.Name);
                this.Bindings.Add("LayoutLabel", layoutLabel);
            }

            this.Bindings.Add("FunctionCalls", namedFunctionCalls);
            this.Bindings.Add("Parameters", new List <ManagedParameterDefinition>());
            this.Bindings.Add("PageId", PageManager.GetChildrenIDs(Guid.Empty).FirstOrDefault());

            if (UserSettings.ActiveLocaleCultureInfo != null)
            {
                List <KeyValuePair <string, string> > activeCulturesDictionary = UserSettings.ActiveLocaleCultureInfos.Select(f => new KeyValuePair <string, string>(f.Name, DataLocalizationFacade.GetCultureTitle(f))).ToList();
                this.Bindings.Add("ActiveCultureName", UserSettings.ActiveLocaleCultureInfo.Name);
                this.Bindings.Add("ActiveCulturesList", activeCulturesDictionary);
            }

            this.Bindings.Add("PageDataScopeName", DataScopeIdentifier.AdministratedName);
            this.Bindings.Add("PageDataScopeList", new Dictionary <string, string>
            {
                { DataScopeIdentifier.AdministratedName, StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "FunctionTesterWorkflow.AdminitrativeScope.Label") },
                { DataScopeIdentifier.PublicName, StringResourceSystemFacade.GetString("Composite.Plugins.AllFunctionsElementProvider", "FunctionTesterWorkflow.PublicScope.Label") }
            });


            Guid stateId = Guid.NewGuid();
            var  state   = new FunctionCallDesignerState {
                WorkflowId = WorkflowInstanceId, ConsoleIdInternal = GetCurrentConsoleId()
            };

            SessionStateManager.DefaultProvider.AddState <IFunctionCallEditorState>(stateId, state, DateTime.Now.AddDays(7.0));

            this.Bindings.Add("SessionStateProvider", SessionStateManager.DefaultProviderName);
            this.Bindings.Add("SessionStateId", stateId);
        }
        private IEnumerable <XNode> GetClassNameOptionsValueNodes(ParameterList parameters)
        {
            BaseRuntimeTreeNode classNameOptionsRuntimeTreeNode = null;

            if (parameters.TryGetParameterRuntimeTreeNode(FontIconSelectorWidgetFuntion.ClassNameOptionsParameterName, out classNameOptionsRuntimeTreeNode))
            {
                object value = parameters.GetParameter(FontIconSelectorWidgetFuntion.ClassNameOptionsParameterName);
                if (value is string)
                {
                    yield return(new XText((string)value));
                }
                else
                {
                    foreach (var node in classNameOptionsRuntimeTreeNode.Serialize().Nodes())
                    {
                        yield return(node);
                    }
                }
            }
        }
        public object CallFunction(XPathNodeIterator nodeIterator)
        {
            Verify.ArgumentNotNull(nodeIterator, "nodeIterator");

            if (!nodeIterator.MoveNext())
            {
                return(string.Empty);
            }

            XPathNavigator navigator = nodeIterator.Current;

            XElement functionNode = GetXElement(navigator);

            if (functionNode == null)
            {
                LoggingService.LogWarning("StandardXslExtendion", "Failed to get a function definition.");
                return(string.Empty);
            }


            BaseRuntimeTreeNode runtimeTreeNode = FunctionTreeBuilder.Build(functionNode);

            object result = runtimeTreeNode.GetValue(new FunctionContextContainer());

            if (result is XElement)
            {
                return((result as XElement).CreateNavigator());
            }

            if (result is IEnumerable <XElement> )
            {
                return(new FunctionResultNodeIterator(result as IEnumerable <XElement>));
            }

            if (result is XhtmlDocument)
            {
                return((result as XhtmlDocument).Root.CreateNavigator());
            }

            return(result);
        }
        public override Expression CreateUpwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext)
        {
            DataEntityToken currentEntityToken = dynamicContext.CurrentEntityToken as DataEntityToken;
            IData           filteredDataItem   = null;

            Func <IData, bool> upwardsFilter = dataItem =>
            {
                var ancestorEntityToken = dataItem.GetDataEntityToken();

                var replaceContext = new DynamicValuesHelperReplaceContext
                {
                    CurrentDataItem    = dataItem,
                    CurrentEntityToken = ancestorEntityToken,
                    PiggybagDataFinder = new PiggybagDataFinder(dynamicContext.Piggybag, ancestorEntityToken)
                };

                XElement markup = this.FunctionMarkupDynamicValuesHelper.ReplaceValues(replaceContext);

                BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup);
                LambdaExpression    expression          = GetLambdaExpression(baseRuntimeTreeNode);

                if (expression.Parameters.Count != 1)
                {
                    throw new InvalidOperationException("Only 1 parameter lamdas supported when calling function: " + markup);
                }

                Delegate compiledExpression = expression.Compile();

                if (filteredDataItem == null)
                {
                    filteredDataItem = currentEntityToken.Data;
                }

                return((bool)compiledExpression.DynamicInvoke(filteredDataItem));
            };


            return(upwardsFilter.Target != null
                ? Expression.Call(Expression.Constant(upwardsFilter.Target), upwardsFilter.Method, parameterExpression)
                : Expression.Call(upwardsFilter.Method, parameterExpression));
        }
        public override Expression CreateDownwardsFilterExpression(ParameterExpression parameterExpression, TreeNodeDynamicContext dynamicContext)
        {
            var replaceContext = new DynamicValuesHelperReplaceContext(dynamicContext.CurrentEntityToken, dynamicContext.Piggybag);

            XElement markup = this.FunctionMarkupDynamicValuesHelper.ReplaceValues(replaceContext);

            BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(markup);
            LambdaExpression    expression          = GetLambdaExpression(baseRuntimeTreeNode);

            if (expression.Parameters.Count != 1)
            {
                throw new InvalidOperationException("Only 1 parameter lamdas supported when calling function: " + markup);
            }


            ParameterChangerExpressionVisitor expressionVisitor = new ParameterChangerExpressionVisitor(expression.Parameters.Single(), parameterExpression);

            Expression resultExpression = expressionVisitor.Visit(expression.Body);

            return(resultExpression);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="targetType"></param>
        /// <returns></returns>
        /// <exclude />
        protected override Validator DoCreateValidator(Type targetType)
        {
            try
            {
                BaseRuntimeTreeNode node = FunctionFacade.BuildTree(XElement.Parse(FunctionMarkup));

                IPropertyValidatorBuilder propertyValidatorBuilder = node.GetValue <IPropertyValidatorBuilder>();

                ValidatorAttribute validatorAttribute = (ValidatorAttribute)propertyValidatorBuilder.GetAttribute();

                Validator validator = (Validator)DoCreateValidatorMethodInfo.Invoke(validatorAttribute, new object[] { targetType });

                return(validator);
            }
            catch (Exception ex)
            {
                string message = string.Format("Validator function markup parse / execution failed with the following error: '{0}'. The validator attribute is dropped.", ex.Message);
                Log.LogError("LazyFunctionProviedPropertyAttribute", message);
            }

            return(new LazyFunctionProviedPropertyValidator());
        }
        public override string ToString()
        {
            BaseRuntimeTreeNode baseRuntimeTreeNode = FunctionTreeBuilder.Build(this.Markup);

            XDocument result = (XDocument)baseRuntimeTreeNode.GetValue();

            XhtmlDocument xhtmlDocument = result as XhtmlDocument;

            if (xhtmlDocument != null)
            {
                StringBuilder sb = new StringBuilder();

                foreach (XElement element in xhtmlDocument.Body.Elements())
                {
                    sb.AppendLine(element.ToString());
                }

                return(sb.ToString());
            }

            return(result.ToString());
        }
Esempio n. 12
0
        public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName)
        {
            BaseRuntimeTreeNode runtimeTreeNode = null;

            if (parameters.TryGetParameterRuntimeTreeNode("Options", out runtimeTreeNode))
            {
                string keyFieldName   = parameters.GetParameter <string>("KeyFieldName");
                string labelFieldName = parameters.GetParameter <string>("LabelFieldName");
                bool   multiple       = parameters.GetParameter <bool>("Multiple");
                bool   required       = parameters.GetParameter <bool>("Required");
                bool   compact        = parameters.GetParameter <bool>("Compact");

                XElement optionsDescriptor = new XElement("SelectorOptionsSource",
                                                          new XAttribute("KeyFieldName", parameters.GetParameter <string>("KeyFieldName") ?? ""),
                                                          new XAttribute("LabelFieldName", parameters.GetParameter <string>("LabelFieldName") ?? ""),
                                                          new XElement("TreeNode",
                                                                       runtimeTreeNode.Serialize()));

                return(StandardWidgetFunctions.BuildStaticCallPopulatedSelectorFormsMarkup(
                           parameters,
                           label,
                           helpDefinition,
                           bindingSourceName,
                           this.GetType(),
                           "GetOptions",
                           optionsDescriptor.ToString(),
                           "Key",
                           "Label",
                           multiple,
                           compact,
                           required,
                           true));
            }
            else
            {
                throw new InvalidOperationException("Could not get BaseRuntimeTreeNode for parameter 'Options'.");
            }
        }
Esempio n. 13
0
        public override XElement GetWidgetMarkup(ParameterList parameters, string label, HelpDefinition helpDefinition, string bindingSourceName)
        {
            BaseRuntimeTreeNode optionsRuntimeTreeNode = null;

            if (parameters.TryGetParameterRuntimeTreeNode("TreeNodes", out optionsRuntimeTreeNode))
            {
                bool required           = parameters.GetParameter <bool>("Required");
                bool autoSelectChildren = parameters.GetParameter <bool>("AutoSelectChildren");
                bool autoSelectParents  = parameters.GetParameter <bool>("AutoSelectParents");

                XElement formElement = base.BuildBasicWidgetMarkup("HierarchicalSelector", "SelectedKeys", label, helpDefinition, bindingSourceName);
                formElement.Add(new XElement(Namespaces.BindingFormsStdUiControls10 + "HierarchicalSelector.TreeNodes",
                                             optionsRuntimeTreeNode.Serialize()));
                formElement.Add(new XAttribute("AutoSelectChildren", autoSelectChildren));
                formElement.Add(new XAttribute("AutoSelectParents", autoSelectParents));

                return(formElement);
            }
            else
            {
                throw new InvalidOperationException("Could not get BaseRuntimeTreeNode for parameter 'TreeNodes'.");
            }
        }
Esempio n. 14
0
        public override object Execute(ParameterList parameters, FunctionContextContainer context)
        {
            var result       = new XhtmlDocument();
            var functionCall = new XElement(Composite.Core.Xml.Namespaces.Function10 + "function",
                                            new XAttribute("name", "Composite.Forms.RendererControl"));
            BaseRuntimeTreeNode paramNode = null;

            foreach (var parameterName in parameters.AllParameterNames)
            {
                try
                {
                    if (parameters.TryGetParameterRuntimeTreeNode(parameterName, out paramNode))
                    {
                        functionCall.Add(paramNode.Serialize());
                    }
                }
                //Ignore
                catch { }
            }
            result.Body.Add(
                new XElement(Namespaces.AspNetControls + "form",
                             functionCall));
            return(result);
        }
Esempio n. 15
0
        private static void SetPropertyOnProducer2(ElementCompileTreeNode element, string propertyName, PropertyCompileTreeNode property, CompileContext compileContext)
        {
            if (property.Value is BaseFunctionRuntimeTreeNode && !(element.Producer is FunctionParameterProducer))
            {
                property.Value = ((BaseFunctionRuntimeTreeNode)property.Value).GetValue();
            }

            if (property.InclosingProducerName != "" &&
                element.XmlSourceNodeInformation.Name != property.InclosingProducerName)
            {
                throw new FormCompileException(string.Format("The inclosing tag does not match the embedded property tag name {0}", propertyName), element, property);
            }

            Type producerType = element.Producer.GetType();

            PropertyInfo propertyInfo = producerType.GetProperty(propertyName);

            if (propertyInfo == null)
            {
                if (property.IsNamespaceDeclaration)
                {
                    return;                                  // Ignore it
                }
                throw new FormCompileException(string.Format("The producer {0} does not have property named {1}", producerType, propertyName), element, property);
            }

            MethodInfo getMethodInfo = propertyInfo.GetGetMethod();

            if (null == getMethodInfo)
            {
                throw new FormCompileException(string.Format("The producer {0} does not have a public get for the property named {1}", producerType, propertyName), element, property);
            }

            bool isReadOrBindProduced = property.Value is BindProducer || property.Value is ReadProducer;

            if (!isReadOrBindProduced && typeof(IDictionary).IsAssignableFrom(getMethodInfo.ReturnType))
            {
                if (property.Value == null)
                {
                    throw new FormCompileException(string.Format("Can not assign null to {0} dictionary", propertyName), element, property);
                }
                IDictionary dictionary = getMethodInfo.Invoke(element.Producer, null) as IDictionary;

                if (dictionary == null)
                {
                    throw new InvalidOperationException(string.Format("Property '{0}' on '{1}' has not been initialized.", propertyName, producerType));
                }

                MethodInfo      dictionaryAddMethodInfo = dictionary.GetType().GetMethod("Add");
                ParameterInfo[] dictionaryAddParmInfo   = dictionaryAddMethodInfo.GetParameters();

                Type valueType = property.Value.GetType();

                if (property.Value is IDictionary)
                {
                    IDictionary           values = (IDictionary)property.Value;
                    IDictionaryEnumerator dictionaryEnumerator = values.GetEnumerator();
                    while (dictionaryEnumerator.MoveNext())
                    {
                        dictionary.Add(dictionaryEnumerator.Key, dictionaryEnumerator.Value);
                    }
                }
                else
                {
                    if (property.Value is DictionaryEntry)
                    {
                        var dictionaryEntry = (DictionaryEntry)property.Value;
                        dictionary.Add(dictionaryEntry.Key, dictionaryEntry.Value);
                    }
                    else
                    {
                        PropertyInfo valueKeyProperty   = valueType.GetProperty("Key");
                        PropertyInfo valueValueProperty = valueType.GetProperty("Value");
                        if (valueKeyProperty == null || valueValueProperty == null)
                        {
                            throw new FormCompileException(string.Format("The type {0} can not be assigned to the The parameter type {0} for the method 'Add' on the return type of the property {1} does not match the value type {2}", dictionaryAddParmInfo[0].ParameterType.ToString(), propertyName, property.Value.GetType()), element, property);
                        }

                        object dictionaryEntryKey   = valueKeyProperty.GetGetMethod().Invoke(property.Value, null);
                        object dictionaryEntryValue = valueValueProperty.GetGetMethod().Invoke(property.Value, null);
                        dictionary.Add(dictionaryEntryKey, dictionaryEntryValue);
                    }
                }
                return;
            }

            if (!isReadOrBindProduced && typeof(IList).IsAssignableFrom(getMethodInfo.ReturnType))
            {
                IList list = getMethodInfo.Invoke(element.Producer, null) as IList;

                if (list == null)
                {
                    throw new InvalidOperationException(string.Format("Property '{0}' (an IList) on '{1}' has not been initialized.", propertyName, producerType));
                }

                MethodInfo      listAddMethodInfo = list.GetType().GetMethod("Add");
                ParameterInfo[] listAddParmInfo   = listAddMethodInfo.GetParameters();


                if (property.Value is IList)
                {
                    IList values = (IList)property.Value;
                    foreach (object value in values)
                    {
                        if (!listAddParmInfo[0].ParameterType.IsInstanceOfType(value))
                        {
                            throw new FormCompileException(string.Format(
                                                               "The parameter type {0} for the method 'Add' on the return type of the property {1} does not match the value type {2}",
                                                               listAddParmInfo[0].ParameterType, propertyName, property.Value.GetType()),
                                                           element, property);
                        }


                        list.Add(value);
                    }
                    return;
                }

                if (property.Value != null)
                {
                    if (!listAddParmInfo[0].ParameterType.IsInstanceOfType(property.Value))
                    {
                        throw new FormCompileException(string.Format(
                                                           "The parameter type {0} for the method 'Add' on the return type of the property {1} does not match the value type {2}",
                                                           listAddParmInfo[0].ParameterType, propertyName, property.Value.GetType()),
                                                       element, property);
                    }

                    list.Add(property.Value);
                }

                return;
            }

            // Binding values for function parameters
            if (property.Value is ReadProducer && typeof(IList <BaseRuntimeTreeNode>).IsAssignableFrom(getMethodInfo.ReturnType))
            {
                IList list = getMethodInfo.Invoke(element.Producer, null) as IList;

                object bindingObject;


                string source = (property.Value as ReadProducer).source;

                if (source.Contains("."))
                {
                    string[] parts = source.Split('.');

                    ResolvePropertyBinding(element, property, compileContext, parts[0], parts.Skip(1).ToArray(), out bindingObject);
                }
                else
                {
                    Type bindingType;

                    ResolveBindingObject(element, property, compileContext, source, out bindingObject, out bindingType);
                }

                list.Add(new ConstantObjectParameterRuntimeTreeNode("BindedValue", bindingObject));

                return;
            }

            CheckForMultiblePropertyAdds(element, propertyName, property);

            MethodInfo setMethodInfo = propertyInfo.GetSetMethod();

            if (null == setMethodInfo)
            {
                throw new FormCompileException(string.Format("The producer {0} does not have a public set for the property named {1}", producerType, propertyName), element, property);
            }

            object parm;

            if (null != property.Value)
            {
                if (property.Value is BindProducer)
                {
                    object[] attributes = propertyInfo.GetCustomAttributes(typeof(BindablePropertyAttribute), true);
                    if (attributes.Length == 0)
                    {
                        throw new FormCompileException(string.Format("The property {0} on the producer {1}, does not have a bind attribute specified", propertyName, producerType), element, property);
                    }

                    BindProducer bind   = (BindProducer)property.Value;
                    string       source = bind.source;

                    EvaluteBinding(element, source, property, compileContext, getMethodInfo, true);
                }
                else if (property.Value is ReadProducer)
                {
                    ReadProducer bind   = (ReadProducer)property.Value;
                    string       source = bind.source;

                    EvaluteBinding(element, source, property, compileContext, getMethodInfo, false);
                }
            }


            if (property.Value != null && getMethodInfo.ReturnType.IsInstanceOfType(property.Value))
            {
                if (typeof(IEnumerable).IsAssignableFrom(getMethodInfo.ReturnType) && getMethodInfo.ReturnType != typeof(string) && property.Value is string && ((string)property.Value).Length > 0)
                {
                    // common err in form: specify a string, where a binding was expected. Problem with IEnumerable: string is converted to char array - hardly the expected result
                    // this is not a critical, but helpful, check
                    throw new InvalidOperationException(string.Format("Unable to cast {0} value '{1}' to type '{2}'", property.Value.GetType().FullName, property.Value, getMethodInfo.ReturnType.FullName));
                }

                parm = property.Value;
            }
            else if (property.Value is BaseRuntimeTreeNode)
            {
                if (!(element.Producer is IFunctionProducer))
                {
                    // Handles C1 function in forms markup
                    BaseRuntimeTreeNode baseRuntimeTreeNode = property.Value as BaseRuntimeTreeNode;

                    object value = baseRuntimeTreeNode.GetValue();

                    parm = value;
                }
                else
                {
                    parm = property.Value;
                }
            }
            else
            {
                parm = ValueTypeConverter.Convert(property.Value, getMethodInfo.ReturnType);
            }

            if (element.Producer is LayoutProducer && propertyName == "UiControl")
            {
                LayoutProducer layoutProducer = (LayoutProducer)element.Producer;

                if (layoutProducer.UiControl != null)
                {
                    throw new FormCompileException(string.Format("Only one ui control is allow at the top level of the layout."), element, property);
                }
            }

            object[] parms = { parm };
            setMethodInfo.Invoke(element.Producer, parms);
        }
        private void editCodeActivity_Preview_ExecuteCode(object sender, EventArgs e)
        {
            IInlineFunction functionInfo       = this.GetBinding <IInlineFunction>("Function");
            string          code               = this.GetBinding <string>("FunctionCode");
            List <string>   selectedAssemblies = this.GetBinding <List <string> >("SelectedAssemblies");

            StringInlineFunctionCreateMethodErrorHandler handler = new StringInlineFunctionCreateMethodErrorHandler();

            MethodInfo methodInfo = InlineFunctionHelper.Create(functionInfo, code, handler, selectedAssemblies);

            FlowControllerServicesContainer serviceContainer            = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
            IFormFlowWebRenderingService    formFlowWebRenderingService = serviceContainer.GetService <IFormFlowWebRenderingService>();

            if (handler.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                if (!string.IsNullOrWhiteSpace(handler.MissingContainerType))
                {
                    AddFormattedTextBlock(sb, handler.MissingContainerType);
                }

                if (!string.IsNullOrWhiteSpace(handler.NamespaceMismatch))
                {
                    AddFormattedTextBlock(sb, handler.NamespaceMismatch);
                }

                if (!string.IsNullOrWhiteSpace(handler.MissionMethod))
                {
                    AddFormattedTextBlock(sb, handler.MissionMethod);
                }

                if (handler.LoadingException != null)
                {
                    AddFormattedTextBlock(sb, handler.LoadingException.ToString());
                }

                foreach (Tuple <int, string, string> compileError in handler.CompileErrors)
                {
                    AddFormattedTextBlock(sb, "{0} : {1} : {2}".FormatWith(compileError.Item1, compileError.Item2, compileError.Item3));
                }

                formFlowWebRenderingService.SetNewPageOutput(new LiteralControl(sb.ToString()));

                return;
            }

            List <ManagedParameterDefinition> parameters = this.GetBinding <List <ManagedParameterDefinition> >("Parameters");

            List <object> parameterValues        = new List <object>();
            bool          parameterErrors        = false;
            StringBuilder parameterErrorMessages = new StringBuilder();

            foreach (ParameterInfo parameterInfo in methodInfo.GetParameters())
            {
                ManagedParameterDefinition parameter = parameters.FirstOrDefault(f => f.Name == parameterInfo.Name);
                if (parameter == null)
                {
                    string message = string.Format(GetText("CSharpInlineFunction.MissingParameterDefinition"), parameterInfo.Name);

                    parameterErrors = true;
                    AddFormattedTextBlock(parameterErrorMessages, message);
                }
                else if (parameter.Type != parameterInfo.ParameterType)
                {
                    string message = string.Format(GetText("CSharpInlineFunction.WrongParameterTestValueType"), parameterInfo.Name, parameterInfo.ParameterType, parameter.Type);

                    parameterErrors = true;
                    AddFormattedTextBlock(parameterErrorMessages, message);
                }
                else
                {
                    string previewValueFunctionMarkup = (string.IsNullOrEmpty(parameter.TestValueFunctionMarkup) ? parameter.DefaultValueFunctionMarkup : parameter.TestValueFunctionMarkup);

                    if (string.IsNullOrEmpty(previewValueFunctionMarkup))
                    {
                        string message = string.Format(GetText("CSharpInlineFunction.MissingParameterTestOrDefaultValue"), parameterInfo.Name, parameterInfo.ParameterType, parameter.Type);

                        parameterErrors = true;
                        AddFormattedTextBlock(parameterErrorMessages, message);
                    }
                    else
                    {
                        try
                        {
                            BaseRuntimeTreeNode treeNode = FunctionFacade.BuildTree(XElement.Parse(previewValueFunctionMarkup));
                            object value      = treeNode.GetValue();
                            object typedValue = ValueTypeConverter.Convert(value, parameter.Type);
                            parameterValues.Add(typedValue);
                        }
                        catch (Exception ex)
                        {
                            string message = string.Format("Error setting '{0}'. {1}", parameterInfo.Name, ex.Message);

                            parameterErrors = true;
                            AddFormattedTextBlock(parameterErrorMessages, message);
                        }
                    }
                }
            }

            if (parameterErrors)
            {
                formFlowWebRenderingService.SetNewPageOutput(new LiteralControl(parameterErrorMessages.ToString()));
                return;
            }

            CultureInfo oldCurrentCulture   = Thread.CurrentThread.CurrentCulture;
            CultureInfo oldCurrentUICulture = Thread.CurrentThread.CurrentUICulture;

            try
            {
                Guid pageId;
                if (this.GetBinding <object>("PageId") == null)
                {
                    pageId = Guid.Empty;
                }
                else
                {
                    pageId = this.GetBinding <Guid>("PageId");
                }
                string      dataScopeName = this.GetBinding <string>("PageDataScopeName");
                string      cultureName   = this.GetBinding <string>("ActiveCultureName");
                CultureInfo cultureInfo   = null;
                if (cultureName != null)
                {
                    cultureInfo = CultureInfo.CreateSpecificCulture(cultureName);
                }

                using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo))
                {
                    Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = cultureInfo;

                    IPage page = DataFacade.GetData <IPage>(f => f.Id == pageId).FirstOrDefault();
                    if (page != null)
                    {
                        PageRenderer.CurrentPage = page;
                    }

                    object result = methodInfo.Invoke(null, parameterValues.ToArray());

                    string resultString;

                    try
                    {
                        resultString = PrettyPrinter.Print(result);
                    }
                    catch (Exception ex)
                    {
                        throw new TargetInvocationException(ex);
                    }

                    SetOutput(formFlowWebRenderingService, resultString);
                }
            }
            catch (TargetInvocationException ex)
            {
                SetOutput(formFlowWebRenderingService, ex.InnerException.ToString());
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture   = oldCurrentCulture;
                Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture;
            }
        }
 protected override void OnInitialize()
 {
     //MRJ: DSLTree: FunctionElementGeneratorTreeNode: More validaion here
     //MRJ: DSLTree: FunctionElementGeneratorTreeNode: What kind of return type should the function have?
     _functionNode = FunctionTreeBuilder.Build(this.FunctionMarkup);
 }
Esempio n. 18
0
        /// <summary>
        /// Executes functions that match the predicate recursively,
        ///
        /// </summary>
        /// <param name="element"></param>
        /// <param name="functionContext"></param>
        /// <param name="functionShouldBeExecuted">A predicate that defines whether a function should be executed based on its name.</param>
        /// <returns><value>True</value> if all of the functions has matched the predicate</returns>
        internal static bool ExecuteFunctionsRec(
            XElement element,
            FunctionContextContainer functionContext,
            Predicate <string> functionShouldBeExecuted = null)
        {
            if (element.Name != XName_function)
            {
                var children = element.Elements();
                if (element.Elements(XName_function).Any())
                {
                    // Allows replacing the function elements without breaking the iterator
                    children = children.ToList();
                }

                bool allChildrenExecuted = true;
                foreach (var childElement in children)
                {
                    if (!ExecuteFunctionsRec(childElement, functionContext, functionShouldBeExecuted))
                    {
                        allChildrenExecuted = false;
                    }
                }
                return(allChildrenExecuted);
            }

            bool allRecFunctionsExecuted = true;

            string functionName = (string)element.Attribute("name");
            object result;

            try
            {
                // Evaluating function calls in parameters
                IEnumerable <XElement> parameters = element.Elements();

                bool allParametersEvaluated = true;
                foreach (XElement parameterNode in parameters.ToList())
                {
                    if (!ExecuteFunctionsRec(parameterNode, functionContext, functionShouldBeExecuted))
                    {
                        allParametersEvaluated = false;
                    }
                }

                if (!allParametersEvaluated)
                {
                    return(false);
                }

                if (functionShouldBeExecuted != null &&
                    !functionShouldBeExecuted(functionName))
                {
                    return(false);
                }

                // Executing a function call
                BaseRuntimeTreeNode runtimeTreeNode = FunctionTreeBuilder.Build(element);
                result = runtimeTreeNode.GetValue(functionContext);

                if (result != null)
                {
                    // Evaluating functions in a result of a function call
                    result = functionContext.MakeXEmbedable(result);

                    foreach (XElement xelement in GetXElements(result).ToList())
                    {
                        if (!ExecuteFunctionsRec(xelement, functionContext, functionShouldBeExecuted))
                        {
                            allRecFunctionsExecuted = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (Profiler.Measure("PageRenderer. Logging exception: " + ex.Message))
                {
                    XElement errorBoxHtml;

                    if (!functionContext.ProcessException(functionName, ex, LogTitle, out errorBoxHtml))
                    {
                        throw;
                    }

                    result = errorBoxHtml;
                }
            }

            ReplaceFunctionWithResult(element, result);

            return(allRecFunctionsExecuted);
        }
        /// <summary>
        /// Execute the C1 Function defined for this attribute and return the result.
        /// </summary>
        /// <returns>Result of C1 Function call</returns>
        public override object GetValue()
        {
            BaseRuntimeTreeNode node = FunctionFacade.BuildTree(XElement.Parse(this.FunctionDescription));

            return(node.GetValue());
        }
Esempio n. 20
0
        private LambdaExpression GetLambdaExpression(BaseRuntimeTreeNode baseRuntimeTreeNode)
        {
            LambdaExpression expression = (LambdaExpression)baseRuntimeTreeNode.GetValue();

            if (expression == null)
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongReturnValue"), string.Format("Expression<Func<{0}, bool>>", this.OwnerNode.InterfaceType));

                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);

                throw new InvalidOperationException(message);
            }


            if (expression.ReturnType != typeof(bool))
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionReturnType"), expression.ReturnType, typeof(bool));
                
                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);
                
                throw new InvalidOperationException(message);
            }

            if (expression.Parameters.Count() != 1)
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionParameterCount"), expression.Parameters.Count());
                
                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);

                throw new InvalidOperationException(message);
            }

            ParameterExpression parameterExpression = expression.Parameters.Single();
            if (this.OwnerNode.InterfaceType.IsAssignableFrom(parameterExpression.Type) == false)
            {
                string message = string.Format(StringResourceSystemFacade.GetString("Composite.C1Console.Trees", "TreeValidationError.FunctionFilter.WrongFunctionParameterType"), parameterExpression.Type, this.OwnerNode.InterfaceType);
                
                Log.LogError("TreeFacade", message);
                Log.LogError("TreeFacade", "In tree " + this.OwnerNode.Tree.TreeId + " in function " + this.XPath);

                throw new InvalidOperationException(message);
            }

            return expression;
        }
 protected override void OnInitialize()
 {
     //MRJ: DSLTree: FunctionElementGeneratorTreeNode: More validaion here
     //MRJ: DSLTree: FunctionElementGeneratorTreeNode: What kind of return type should the function have?
     _functionNode = FunctionTreeBuilder.Build(this.FunctionMarkup);
 }
        private static bool IsSelfCalling(string functionName, BaseRuntimeTreeNode runtimeTreeNode)
        {
            if (runtimeTreeNode is FunctionParameterRuntimeTreeNode)
            {
                FunctionParameterRuntimeTreeNode functionParameterRuntimeTreeNode = runtimeTreeNode as FunctionParameterRuntimeTreeNode;

                if (functionParameterRuntimeTreeNode.GetHostedFunction().GetCompositeName() == functionName)
                {
                    return true;
                }
                return IsSelfCalling(functionName, functionParameterRuntimeTreeNode.GetHostedFunction());
            }

            if (runtimeTreeNode is BaseFunctionRuntimeTreeNode)
            {
                BaseFunctionRuntimeTreeNode functionRuntimeTreeNode = runtimeTreeNode as BaseFunctionRuntimeTreeNode;

                if (functionName == functionRuntimeTreeNode.GetCompositeName())
                {
                    return true;
                }

                foreach (BaseParameterRuntimeTreeNode parameterRuntimeTreeNode in functionRuntimeTreeNode.Parameters)
                {
                    if (IsSelfCalling(functionName, parameterRuntimeTreeNode))
                    {
                        return true;
                    }
                }

                return false;
            }

            return false;
        }
Esempio n. 23
0
        /// <exclude />
        public static void ExecuteEmbeddedFunctions(XElement element, FunctionContextContainer contextContainer)
        {
            using (TimerProfilerFacade.CreateTimerProfiler())
            {
                IEnumerable <XElement> functionCallDefinitions = element.DescendantsAndSelf(Namespaces.Function10 + "function")
                                                                 .Where(f => !f.Ancestors(Namespaces.Function10 + "function").Any());

                var functionCalls = functionCallDefinitions.ToList();
                if (functionCalls.Count == 0)
                {
                    return;
                }

                object[] functionExecutionResults = new object[functionCalls.Count];

                for (int i = 0; i < functionCalls.Count; i++)
                {
                    XElement functionCallDefinition = functionCalls[i];
                    string   functionName           = null;

                    object functionResult;
                    try
                    {
                        // Evaluating function calls in parameters
                        IEnumerable <XElement> parameters = functionCallDefinition.Elements();

                        foreach (XElement parameterNode in parameters)
                        {
                            ExecuteEmbeddedFunctions(parameterNode, contextContainer);
                        }


                        // Executing a function call
                        BaseRuntimeTreeNode runtimeTreeNode = FunctionTreeBuilder.Build(functionCallDefinition);

                        functionName = runtimeTreeNode.GetAllSubFunctionNames().FirstOrDefault();

                        object result = runtimeTreeNode.GetValue(contextContainer);

                        if (result != null)
                        {
                            // Evaluating functions in a result of a function call
                            object embedableResult = contextContainer.MakeXEmbedable(result);

                            foreach (XElement xelement in GetXElements(embedableResult))
                            {
                                ExecuteEmbeddedFunctions(xelement, contextContainer);
                            }

                            functionResult = embedableResult;
                        }
                        else
                        {
                            functionResult = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        using (Profiler.Measure("PageRenderer. Loggin an exception"))
                        {
                            XElement errorBoxHtml;

                            if (!contextContainer.ProcessException(functionName, ex, LogTitle, out errorBoxHtml))
                            {
                                throw;
                            }

                            functionResult = errorBoxHtml;
                        }
                    }

                    functionExecutionResults[i] = functionResult;
                }
                ;

                // Applying changes
                for (int i = 0; i < functionCalls.Count; i++)
                {
                    XElement functionCall       = functionCalls[i];
                    object   functionCallResult = functionExecutionResults[i];
                    if (functionCallResult != null)
                    {
                        if (functionCallResult is XAttribute && functionCall.Parent != null)
                        {
                            functionCall.Parent.Add(functionCallResult);
                            functionCall.Remove();
                        }
                        else
                        {
                            functionCall.ReplaceWith(functionCallResult);
                        }
                    }
                    else
                    {
                        functionCall.Remove();
                    }
                }
            }
        }