Ejemplo n.º 1
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);
            }
        }
Ejemplo n.º 2
0
            public object Execute(ParameterList parameters, FunctionContextContainer context)
            {
                Guid xsltFunctionId = this._xsltFunction.Id;

                if (_FunctionCalls == null)
                {
                    lock (_lock)
                    {
                        if (_FunctionCalls == null)
                        {
                            _FunctionCalls = RenderHelper.GetValidatedFunctionCalls(xsltFunctionId);
                        }
                    }
                }

                TransformationInputs transformationInput = RenderHelper.BuildInputDocument(_FunctionCalls, parameters, false);

                XDocument newTree = new XDocument();

                using (XmlWriter writer = new LimitedDepthXmlWriter(newTree.CreateWriter()))
                {
                    XslCompiledTransform xslTransformer = GetXslCompiledTransform();

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

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

                    xslTransformer.Transform(transformationInput.InputDocument.CreateReader(), transformArgs, writer);
                }

                if (this._xsltFunction.OutputXmlSubType == "XHTML")
                {

                    return new XhtmlDocument(newTree);
                }
                return newTree.Root;
            }