Пример #1
0
        /// <exclude />
        public static Control Render(XDocument document, FunctionContextContainer contextContainer, IXElementToControlMapper mapper, IPage page)
        {
            using (TimerProfilerFacade.CreateTimerProfiler())
            {
                ExecuteEmbeddedFunctions(document.Root, contextContainer);

                ResolvePageFields(document, page);

                NormalizeAspNetForms(document);

                if (document.Root.Name != Namespaces.Xhtml + "html")
                {
                    return(new LiteralControl(document.ToString()));
                }

                XhtmlDocument xhtmlDocument = new XhtmlDocument(document);
                NormalizeXhtmlDocument(xhtmlDocument);

                ResolveRelativePaths(xhtmlDocument);

                PrioritizeHeadNodex(xhtmlDocument);

                AppendC1MetaTags(page, xhtmlDocument);

                LocalizationParser.Parse(xhtmlDocument);

                return(xhtmlDocument.AsAspNetControl(mapper));
            }
        }
Пример #2
0
        internal static void ProcessXhtmlDocument(XhtmlDocument xhtmlDocument, IPage page)
        {
            using (Profiler.Measure("Normalizing XHTML document"))
            {
                NormalizeXhtmlDocument(xhtmlDocument);
            }

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

            using (Profiler.Measure("Sorting <head> elements"))
            {
                PrioritizeHeadNodes(xhtmlDocument);
            }

            using (Profiler.Measure("Appending C1 meta tags"))
            {
                AppendC1MetaTags(page, xhtmlDocument);
            }

            using (Profiler.Measure("Parsing localization strings"))
            {
                LocalizationParser.Parse(xhtmlDocument);
            }
        }
            private XslCompiledTransform BuildCompiledTransform()
            {
                using (DebugLoggingScope.CompletionTime(this.GetType(), $"Loading and compiling {_xsltFunction.XslFilePath}"))
                {
                    string folderPath = Path.GetDirectoryName(_xsltFunction.XslFilePath);
                    string fileName   = Path.GetFileName(_xsltFunction.XslFilePath);

                    IXsltFile xsltFileHandle;

                    try
                    {
                        var xsltFileHandles =
                            (from file in DataFacade.GetData <IXsltFile>()
                             where String.Equals(file.FolderPath, folderPath, StringComparison.OrdinalIgnoreCase) &&
                             String.Equals(file.FileName, fileName, StringComparison.OrdinalIgnoreCase)
                             select file).ToList();

                        Verify.That(xsltFileHandles.Count == 1, "XSLT file path {0} found {1} times. Only one instance was expected.", _xsltFunction.XslFilePath, xsltFileHandles.Count);
                        xsltFileHandle = xsltFileHandles[0];
                    }
                    catch (Exception ex)
                    {
                        Log.LogError("XsltBasedFunctionProvider", ex);
                        throw;
                    }

                    if (!_subscribedToFileChanges)
                    {
                        xsltFileHandle.SubscribeOnChanged(ClearCachedData);
                        _subscribedToFileChanges = true;
                    }

                    var xslCompiledTransform = new XslCompiledTransform();


                    XDocument doc;
                    using (Stream xsltSourceStream = xsltFileHandle.GetReadStream())
                    {
                        using (XmlReader xmlReader = XmlReader.Create(xsltSourceStream))
                        {
                            doc = XDocument.Load(xmlReader);
                        }
                    }

                    ResolveImportIncludePaths(doc);

                    LocalizationParser.Parse(doc);

                    xslCompiledTransform.Load(doc.CreateReader(), XsltSettings.TrustedXslt, new XmlUrlResolver());


                    return(xslCompiledTransform);
                }
            }
Пример #4
0
        internal static void ProcessXhtmlDocument(XhtmlDocument xhtmlDocument, IPage page)
        {
            using (Profiler.Measure("Normalizing XHTML document"))
            {
                NormalizeXhtmlDocument(xhtmlDocument);
            }

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

            using (Profiler.Measure("Appending C1 meta tags"))
            {
                AppendC1MetaTags(page, xhtmlDocument);
            }

            using (Profiler.Measure("Sorting <head> elements"))
            {
                PrioritizeHeadNodes(xhtmlDocument);
            }

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

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

            var filters = ServiceLocator.GetServices <IPageContentFilter>().OrderBy(f => f.Order).ToList();

            if (filters.Any())
            {
                using (Profiler.Measure("Executing page content filters"))
                {
                    filters.ForEach(filter =>
                    {
                        using (Profiler.Measure($"Filter: {filter.GetType().FullName}"))
                        {
                            filter.Filter(xhtmlDocument, page);
                        }
                    });
                }
            }
        }
Пример #5
0
        private void editPreviewActivity_ExecuteCode(object sender, EventArgs e)
        {
            Stopwatch functionCallingStopwatch = null;
            long      millisecondsToken        = 0;

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

            try
            {
                IXsltFunction xslt = this.GetBinding <IXsltFunction>("CurrentXslt");

                string xslTemplate = this.GetBinding <string>("XslTemplate");

                IFile persistemTemplateFile = IFileServices.TryGetFile <IXsltFile>(xslt.XslFilePath);
                if (persistemTemplateFile != null)
                {
                    string persistemTemplate = persistemTemplateFile.ReadAllText();

                    if (this.GetBinding <int>("XslTemplateLastSaveHash") != persistemTemplate.GetHashCode())
                    {
                        xslTemplate = persistemTemplate;
                        ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem {
                            Level = LogLevel.Fine, Message = "XSLT file on file system was used. It has been changed by another process.", Sender = this.GetType()
                        }, this.GetCurrentConsoleId());
                    }
                }

                List <NamedFunctionCall> namedFunctions = this.GetBinding <IEnumerable <NamedFunctionCall> >("FunctionCalls").ToList();

                // If preview is done multiple times in a row, with no postbacks an object reference to BaseFunctionRuntimeTreeNode may be held
                // If the function in the BaseFunctionRuntimeTreeNode have ben unloaded / reloaded, this preview will still run on the old instance
                // We force refresh by serializing / deserializing
                foreach (NamedFunctionCall namedFunction in namedFunctions)
                {
                    namedFunction.FunctionCall = (BaseFunctionRuntimeTreeNode)FunctionFacade.BuildTree(namedFunction.FunctionCall.Serialize());
                }


                List <ManagedParameterDefinition> parameterDefinitions = this.GetBinding <IEnumerable <ManagedParameterDefinition> >("Parameters").ToList();

                Guid        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);
                }

                IPage page;

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

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

                    functionCallingStopwatch = Stopwatch.StartNew();
                    transformationInput      = RenderHelper.BuildInputDocument(namedFunctions, parameterDefinitions, true);
                    functionCallingStopwatch.Stop();

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


                string output = "";
                string error  = "";
                try
                {
                    Thread.CurrentThread.CurrentCulture   = cultureInfo;
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;

                    var styleSheet = XElement.Parse(xslTemplate);

                    XsltBasedFunctionProvider.ResolveImportIncludePaths(styleSheet);

                    LocalizationParser.Parse(styleSheet);

                    XDocument transformationResult = new XDocument();
                    using (XmlWriter writer = new LimitedDepthXmlWriter(transformationResult.CreateWriter()))
                    {
                        XslCompiledTransform xslTransformer = new XslCompiledTransform();
                        xslTransformer.Load(styleSheet.CreateReader(), XsltSettings.TrustedXslt, new XmlUrlResolver());

                        XsltArgumentList transformArgs = new XsltArgumentList();
                        XslExtensionsManager.Register(transformArgs);

                        if (transformationInput.ExtensionDefinitions != null)
                        {
                            foreach (IXsltExtensionDefinition extensionDef in transformationInput.ExtensionDefinitions)
                            {
                                transformArgs.AddExtensionObject(extensionDef.ExtensionNamespace.ToString(),
                                                                 extensionDef.EntensionObjectAsObject);
                            }
                        }

                        Exception   exception   = null;
                        HttpContext httpContext = HttpContext.Current;

                        Thread thread = new Thread(delegate()
                        {
                            Thread.CurrentThread.CurrentCulture   = cultureInfo;
                            Thread.CurrentThread.CurrentUICulture = cultureInfo;

                            Stopwatch transformationStopwatch = Stopwatch.StartNew();

                            try
                            {
                                using (ThreadDataManager.Initialize())
                                    using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo))
                                    {
                                        HttpContext.Current = httpContext;

                                        var reader = transformationInput.InputDocument.CreateReader();
                                        xslTransformer.Transform(reader, transformArgs, writer);
                                    }
                            }
                            catch (ThreadAbortException ex)
                            {
                                exception = ex;
                                Thread.ResetAbort();
                            }
                            catch (Exception ex)
                            {
                                exception = ex;
                            }

                            transformationStopwatch.Stop();

                            millisecondsToken = transformationStopwatch.ElapsedMilliseconds;
                        });

                        thread.Start();
                        bool res = thread.Join(1000);  // sadly, this needs to be low enough to prevent StackOverflowException from fireing.

                        if (res == false)
                        {
                            if (thread.ThreadState == System.Threading.ThreadState.Running)
                            {
                                thread.Abort();
                            }
                            throw new XslLoadException("Transformation took more than 1000 milliseconds to complete. This could be due to a never ending recursive call. Execution aborted to prevent fatal StackOverflowException.");
                        }

                        if (exception != null)
                        {
                            throw exception;
                        }
                    }

                    if (xslt.OutputXmlSubType == "XHTML")
                    {
                        XhtmlDocument xhtmlDocument = new XhtmlDocument(transformationResult);

                        output = xhtmlDocument.Root.ToString();
                    }
                    else
                    {
                        output = transformationResult.Root.ToString();
                    }
                }
                catch (Exception ex)
                {
                    output = "<error/>";
                    error  = string.Format("{0}\n{1}", ex.GetType().Name, ex.Message);

                    Exception inner = ex.InnerException;

                    string indent = "";

                    while (inner != null)
                    {
                        indent = indent + " - ";
                        error  = error + "\n" + indent + inner.Message;
                        inner  = inner.InnerException;
                    }
                }
                finally
                {
                    Thread.CurrentThread.CurrentCulture   = oldCurrentCulture;
                    Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture;
                }

                Page currentPage = HttpContext.Current.Handler as Page;
                if (currentPage == null)
                {
                    throw new InvalidOperationException("The Current HttpContext Handler must be a System.Web.Ui.Page");
                }

                UserControl inOutControl = (UserControl)currentPage.LoadControl(UrlUtils.ResolveAdminUrl("controls/Misc/MarkupInOutView.ascx"));
                inOutControl.Attributes.Add("in", transformationInput.InputDocument.ToString());
                inOutControl.Attributes.Add("out", output);
                inOutControl.Attributes.Add("error", error);
                inOutControl.Attributes.Add("statusmessage", string.Format("Execution times: Total {0} ms. Functions: {1} ms. XSLT: {2} ms.",
                                                                           millisecondsToken + functionCallingStopwatch.ElapsedMilliseconds,
                                                                           functionCallingStopwatch.ElapsedMilliseconds,
                                                                           millisecondsToken));

                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                var webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(inOutControl);
            }
            catch (Exception ex)
            {
                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                Control errOutput        = new LiteralControl("<pre>" + ex.ToString() + "</pre>");
                var     webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(errOutput);
            }
        }
        public void Parse_should_yield_results()
        {
            DISetup.SetupContainer();

            var sb = new StringBuilder();

            sb.AppendLine(@"l_english:");
            sb.AppendLine(@" NEW_ACHIEVEMENT_2_0_NAME:0 ""Brave New World""");
            sb.AppendLine(@" NEW_ACHIEVEMENT_2_0_DESC:0 ""Colonize a planet""");
            sb.AppendLine(@" NEW_ACHIEVEMENT_2_1_NAME:0 ""Digging Deep""");

            var sb2 = new StringBuilder();

            sb2.AppendLine(@"l_english:");
            sb2.AppendLine(@" NEW_ACHIEVEMENT_2_0_NAME:0 ""Brave New World""");

            var sb3 = new StringBuilder();

            sb3.AppendLine(@"l_english:");
            sb3.AppendLine(@" NEW_ACHIEVEMENT_2_0_DESC:0 ""Colonize a planet""");

            var sb4 = new StringBuilder();

            sb4.AppendLine(@"l_english:");
            sb4.AppendLine(@" NEW_ACHIEVEMENT_2_1_NAME:0 ""Digging Deep""");

            var args = new ParserArgs()
            {
                ContentSHA      = "sha",
                ModDependencies = new List <string> {
                    "1"
                },
                File    = "loc\\loc.yml",
                Lines   = sb.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries),
                ModName = "fake"
            };
            var parser = new LocalizationParser(new CodeParser(new Logger()), null);
            var result = parser.Parse(args).ToList();

            result.Should().NotBeNullOrEmpty();
            result.Count().Should().Be(3);
            for (int i = 0; i < 3; i++)
            {
                result[i].ContentSHA.Should().Be("sha");
                result[i].Dependencies.First().Should().Be("1");
                result[i].File.Should().Be("loc\\loc.yml");
                switch (i)
                {
                case 0:
                    result[i].Code.Trim().Should().Be(sb2.ToString().Trim());
                    result[i].Id.Should().Be("NEW_ACHIEVEMENT_2_0_NAME");
                    result[i].ValueType.Should().Be(Common.ValueType.SpecialVariable);
                    break;

                case 1:
                    result[i].Code.Trim().Should().Be(sb3.ToString().Trim());
                    result[i].Id.Should().Be("NEW_ACHIEVEMENT_2_0_DESC");
                    result[i].ValueType.Should().Be(Common.ValueType.SpecialVariable);
                    break;

                case 2:
                    result[i].Code.Trim().Should().Be(sb4.ToString().Trim());
                    result[i].Id.Should().Be("NEW_ACHIEVEMENT_2_1_NAME");
                    result[i].ValueType.Should().Be(Common.ValueType.SpecialVariable);
                    break;

                default:
                    break;
                }
                result[i].ModName.Should().Be("fake");
                result[i].Type.Should().Be("loc\\l_english-yml");
            }
        }
Пример #7
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);
        }
Пример #8
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());
        }