public void ProcessRequest(HttpContext context)
        {
            var functionName = (string)context.Request.RequestContext.RouteData.Values["function"];

            var dataCulture = GetCurrentDataCulture(context);

            using (var data = new DataConnection())
            {
                if (!data.Get <IFunctionRoute>().Any())
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                    return;
                }
            }

            IFunction function;

            if (!FunctionFacade.TryGetFunction(out function, functionName))
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                return;
            }

            using (var dataScope = new DataScope(DataScopeIdentifier.Public, dataCulture))
            {
                var functionResult = FunctionFacade.Execute <object>(function, context.Request.QueryString);
                if (functionResult == null)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;

                    return;
                }

                var xhtmlDocument = functionResult as XhtmlDocument;
                if (xhtmlDocument != null)
                {
                    PageRenderer.ExecuteEmbeddedFunctions(xhtmlDocument.Root, new FunctionContextContainer());
                    PageRenderer.NormalizeXhtmlDocument(xhtmlDocument);

                    var xhtml = xhtmlDocument.ToString();

                    xhtml = PageUrlHelper.ChangeRenderingPageUrlsToPublic(functionResult.ToString());
                    xhtml = MediaUrlHelper.ChangeInternalMediaUrlsToPublic(xhtml);

                    context.Response.Write(xhtml);
                }
                else
                {
                    context.Response.Write(functionResult.ToString());

                    if (functionResult is XNode && function.ReturnType != typeof(XhtmlDocument))
                    {
                        context.Response.ContentType = "text/xml";
                    }
                }
            }
        }
Exemplo n.º 2
0
        public IHtmlString EvaluateMarkup(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var doc = new XElement(element);

            PageRenderer.ExecuteEmbeddedFunctions(doc, FunctionContextContainer);

            return(new HtmlString(doc.ToString()));
        }
        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 static object EvaluateLazyResult(object result, FunctionContextContainer context)
        {
            if (result is XDocument)
            {
                PageRenderer.ExecuteEmbeddedFunctions((result as XDocument).Root, context);
                return(result);
            }

            if (result is IEnumerable <XNode> )
            {
                return(EvaluateLazyResult(result as IEnumerable <XNode>, context));
            }

            return(result);
        }
        /// <summary>
        /// Binds placeholders' content to the related properties on a template definition
        /// </summary>
        /// <param name="template">The template.</param>
        /// <param name="pageContentToRender">The page rendering job.</param>
        /// <param name="placeholderProperties">The placeholder properties.</param>
        /// <param name="functionContextContainer">The function context container, if not null, nested functions fill be evaluated.</param>
        public static void BindPlaceholders(IPageTemplate template,
                                            PageContentToRender pageContentToRender,
                                            IDictionary <string, PropertyInfo> placeholderProperties,
                                            FunctionContextContainer functionContextContainer)
        {
            Verify.ArgumentNotNull(template, "template");
            Verify.ArgumentNotNull(pageContentToRender, "pageContentToRender");
            Verify.ArgumentNotNull(placeholderProperties, "placeholderProperties");

            foreach (var placeholderContent in pageContentToRender.Contents)
            {
                string placeholderId = placeholderContent.PlaceHolderId;

                if (!placeholderProperties.ContainsKey(placeholderId))
                {
                    continue;
                }

                XhtmlDocument placeholderXhtml = PageRenderer.ParsePlaceholderContent(placeholderContent);

                if (functionContextContainer != null)
                {
                    using (Profiler.Measure($"Evaluating placeholder '{placeholderId}'"))
                    {
                        PageRenderer.ExecuteEmbeddedFunctions(placeholderXhtml.Root, functionContextContainer);
                    }

                    using (Profiler.Measure("Normalizing XHTML document"))
                    {
                        PageRenderer.NormalizeXhtmlDocument(placeholderXhtml);
                    }
                }

                PageRenderer.ResolveRelativePaths(placeholderXhtml);

                PropertyInfo property = placeholderProperties[placeholderId];

                if (!property.ReflectedType.IsInstanceOfType(template))
                {
                    string propertyName = property.Name;
                    property = template.GetType().GetProperty(property.Name);
                    Verify.IsNotNull(property, "Failed to find placeholder property '{0}'", propertyName);
                }

                property.SetValue(template, placeholderXhtml, new object[0]);
            }
        }
Exemplo n.º 6
0
        /// <exclude />
        protected override void CreateChildControls()
        {
            if (InnerContent == null)
            {
                ProcessInternalControls();
            }

            if (InnerContent != null)
            {
                var functionContextContainer = _functionContextContainer;
                if (functionContextContainer == null && this.NamingContainer is UserControlFunction)
                {
                    var containerFunction = this.NamingContainer as UserControlFunction;
                    functionContextContainer = containerFunction.FunctionContextContainer;
                }

                if (functionContextContainer == null)
                {
                    functionContextContainer = PageRenderer.GetPageRenderFunctionContextContainer();
                }
                var controlMapper = (IXElementToControlMapper)functionContextContainer.XEmbedableMapper;

                PageRenderer.ExecuteEmbeddedFunctions(InnerContent, functionContextContainer);

                var xhmlDocument = new XhtmlDocument(InnerContent);

                PageRenderer.NormalizeXhtmlDocument(xhmlDocument);
                PageRenderer.ResolveRelativePaths(xhmlDocument);

                if (PageRenderer.CurrentPage != null)
                {
                    PageRenderer.ResolvePageFields(xhmlDocument, PageRenderer.CurrentPage);
                }

                NormalizeAspNetForms(xhmlDocument);

                AddNodesAsControls(xhmlDocument.Body.Nodes(), this, controlMapper);

                if (Page.Header != null)
                {
                    MergeHeadSection(xhmlDocument, Page.Header, controlMapper);
                }
            }

            base.CreateChildControls();
        }
Exemplo n.º 7
0
        public XElement RenderDocument(XElement doc)
        {
            using (Profiler.Measure("Executing C1 functions"))
            {
                PageRenderer.ExecuteEmbeddedFunctions(doc, FunctionContext);

                try
                {
                    var xDoc = new XhtmlDocument(doc);

                    PageRenderer.NormalizeXhtmlDocument(xDoc);
                    PageRenderer.ResolveRelativePaths(xDoc);

                    return(xDoc.Root);
                }
                catch (ArgumentException)
                {
                    return(doc);
                }
            }
        }
        private static XhtmlDocument RenderDataListImpl <T>(XhtmlDocument templateDocument, DataTypeDescriptor typeDescriptor, List <T> dataList, FunctionContextContainer functionContextContainer)
            where T : class, IData
        {
            XhtmlDocument outputDocument = new XhtmlDocument();

            if (dataList.Count > 0)
            {
                Type     interfaceType = typeDescriptor.GetInterfaceType();
                XElement templateBody  = new XElement(templateDocument.Body);

                Dictionary <string, PropertyInfo> propertyInfoLookup =
                    interfaceType.GetPropertiesRecursively(p => typeof(IData).IsAssignableFrom(p.DeclaringType)).ToList().ToDictionary(p => p.Name);

                List <string> fieldsWithReferenceRendering = new List <string>();

                foreach (PropertyInfo dataPropertyInfo in propertyInfoLookup.Values)
                {
                    Type referencedType = null;
                    if (dataPropertyInfo.TryGetReferenceType(out referencedType))
                    {
                        bool canRender = DataXhtmlRenderingServices.CanRender(referencedType, XhtmlRenderingType.Embedable);

                        if (canRender)
                        {
                            fieldsWithReferenceRendering.Add(dataPropertyInfo.Name);
                        }
                    }
                }


                // any optimization would do wonders
                foreach (IData data in dataList)
                {
                    XElement currentRowElementsContainer = new XElement(templateBody);

                    List <DynamicTypeMarkupServices.FieldReferenceDefinition> references =
                        DynamicTypeMarkupServices.GetFieldReferenceDefinitions(currentRowElementsContainer, typeDescriptor.TypeManagerTypeName).ToList();

                    // perf waste - if some props are not used;
                    Dictionary <string, object> objectValues =
                        propertyInfoLookup.ToDictionary(f => f.Key, f => f.Value.GetValue(data, new object[] { }));

                    foreach (DynamicTypeMarkupServices.FieldReferenceDefinition reference in references)
                    {
                        object value = null;

                        if (fieldsWithReferenceRendering.Contains(reference.FieldName))
                        {
                            // reference field with rendering...
                            Type referencedType = null;
                            if (propertyInfoLookup[reference.FieldName].TryGetReferenceType(out referencedType))
                            {
                                if (objectValues[reference.FieldName] != null)
                                {
                                    IDataReference dataReference = DataReferenceFacade.BuildDataReference(referencedType, objectValues[reference.FieldName]);
                                    try
                                    {
                                        value = DataXhtmlRenderingServices.Render(dataReference, XhtmlRenderingType.Embedable).Root;
                                    }
                                    catch (Exception)
                                    {
                                        value = objectValues[reference.FieldName];
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (objectValues.ContainsKey(reference.FieldName)) // prevents unknown props from creating exceptions
                            {
                                value = objectValues[reference.FieldName];
                            }
                        }

                        if (value != null)
                        {
                            if (value.GetType() == typeof(DateTime))
                            {
                                DateTime dateTimeValue = (DateTime)value;

                                if (dateTimeValue.TimeOfDay.TotalSeconds > 0)
                                {
                                    value = string.Format("{0} {1}", dateTimeValue.ToShortDateString(), dateTimeValue.ToShortDateString());
                                }
                                else
                                {
                                    value = dateTimeValue.ToShortDateString();
                                }
                            }

                            if (value.GetType() == typeof(string))
                            {
                                string stringValue = (string)value;

                                if (stringValue.StartsWith("<html") && stringValue.Contains(Namespaces.Xhtml.NamespaceName))
                                {
                                    try
                                    {
                                        value = XElement.Parse(stringValue);
                                    }
                                    catch { }
                                }
                                else if (stringValue.Contains('\n'))
                                {
                                    string valueEncodedWithBr = HttpUtility.HtmlEncode(stringValue).Replace("\n", "<br/>");
                                    value = XElement.Parse(string.Format("<body xmlns='{0}'>{1}</body>", Namespaces.Xhtml, valueEncodedWithBr)).Nodes();
                                }
                            }
                        }


                        reference.FieldReferenceElement.ReplaceWith(value);
                    }

                    FunctionContextContainer fcc = new FunctionContextContainer(functionContextContainer, objectValues);

                    PageRenderer.ExecuteEmbeddedFunctions(currentRowElementsContainer, fcc);

                    outputDocument.Body.Add(currentRowElementsContainer.Elements());
                }
            }

            return(outputDocument);
        }
Exemplo n.º 9
0
        public void ProcessRequest(HttpContext context)
        {
            OutputCacheHelper.InitializeFullPageCaching(context);

            using (var renderingContext = RenderingContext.InitializeFromHttpContext())
            {
                bool            cachingEnabled = false;
                string          cacheKey       = null;
                DonutCacheEntry cacheEntry     = null;

                bool consoleUserLoggedIn = Composite.C1Console.Security.UserValidationFacade.IsLoggedIn();

                // "Donut caching" is enabled for logged in users, only if profiling is enabled as well.
                if (!renderingContext.CachingDisabled &&
                    (!consoleUserLoggedIn || renderingContext.ProfilingEnabled))
                {
                    cachingEnabled = OutputCacheHelper.TryGetCacheKey(context, out cacheKey);
                    if (cachingEnabled)
                    {
                        using (Profiler.Measure("Cache lookup"))
                        {
                            cacheEntry = OutputCacheHelper.GetFromCache(context, cacheKey);
                        }
                    }
                }

                XDocument document;
                var       functionContext = PageRenderer.GetPageRenderFunctionContextContainer();

                bool allFunctionsExecuted   = false;
                bool preventResponseCaching = false;

                if (cacheEntry != null)
                {
                    document = cacheEntry.Document;
                    foreach (var header in cacheEntry.OutputHeaders)
                    {
                        context.Response.Headers[header.Name] = header.Value;
                    }

                    // Making sure this response will not go to the output cache
                    preventResponseCaching = true;
                }
                else
                {
                    if (renderingContext.RunResponseHandlers())
                    {
                        return;
                    }

                    var renderer = PageTemplateFacade.BuildPageRenderer(renderingContext.Page.TemplateId);

                    var slimRenderer = (ISlimPageRenderer)renderer;

                    using (Profiler.Measure($"{nameof(ISlimPageRenderer)}.Render"))
                    {
                        document = slimRenderer.Render(renderingContext.PageContentToRender, functionContext);
                    }

                    allFunctionsExecuted = PageRenderer.ExecuteCacheableFunctions(document.Root, functionContext);

                    if (cachingEnabled && !allFunctionsExecuted && OutputCacheHelper.ResponseCacheable(context))
                    {
                        preventResponseCaching = true;

                        if (!functionContext.ExceptionsSuppressed)
                        {
                            using (Profiler.Measure("Adding to cache"))
                            {
                                OutputCacheHelper.AddToCache(context, cacheKey, new DonutCacheEntry(context, document));
                            }
                        }
                    }
                }

                if (!allFunctionsExecuted)
                {
                    using (Profiler.Measure("Executing embedded functions"))
                    {
                        PageRenderer.ExecuteEmbeddedFunctions(document.Root, functionContext);
                    }
                }

                using (Profiler.Measure("Resolving page fields"))
                {
                    PageRenderer.ResolvePageFields(document, renderingContext.Page);
                }

                string xhtml;
                if (document.Root.Name == RenderingElementNames.Html)
                {
                    var xhtmlDocument = new XhtmlDocument(document);

                    PageRenderer.ProcessXhtmlDocument(xhtmlDocument, renderingContext.Page);
                    PageRenderer.ProcessDocumentHead(xhtmlDocument);

                    xhtml = xhtmlDocument.ToString();
                }
                else
                {
                    xhtml = document.ToString();
                }

                if (renderingContext.PreRenderRedirectCheck())
                {
                    return;
                }

                xhtml = renderingContext.ConvertInternalLinks(xhtml);

                if (GlobalSettingsFacade.PrettifyPublicMarkup)
                {
                    xhtml = renderingContext.FormatXhtml(xhtml);
                }

                var response = context.Response;

                if (preventResponseCaching)
                {
                    context.Response.Cache.SetNoServerCaching();
                }

                // Disabling ASP.NET cache if there's a logged-in user
                if (consoleUserLoggedIn)
                {
                    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                }

                // Inserting performance profiling information
                if (renderingContext.ProfilingEnabled)
                {
                    xhtml = renderingContext.BuildProfilerReport();

                    response.ContentType = "text/xml";
                }

                response.Write(xhtml);
            }
        }
Exemplo n.º 10
0
        public override void ExecuteResult(ControllerContext context)
        {
            string markup;

            using (TimerProfilerFacade.CreateTimerProfiler())
            {
                var page          = PageRenderer.CurrentPage;
                var markupBuilder = new StringBuilder();
                var sw            = new StringWriter(markupBuilder);
                var output        = new HtmlTextWriter(sw);

                IView view;
                using (Profiler.Measure("Resolving view for template"))
                {
                    view = FindView(context).View;
                }

                var viewContext = new ViewContext(context, view, ViewData, TempData, output);

                view.Render(viewContext, output);

                markup = markupBuilder.ToString();
                var xml = XDocument.Parse(markup);

                var functionContext = PageRenderer.GetPageRenderFunctionContextContainer();

                functionContext = new FunctionContextContainer(functionContext, new Dictionary <string, object>
                {
                    { "viewContext", viewContext }
                });

                using (Profiler.Measure("Executing embedded functions"))
                {
                    PageRenderer.ExecuteEmbeddedFunctions(xml.Root, functionContext);
                }

                using (Profiler.Measure("Resolving pagefields"))
                {
                    PageRenderer.ResolvePageFields(xml, page);
                }

                var document = new XhtmlDocument(xml);

                using (Profiler.Measure("Normalizing html"))
                {
                    PageRenderer.NormalizeXhtmlDocument(document);
                }

                PageRenderer.ResolveRelativePaths(document);
                PageRenderer.AppendC1MetaTags(page, document);

                using (Profiler.Measure("Resolving localized strings"))
                {
                    LocalizationParser.Parse(document);
                }

                markup = document.ToString();

                using (Profiler.Measure("Changing 'internal' page urls to 'public'"))
                {
                    markup = PageUrlHelper.ChangeRenderingPageUrlsToPublic(markup);
                }

                using (Profiler.Measure("Changing 'internal' media urls to 'public'"))
                {
                    markup = MediaUrlHelper.ChangeInternalMediaUrlsToPublic(markup);
                }

                markup = _mvcContext.FormatXhtml(markup);
            }

            if (_mvcContext.ProfilingEnabled)
            {
                markup = _mvcContext.BuildProfilerReport();

                context.HttpContext.Response.ContentType = "text/xml";
            }

            context.HttpContext.Response.Write(markup);
        }
Exemplo n.º 11
0
        private static XhtmlDocument ExecuteNestedFunctions(XhtmlDocument document, FunctionContextContainer functionContextContainer)
        {
            PageRenderer.ExecuteEmbeddedFunctions(document.Root, functionContextContainer);

            return(document);
        }
Exemplo n.º 12
0
        public virtual IHttpActionResult Body([FromBody] string body)
        {
            InitializeFullPageCaching(System.Web.HttpContext.Current);

            if (string.IsNullOrWhiteSpace(body))
            {
                NotFound();
            }

            var decrypted = LazyFunctionCallDataProvider.UnprotectFunctionCall(body);

            if (decrypted == null)
            {
                return(NotFound());
            }

            HttpContext.RewritePath(HttpContext.Request.FilePath, HttpContext.Request.PathInfo, decrypted.QueryString);

            using (var data = new DataConnection(PublicationScope.Published, ComposerContext.CultureInfo))
            {
                // Grab a function object to execute
                IFunction function = FunctionFacade.GetFunction(decrypted.FunctionName);

                PageRenderer.CurrentPage = PageManager.GetPageById(decrypted.PageId);;

                // Execute the function, passing all query string parameters as input parameters
                var functionResult = (XhtmlDocument)FunctionFacade.Execute <object>(function, decrypted.Parameters.ToDictionary(d => d.Key, d => (object)d.Value));


                // output result
                if (functionResult != null)
                {
                    var functionContext = new FunctionContextContainer();

                    PageRenderer.ExecuteEmbeddedFunctions(functionResult.Root, functionContext);

                    //PageRenderer.ProcessXhtmlDocument(functionResult, productPage);

                    using (Profiler.Measure("Normalizing XHTML document"))
                    {
                        PageRenderer.NormalizeXhtmlDocument(functionResult);
                    }

                    using (Profiler.Measure("Resolving relative paths"))
                    {
                        PageRenderer.ResolveRelativePaths(functionResult);
                    }


                    using (Profiler.Measure("Parsing localization strings"))
                    {
                        LocalizationParser.Parse(functionResult);
                    }

                    using (Profiler.Measure("Converting URLs from internal to public format (XhtmlDocument)"))
                    {
                        InternalUrls.ConvertInternalUrlsToPublic(functionResult);
                    }

                    //TODO: Update C1 Version
                    //PageRenderer.ProcessDocumentHead(functionResult);

                    StringBuilder sb = new StringBuilder();

                    foreach (var node in functionResult.Body.Nodes())
                    {
                        sb.Append(node.ToString());
                    }

                    return(Json(sb.ToString()));
                }
            }

            return(NotFound());
        }