Exemple #1
0
        /// <exclude />
        public static ParameterList GetParametersListForTest(IEnumerable <ManagedParameterDefinition> parameterDefinitions)
        {
            ParameterList parameterList = new ParameterList(null);

            foreach (var parameterDefinition in parameterDefinitions)
            {
                if (!parameterDefinition.TestValueFunctionMarkup.IsNullOrEmpty())
                {
                    FunctionRuntimeTreeNode functionNode  = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.TestValueFunctionMarkup));
                    FunctionValueProvider   valueProvider = new FunctionValueProvider(functionNode);

                    object value = valueProvider.GetValue();
                    parameterList.AddConstantParameter(parameterDefinition.Name, value, parameterDefinition.Type);
                }
                else if (!parameterDefinition.DefaultValueFunctionMarkup.IsNullOrEmpty())
                {
                    FunctionRuntimeTreeNode functionNode  = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.DefaultValueFunctionMarkup));
                    FunctionValueProvider   valueProvider = new FunctionValueProvider(functionNode);

                    object value = valueProvider.GetValue();
                    parameterList.AddConstantParameter(parameterDefinition.Name, value, parameterDefinition.Type);
                }
                else
                {
                    throw new InvalidOperationException("Parameter '{0}' have neigther 'test value' nor 'default value' specified.".FormatWith(parameterDefinition.Name));
                }
            }


            return(parameterList);
        }
        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());
        }
        private static Dictionary <string, object> BuildTestParameterInput(IEnumerable <ManagedParameterDefinition> parameters)
        {
            Dictionary <string, object> inputValues = new Dictionary <string, object>();

            foreach (ManagedParameterDefinition parameterDefinition in parameters)
            {
                object value = null;
                if (string.IsNullOrEmpty(parameterDefinition.TestValueFunctionMarkup) == false)
                {
                    FunctionRuntimeTreeNode functionNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.TestValueFunctionMarkup));
                    value = functionNode.GetValue();
                }
                else
                {
                    if (string.IsNullOrEmpty(parameterDefinition.DefaultValueFunctionMarkup) == false)
                    {
                        FunctionRuntimeTreeNode functionNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(XElement.Parse(parameterDefinition.DefaultValueFunctionMarkup));
                        value = functionNode.GetValue();
                    }
                }

                if (value != null)
                {
                    if (parameterDefinition.Type.IsAssignableFrom(value.GetType()) == false)
                    {
                        value = ValueTypeConverter.Convert(value, parameterDefinition.Type);
                    }

                    inputValues.Add(parameterDefinition.Name, value);
                }
            }

            return(inputValues);
        }
        private static object EvaluateLazyResult(IEnumerable <XNode> xNodes, FunctionContextContainer context)
        {
            var resultList = new List <object>();

            // Attaching the result to be cached to an XElement, so the cached XObject-s will not be later attached to
            // an XDocument and causing a bigger memory leak.
            var tempParent = new XElement("t");

            foreach (var node in xNodes.Evaluate())
            {
                node.Remove();

                if (node is XElement element)
                {
                    if (element.Name == FunctionXName)
                    {
                        var functionTreeNode = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(element);

                        var functionCallResult = functionTreeNode.GetValue(context);
                        if (functionCallResult != null)
                        {
                            if (functionCallResult is XDocument document)
                            {
                                functionCallResult = document.Root;
                            }

                            resultList.Add(functionCallResult);

                            if (functionCallResult is XObject || functionCallResult is IEnumerable <XObject> )
                            {
                                tempParent.Add(functionCallResult);
                            }
                        }
                    }
                    else
                    {
                        PageRenderer.ExecuteEmbeddedFunctions(element, context);
                        resultList.Add(element);
                        tempParent.Add(element);
                    }
                }
                else
                {
                    resultList.Add(node);
                    tempParent.Add(node);
                }
            }

            return(resultList.ToArray());
        }
        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();
        }
        internal override void Initialize()
        {
            try
            {
                FunctionTreeBuilder.Build(this.FunctionMarkup);
            }
            catch
            {
                AddValidationError("TreeValidationError.FunctionFilter.WrongFunctionMarkup");
                return;
            }


            this.FunctionMarkupDynamicValuesHelper = new AttributeDynamicValuesHelper(this.FunctionMarkup);
            this.FunctionMarkupDynamicValuesHelper.Initialize(this.OwnerNode);
        }
        /// <exclude />
        protected override void OnInitialize()
        {
            try
            {
                FunctionTreeBuilder.Build(this.FunctionMarkup);
            }
            catch
            {
                AddValidationError("TreeValidationError.Common.WrongFunctionMarkup");
                return;
            }

            this.FunctionMarkupDynamicValuesHelper = new AttributeDynamicValuesHelper(this.FunctionMarkup);
            this.FunctionMarkupDynamicValuesHelper.Initialize(this.OwnerNode);

            this.DocumentLabelDynamicValueHelper = new DynamicValuesHelper(this.DocumentLabel);
            this.DocumentLabelDynamicValueHelper.Initialize(this.OwnerNode);
        }
        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 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 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);
        }
        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());
        }
        /// <exclude />
        public static IEnumerable <NamedFunctionCall> GetValidFunctionCalls(Guid xsltFunctionId, out List <string> errors)
        {
            errors = null;
            List <NamedFunctionCall> result = new List <NamedFunctionCall>();

            foreach (INamedFunctionCall namedFunctionCallData in DataFacade.GetData <INamedFunctionCall>(f => f.XsltFunctionId == xsltFunctionId))
            {
                XElement functionElement = XElement.Parse(namedFunctionCallData.SerializedFunction);

                FunctionRuntimeTreeNode function = null;

                try
                {
                    function = (FunctionRuntimeTreeNode)FunctionTreeBuilder.Build(functionElement);
                }
                catch (Exception ex)
                {
                    string errDescriptionForLog  = string.Format("XSLT Function call markup for failed to parse ('{0}').\nThe markup was \n{1}", ex.Message, functionElement);
                    string errDescriptionForUser = string.Format("XSLT Function call markup for failed to parse ('{0}').\nPlease see server log for more details.", ex.Message);
                    LoggingService.LogError("Function parse error", errDescriptionForLog);

                    if (errors == null)
                    {
                        errors = new List <string>();
                    }

                    errors.Add(errDescriptionForUser);
                }

                if (function != null)
                {
                    result.Add(new NamedFunctionCall(namedFunctionCallData.Name, function));
                }
            }

            return(result);
        }
Exemple #13
0
        private void GenerateForm()
        {
            var fieldNameToBindingNameMapper = new Dictionary <string, string>();

            _bindingsXml = new XElement(CmsBindingsElementTemplate);
            var layout = new XElement(CmsLayoutElementTemplate);

            if (!string.IsNullOrEmpty(LayoutIconHandle))
            {
                layout.Add(new XAttribute("iconhandle", LayoutIconHandle));
            }

            // Add a read binding as the layout label
            if (!string.IsNullOrEmpty(LayoutLabel))
            {
                var labelAttribute = new XAttribute("label", LayoutLabel);
                layout.Add(labelAttribute);
            }
            else if (!string.IsNullOrEmpty(_dataTypeDescriptor.LabelFieldName))
            {
                layout.Add((new XElement(CmsNamespace + "layout.label", new XElement(CmsNamespace + "read", new XAttribute("source", _dataTypeDescriptor.LabelFieldName)))));
            }


            _panelXml = new XElement(MainNamespace + "FieldGroup");

            string formLabel = !string.IsNullOrEmpty(FieldGroupLabel) ? FieldGroupLabel : _dataTypeDescriptor.Title;

            if (!string.IsNullOrEmpty(formLabel))
            {
                _panelXml.Add(new XAttribute("Label", formLabel));
            }

            layout.Add(_panelXml);

            foreach (var fieldDescriptor in _dataTypeDescriptor.Fields)
            {
                var bindingType = GetFieldBindingType(fieldDescriptor);
                var bindingName = GetBindingName(fieldDescriptor);

                fieldNameToBindingNameMapper.Add(fieldDescriptor.Name, bindingName);

                var binding = new XElement(CmsNamespace + FormKeyTagNames.Binding,
                                           new XAttribute("name", bindingName),
                                           new XAttribute("type", bindingType));

                if (fieldDescriptor.IsNullable)
                {
                    binding.Add(new XAttribute("optional", "true"));
                }

                _bindingsXml.Add(binding);

                if (!_readOnlyFields.Contains(fieldDescriptor.Name))
                {
                    XElement widgetFunctionMarkup;
                    var      label = fieldDescriptor.FormRenderingProfile.Label;
                    if (label.IsNullOrEmpty())
                    {
                        label = fieldDescriptor.Name;
                    }

                    var helptext = fieldDescriptor.FormRenderingProfile.HelpText ?? "";

                    if (!string.IsNullOrEmpty(fieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup))
                    {
                        widgetFunctionMarkup = XElement.Parse(fieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup);
                    }
                    else if (!DataTypeDescriptor.IsCodeGenerated && fieldDescriptor.FormRenderingProfile.WidgetFunctionMarkup == null)
                    {
                        // Auto generating a widget for not code generated data types
                        Type fieldType;

                        if (!fieldDescriptor.ForeignKeyReferenceTypeName.IsNullOrEmpty())
                        {
                            Type foreignKeyType;

                            try
                            {
                                foreignKeyType = Type.GetType(fieldDescriptor.ForeignKeyReferenceTypeName, true);
                            }
                            catch (Exception ex)
                            {
                                throw new InvalidOperationException("Failed to get referenced foreign key type '{0}'".FormatWith(fieldDescriptor.ForeignKeyReferenceTypeName), ex);
                            }

                            var referenceTemplateType = fieldDescriptor.IsNullable ? typeof(NullableDataReference <>) : typeof(DataReference <>);

                            fieldType = referenceTemplateType.MakeGenericType(foreignKeyType);
                        }
                        else
                        {
                            fieldType = fieldDescriptor.InstanceType;
                        }

                        var widgetFunctionProvider = StandardWidgetFunctions.GetDefaultWidgetFunctionProviderByType(fieldType);
                        if (widgetFunctionProvider != null)
                        {
                            widgetFunctionMarkup = widgetFunctionProvider.SerializedWidgetFunction;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }

                    var widgetRuntimeTreeNode = (WidgetFunctionRuntimeTreeNode)FunctionTreeBuilder.Build(widgetFunctionMarkup);
                    widgetRuntimeTreeNode.Label             = label;
                    widgetRuntimeTreeNode.HelpDefinition    = new HelpDefinition(helptext);
                    widgetRuntimeTreeNode.BindingSourceName = bindingName;

                    var element = (XElement)widgetRuntimeTreeNode.GetValue();
                    _panelXml.Add(element);
                }
            }

            if (_showPublicationStatusSelector && _dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)))
            {
                var placeholder = new XElement(MainNamespace + "PlaceHolder");
                _panelXml.Remove();

                placeholder.Add(_panelXml);
                layout.Add(placeholder);

                var publishFieldsXml = new XElement(MainNamespace + "FieldGroup", new XAttribute("Label", Texts.PublicationSettings_FieldGroupLabel));
                placeholder.Add(publishFieldsXml);

                var publicationStatusOptionsBinding = new XElement(CmsNamespace + FormKeyTagNames.Binding,
                                                                   new XAttribute("name", PublicationStatusOptionsBindingName),
                                                                   new XAttribute("type", typeof(object)));

                _bindingsXml.Add(publicationStatusOptionsBinding);

                var element =
                    new XElement(MainNamespace + "KeySelector",
                                 new XAttribute("OptionsKeyField", "Key"),
                                 new XAttribute("OptionsLabelField", "Value"),
                                 new XAttribute("Label", Texts.PublicationStatus_Label),
                                 new XAttribute("Help", Texts.PublicationStatus_Help),
                                 new XElement(MainNamespace + "KeySelector.Selected",
                                              new XElement(CmsNamespace + "bind", new XAttribute("source", PublicationStatusBindingName))),
                                 new XElement(MainNamespace + "KeySelector.Options",
                                              new XElement(CmsNamespace + "read", new XAttribute("source", PublicationStatusOptionsBindingName)))
                                 );


                publishFieldsXml.Add(element);


                var publishDateBinding = new XElement(CmsNamespace + FormKeyTagNames.Binding,
                                                      new XAttribute("name", "PublishDate"),
                                                      new XAttribute("type", typeof(DateTime)),
                                                      new XAttribute("optional", "true"));

                _bindingsXml.Add(publishDateBinding);

                publishFieldsXml.Add(
                    new XElement(MainNamespace + "DateTimeSelector",
                                 new XAttribute("Label", Texts.PublishDate_Label),
                                 new XAttribute("Help", Texts.PublishDate_Help),
                                 new XElement(CmsNamespace + "bind",
                                              new XAttribute("source", "PublishDate"))));

                var unpublishDateBinding = new XElement(CmsNamespace + FormKeyTagNames.Binding,
                                                        new XAttribute("name", "UnpublishDate"),
                                                        new XAttribute("type", typeof(DateTime)),
                                                        new XAttribute("optional", "true"));

                _bindingsXml.Add(unpublishDateBinding);

                publishFieldsXml.Add(
                    new XElement(MainNamespace + "DateTimeSelector",
                                 new XAttribute("Label", Texts.UnpublishDate_Label),
                                 new XAttribute("Help", Texts.UnpublishDate_Help),
                                 new XElement(CmsNamespace + "bind",
                                              new XAttribute("source", "UnpublishDate"))));
            }

            var formDefinition = new XElement(CmsFormElementTemplate);

            formDefinition.Add(_bindingsXml);
            formDefinition.Add(layout);

            if (CustomFormDefinition == null)
            {
                _generatedForm = formDefinition.ToString();
            }
            else
            {
                if (_dataTypeDescriptor.SuperInterfaces.Contains(typeof(IPublishControlled)))
                {
                    fieldNameToBindingNameMapper.Add("PublishDate", "PublishDate");
                    fieldNameToBindingNameMapper.Add("UnpublishDate", "UnpublishDate");
                }

                Func <XElement, IEnumerable <XAttribute> > getBindingsFunc =
                    doc => doc.Descendants(CmsNamespace + "binding").Attributes("name")
                    .Concat(doc.Descendants(CmsNamespace + "bind").Attributes("source"))
                    .Concat(doc.Descendants(CmsNamespace + "read").Attributes("source"));

                // Validation
                foreach (var bindingNameAttribute in getBindingsFunc(CustomFormDefinition.Root))
                {
                    var bindingName = bindingNameAttribute.Value;

                    if (!IsNotFieldBinding(bindingName) && !fieldNameToBindingNameMapper.ContainsKey(bindingName))
                    {
                        throw new ParseDefinitionFileException("Invalid binding name '{0}'".FormatWith(bindingName), bindingNameAttribute);
                    }
                }

                var formDefinitionElement = new XElement(CustomFormDefinition.Root);

                foreach (var bindingNameAttribute in getBindingsFunc(formDefinitionElement).Where(attr => !IsNotFieldBinding(attr.Value)))
                {
                    bindingNameAttribute.Value = fieldNameToBindingNameMapper[bindingNameAttribute.Value];
                }

                if (!string.IsNullOrEmpty(FieldGroupLabel))
                {
                    foreach (var fieldGroupElement in formDefinitionElement.Descendants(MainNamespace + "FieldGroup"))
                    {
                        if (fieldGroupElement.Attribute("Label") == null)
                        {
                            fieldGroupElement.Add(new XAttribute("Label", FieldGroupLabel));
                        }
                    }
                }

                _generatedForm = formDefinitionElement.ToString();
                _panelXml      = formDefinitionElement.Elements().Last().Elements().LastOrDefault();
            }
        }
        /// <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);
        }
 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);
 }
Exemple #16
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();
                    }
                }
            }
        }