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());
        }
예제 #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);
        }
        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 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());
        }
        /// <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());
        }
예제 #8
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;
            }
        }
예제 #10
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());
        }
예제 #12
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;
        }
 private IEnumerable <KeyValuePair <string, string> > GetFunctionResult()
 {
     return(_functionNode.GetValue <IEnumerable <KeyValuePair <string, string> > >());
 }
예제 #14
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();
                    }
                }
            }
        }