public void MakeHCFiles(XDocument model)
		{
			using (var writer = new StreamWriter(Path.Combine(Path.GetTempPath(), m_database + "HCInput.xml")))
				InputTransform.Transform(model.CreateNavigator(), null, writer);

			using (var writer = new StreamWriter(Path.Combine(Path.GetTempPath(), m_database + "gram.txt")))
				GrammarTransform.Transform(model.CreateNavigator(), null, writer);

			// TODO: Putting this here is not necessarily efficient because it happens every time
			//       the parser is run.  It would be more efficient to run this only when the user
			//       is trying a word.  But we need the "model" to apply this transform and it is
			//       available here, so we're doing this for now.
			using (var writer = new StreamWriter(Path.Combine(Path.GetTempPath(), m_database + "XAmpleWordGrammarDebugger.xsl")))
				GrammarDebuggingTransform.Transform(model.CreateNavigator(), null, writer);
		}
 /// <summary>
 /// Creates a new instance of the ValidationEvaluator containing the
 /// the validation schema and a specific XML document to be validated.
 /// </summary>
 /// <param name="schema">Validation schema. Must not be null.</param>
 /// <param name="xInstance">An instance of an XML document to be validated.
 /// Must not be null.</param>
 /// <param name="fullValidation">Indicates whether to validate the
 /// whole document regardless of any assertion, or to stop validation at
 /// the first assertion.</param>
 public ValidationEvaluator(Schema schema, XDocument xInstance, bool fullValidation)
 {
     this.schema = schema;
     this.xInstance = xInstance;
     this.fullValidation = fullValidation;
     this.xNavigator = xInstance.CreateNavigator();
 }
        public AjaxResult Feedback(string email, string message, string additionalInfo)
        {
            try
            {
                this.HandleCall ();

                if (!Utils.ValidateRequired (email, message) || !Utils.ValidateEmail (email))
                    return AjaxResult.WrongParametersOrHackAttempt;

                XDocument xml = new XDocument (
                        new XElement ("Root",
                            new XElement ("Email", Utils.RemoveHtmlTagsAndTrim (email, false)),
                            new XElement ("Message", Utils.RemoveHtmlTagsAndTrim (message, true)),
                            new XElement ("AdditionalInfo", Utils.RemoveHtmlTagsAndTrim (additionalInfo, true))
                        )
                    );

                if (this.Context.Request.Browser != null)
                    xml.Root.Add (new XElement ("Browser", this.Context.Request.Browser.Platform + " " + this.Context.Request.Browser.Browser + " " + this.Context.Request.Browser.Version));

                if (this.Context.Request.UserAgent != null)
                    xml.Root.Add (new XElement ("UserAgent", this.Context.Request.UserAgent));

                if (this.Context.Request.UserHostAddress != null)
                    xml.Root.Add (new XElement ("UserHostAddress", this.Context.Request.UserHostAddress));

                Utils.SendMailXslt (xml.CreateNavigator (), "~/Xslt/EmailFeedback.xslt", ConfigurationManager.AppSettings["SupportEmail"]);

                return AjaxResult.Success;
            }
            catch (Exception ex)
            {
                return this.HandleException (ex);
            }
        }
 protected override async Task SendBodyAsync(IRequestContext context)
 {
     if (Xslt != null) {
         if (Model is XDocument)
             await TransformAsync(context, ((XDocument)Model).CreateNavigator());
         else if (Model is IXPathNavigable)
             await TransformAsync(context, ((IXPathNavigable)Model));
         else {
             var ser = Serializer ?? new XmlSerializer(Model.GetType());
             var doc = new XDocument();
             using (var writer = doc.CreateWriter())
                 ser.Serialize(writer, Model);
             await TransformAsync(context, doc.CreateNavigator());
         }
     }
     else {
         using (var writer = context.Response.GetStreamWriter()) {
             if (Model is XDocument)
                 ((XDocument)Model).Save(writer);
             else if (Model is XmlDocument)
                 ((XmlDocument)Model).Save(writer);
             else if (Model is IXPathNavigable)
                 using (var xWriter = new XmlTextWriter(writer))
                     ((IXPathNavigable)Model).CreateNavigator().WriteSubtree(xWriter);
             else
                 (Serializer ?? new XmlSerializer(Model.GetType()))
                     .Serialize(writer, Model);
         }
     }
 }
        public Stream GetPersonInfo(string id)
        {
            int personId = 0;
            int.TryParse(id, out personId);
            Person personFound = persons.FirstOrDefault(p => p.Id == personId);

            if (WebOperationContext.Current != null)
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";

            var reader = new StringReader(Resource.Style);
            XmlReader xreader = XmlReader.Create(reader);
            var xslt = new XslCompiledTransform(false);
            xslt.Load(xreader);
            var serializer = new XmlSerializer(typeof(Person));

            var doc = new XDocument();
            using (XmlWriter writer = doc.CreateWriter())
            {
                if (personFound != null) 
                    serializer.Serialize(writer, personFound);
            }

            var outputWriter = new StringWriter();
            xslt.Transform(doc.CreateNavigator(), null, outputWriter);
            string htmlEmailText = outputWriter.ToString();

            var encoding = new System.Text.ASCIIEncoding();
            var stream = new MemoryStream(encoding.GetBytes(htmlEmailText));

            return stream;
        }
        public XmlNamespaceManagerEnhanced(XDocument doc)
            : base(doc.CreateReader().NameTable)
        {
            var ns = doc.Root.GetDefaultNamespace();
            if (ns != null && !string.IsNullOrWhiteSpace(ns.NamespaceName))
            {
                this.defaultNamespace = ns.NamespaceName;
                AddNamespace(Common.DefaultNamespace, this.defaultNamespace);
            }

            var nslist = new Dictionary<string, string>();
            var nav = doc.CreateNavigator();
            while (nav.MoveToFollowing(XPathNodeType.Element))
            {
                var newFoundNapespaces = nav.GetNamespacesInScope(XmlNamespaceScope.All).Where(a => !nslist.ContainsKey(a.Key) && !this.HasNamespace(a.Key));
                foreach (var item in newFoundNapespaces)
                {
                    nslist.Add(item.Key, item.Value);
                }
            }

            foreach (var item in nslist)
            {
                if (string.IsNullOrWhiteSpace(item.Key))
                    continue;
                AddNamespace(item.Key, item.Value);
            }
        }
 private string[] FindUnknownParentKeys(XDocument xmlDocument)
 {
     var pathNavigator = xmlDocument.CreateNavigator();
       var issueKeyList = pathNavigator.Select ("//key").Cast<XPathNavigator>().Select (n => n.Value).Distinct();
       var parentKeyList = pathNavigator.Select ("//parent").Cast<XPathNavigator>().Select (n => n.Value).Distinct();
       return parentKeyList.Except (issueKeyList).ToArray();
 }
        /// <summary>
        /// выполнить конвертацию структуры
        /// </summary>
        public void Do()
        {
            try
            {
                SendMessage("\n- Конвертация структуры курса");
                XDocument doc = new XDocument(course);
                doc.Document.Declaration = new XDeclaration("1.0", "utf-8", "true");
                XPathNavigator nv = doc.CreateNavigator();

                XslCompiledTransform xslt = new XslCompiledTransform();

                xslt.Load(convParams.ContentShemePath);

                XsltArgumentList xslArg = new XsltArgumentList();
                xslArg.AddParam("itemsPath", "", convParams.RootFolderName);

                string outFile = Path.Combine(convParams.OutputAbsPath, convParams.StartFileName);

                using (FileStream fs = new FileStream(outFile, FileMode.Create))
                {
                    xslt.Transform(nv, xslArg, fs);
                }
            }
            catch(Exception ex)
            {
                LastError = ex.Message;
                throw new Exception("Исключение при конвертации структуры курса: "+ex.Message);
            }
        }
 private XPathNodeIterator GetChildIterator(XDocument packet)
 {
     var xpathNavigator = packet.CreateNavigator();
     xpathNavigator.MoveToRoot();
     xpathNavigator.MoveToFirstChild();
     return xpathNavigator.SelectChildren(XPathNodeType.Element);
 }
Exemple #10
0
        private IXPathNavigable GetInputXml()
        {
            var xml = new XDocument(new XElement("x", new XElement("y", "sds")));

            //XmlDocument xml = new XmlDocument();
            //xml.LoadXml("<x><y>sds</y></x>");

            return xml.CreateNavigator();
        }
        public void GenerateQuickXml(TextWriter writer, XDocument xml)
        {
            var nav = xml.CreateNavigator();

            if(xml.Declaration != null)
            writer.WriteLine("?{0} {1}", xml.Declaration.Version, xml.Declaration.Encoding);

            Traverse(writer, nav);
        }
		public string Transform(Mediator mediator, XDocument doc, string baseName, XsltArgumentList args)
		{
			var cache = (FdoCache) mediator.PropertyTable.GetValue("cache");
			SetWritingSystemBasedArguments(cache, mediator, args);
			args.AddParam("prmIconPath", "", IconPath);
			string filePath = Path.Combine(Path.GetTempPath(), cache.ProjectId.Name + baseName + ".htm");
			using (var writer = new StreamWriter(filePath))
				m_transform.Transform(doc.CreateNavigator(), args, writer);
			return filePath;
		}
Exemple #13
0
		public void GetReady ()
		{
			document = XDocument.Parse ("<foo><bar/><baz/><qux/><squonk/></foo>");
			navigator = document.CreateNavigator ();

			document2 = XDocument.Parse ("<foo><bar baz='1'/><bar baz='2'/><bar baz='3'/></foo>");
			navigator2 = document2.CreateNavigator ();

			document3 = XDocument.Parse ("<foo><bar/><baz/><qux/></foo>");
			navigator3 = document3.CreateNavigator ();
		}
 internal static LoginProfile ProfileFromTwitter(XDocument info)
 {
     XPathNavigator nav = info.CreateNavigator();
     var profile = new LoginProfile
                       {
                           Name = nav.SelectNodeValue("//screen_name"),
                           DisplayName = nav.SelectNodeValue("//name"),
                           Avatar = nav.SelectNodeValue("//profile_image_url"),
                           TimeZone = nav.SelectNodeValue("//time_zone"),
                           Locale = nav.SelectNodeValue("//lang"),
                           Id = nav.SelectNodeValue("//id"),
                           Link = nav.SelectNodeValue("//url"),
                           Provider = ProviderConstants.Twitter
                       };
     return profile;
 }
Exemple #15
0
		public void saveTestCoreFunctionString ()
		{
			document = XDocument.Parse ("<foo>hello<bar>world</bar><baz>how are you</baz></foo>");
			navigator = document.CreateNavigator ();

			Assert.AreEqual ("world", navigator.Evaluate ("string(/foo/*)").ToString (), "#1");
			Assert.AreEqual ("NaN", navigator.Evaluate ("string(0 div 0)").ToString (), "#2");
			
			try {
				navigator.Evaluate ("string(+0)");
				Assert.Fail ("Expected an XPathException to be thrown.");
			} catch (XPathException) {}
			
			Assert.AreEqual ("0", navigator.Evaluate ("string(-0)").ToString (), "#3");
			Assert.AreEqual ("Infinity", navigator.Evaluate ("string(1 div 0)").ToString (), "#4");
			Assert.AreEqual ("-Infinity", navigator.Evaluate ("string(-1 div 0)").ToString (), "#5");
			Assert.AreEqual ("45", navigator.Evaluate ("string(45)").ToString (), "#6");
			Assert.AreEqual ("-22", navigator.Evaluate ("string(-22)").ToString (), "#7");
			Assert.AreEqual ("0.25", navigator.Evaluate ("string(.25)").ToString (), "#8");
			Assert.AreEqual ("-0.25", navigator.Evaluate ("string(-.25)").ToString (), "#9");
			Assert.AreEqual ("2", navigator.Evaluate ("string(2.0)").ToString (), "#10");
			Assert.AreEqual ("2.01", navigator.Evaluate ("string(2.01)").ToString (), "#11");
			Assert.AreEqual ("-3", navigator.Evaluate ("string(-3.0)").ToString (), "#12");
			Assert.AreEqual ("3.45", navigator.Evaluate ("string(3.45)").ToString (), "#13");

			// Wonder what this will look like under a different platform.
			Assert.AreEqual("0.33333333333333331", navigator.Evaluate ("string(1 div 3)").ToString (), "#14");
		}
        protected virtual XDocument ApplyMetaTransforms(XDocument workingDoc, CustomXsltContext customContext, IFileProvider provider, TempFileCollection tempFiles)
        {
            // check for meta-template directives and expand
            int metaCount = 0;
            XElement metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault();
            while (metaNode != null)
            {
                if (EvalCondition(customContext, metaNode, this.GetAttributeValueOrDefault(metaNode, "condition")))
                {
                    XslCompiledTransform metaTransform = this.LoadStylesheet(provider,
                                                                             this.GetAttributeValue(metaNode, "stylesheet"));

                    XsltArgumentList xsltArgList = new XsltArgumentList();

                    // TODO this is a quick fix/hack
                    xsltArgList.AddExtensionObject(Namespaces.Template, new TemplateXsltExtensions(null, null));

                    var metaParamNodes = metaNode.Elements("with-param");

                    foreach (XElement paramNode in metaParamNodes)
                    {
                        string pName = this.GetAttributeValue(paramNode, "name");
                        string pExpr = this.GetAttributeValue(paramNode, "select");

                        try
                        {
                            xsltArgList.AddParam(pName,
                                                 string.Empty,
                                                 workingDoc.XPathEvaluate(pExpr, customContext));
                        }
                        catch (XPathException ex)
                        {
                            throw new TemplateException(this._templateSourcePath,
                                                        paramNode.Attribute("select"),
                                                        string.Format(
                                                            "Unable to process XPath expression: '{0}'",
                                                            pExpr),
                                                        ex);
                        }
                    }



                    // this isn't very nice, but I can't figure out another way to get LineInfo included in the transformed document
                    XDocument outputDoc;
                    using (MemoryStream tempStream = new MemoryStream())
                    using (XmlWriter outputWriter = XmlWriter.Create(tempStream, new XmlWriterSettings { Indent = true }))
                    {

                        metaTransform.Transform(workingDoc.CreateNavigator(),
                                                xsltArgList,
                                                outputWriter,
                                                new XmlFileProviderResolver(provider));

                        outputWriter.Close();

                        // rewind stream
                        tempStream.Seek(0, SeekOrigin.Begin);
                        outputDoc = XDocument.Load(tempStream, LoadOptions.SetLineInfo);

                        // create and register temp file
                        // this will override the value set in PrepareTemplate in case of template inhertence
                        // TODO this is a bit hacky, maybe add Template.Name {get;} instead of this._basePath (which could be anything)
                        string filename = this._basePath + ".meta." + (++metaCount).ToString(CultureInfo.InvariantCulture);
                        this._templateSourcePath = this.SaveTempFile(tempFiles, outputDoc, filename);
                    }


                    TraceSources.TemplateSource.TraceVerbose("Template after transformation by {0}",
                                                             this.GetAttributeValue(metaNode, "stylesheet"));

                    TraceSources.TemplateSource.TraceData(TraceEventType.Verbose, 1, outputDoc.CreateNavigator());

                    workingDoc = outputDoc;
                }
                else
                {
                    // didn't process, so remove it
                    metaNode.Remove();
                }

                // select next template
                metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault();
            }
            return workingDoc;
        }
Exemple #17
0
 private static int Native(XPathExpression ms_xp, XDocument doc)
 {
     var l = new List<int>();
     for (int i = 0; i < numIters; ++i)
     {
         l.Add(((XPathNodeIterator)doc.CreateNavigator().Evaluate(ms_xp)).Count);
     }
     return l.FirstOrDefault();
 }
		private string CreateWordDebuggerPage(XDocument xmlDoc)
		{
			// apply word grammar step transform file
			var output = new XDocument();
			using (XmlWriter writer = output.CreateWriter())
				m_intermediateTransform.Transform(xmlDoc.CreateNavigator(), writer);
			m_wordGrammarDebuggerXml = output;
			// format the result
			return PageTransform.Transform(m_mediator, output, "WordGrammarDebugger" + m_xmlHtmlStack.Count);
		}
 public static IDictionary<string, string> GetSchemasInFile(XDocument doc)
 {
     XPathNavigator nav = doc.CreateNavigator();
     nav.MoveToFollowing(XPathNodeType.Element);
     return nav.GetNamespacesInScope(XmlNamespaceScope.All);
 }
        void TraceExceptionXml(Exception exception, string format, params object[] args)
        {
            var message = format;
            if (args != null && args.Length > 0)
                message = string.Format(CultureInfo.CurrentCulture, format, args);

            var xdoc = new XDocument();
            var writer = xdoc.CreateWriter();

            writer.WriteStartElement("", "TraceRecord", TraceXmlNs);
            writer.WriteAttributeString("Severity", "Error");
            //writer.WriteElementString ("TraceIdentifier", msdnTraceCode);
            writer.WriteElementString("Description", TraceXmlNs, message);
            writer.WriteElementString("AppDomain", TraceXmlNs, AppDomain.CurrentDomain.FriendlyName);
            writer.WriteElementString("Source", TraceXmlNs, source.Name);
            AddExceptionXml(writer, exception);
            writer.WriteEndElement();

            writer.Flush();
            writer.Close();

            source.TraceData(TraceEventType.Error, 0, xdoc.CreateNavigator());
        }
Exemple #21
0
		public void CoreFunctionNamespaceURI ()
		{
			document = XDocument.Parse ("<foo:bar xmlns:foo='#foo'><foo:baz><foo:qux /></foo:baz></foo:bar>");
			navigator = document.CreateNavigator ();

			Assert.AreEqual ("", navigator.Evaluate ("namespace-uri()").ToString (), "#1");
			Assert.AreEqual ("", navigator.Evaluate ("namespace-uri(/bogus)").ToString (), "#2");
			//Assert.AreEqual("foo", navigator.Evaluate ("namespace-uri(/bar)").ToString (), "#3");
			Assert.AreEqual ("", navigator2.Evaluate ("namespace-uri(//bar)").ToString (), "#4");
		}
        /// <summary>
        /// Gets the results as XML.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        private static XPathNodeIterator GetResultsAsXml(ISearchResults results)
        {
            // create the XDocument
            XDocument doc = new XDocument();

            // check there are any search results
            if (results.TotalItemCount > 0)
            {
                // create the root element
                XElement root = new XElement("nodes");

                // iterate through the search results
                foreach (SearchResult result in results)
                {
                    // create a new <node> element
                    XElement node = new XElement("node");

                    // create the @id attribute
                    XAttribute nodeId = new XAttribute("id", result.Id);

                    // create the @score attribute
                    XAttribute nodeScore = new XAttribute("score", result.Score);

                    // add the content
                    node.Add(nodeId, nodeScore);

                    foreach (KeyValuePair<String, String> field in result.Fields)
                    {
                        // create a new <data> element
                        XElement data = new XElement("data");

                        // create the @alias attribute
                        XAttribute alias = new XAttribute("alias", field.Key);

                        // assign the value to a CDATA section
                        XCData value = new XCData(field.Value);

                        // append the content
                        data.Add(alias, value);

                        // append the <data> element
                        node.Add(data);
                    }

                    // add the node
                    root.Add(node);
                }

                // add the root node
                doc.Add(root);
            }
            else
            {
                doc.Add(new XElement("error", "There were no search results."));
            }

            return doc.CreateNavigator().Select("/");
        }
        /// <summary>
        /// Transforms an XDocument to a new XDocument file using an embedded resource xslt file
        /// </summary>
        /// <param name="inputXDoc">XDocument to be transformed to KML</param>
        /// <param name="xsltFileName">Name of .xslt file in Resources folder (must be Embedded Resource)</param>
        /// <returns>new XDocument</returns>
        private static XDocument TransformXDocumentWithResourcesXslt(XDocument inputXDoc, string xsltFileName)
        {
            XslCompiledTransform xslt = new XslCompiledTransform();
            XsltSettings settings = new XsltSettings(true, false);

            XmlWriterSettings writerSettings = new XmlWriterSettings();
            writerSettings.Indent = true;
            writerSettings.IndentChars = "\t";
            writerSettings.Encoding = Encoding.UTF8;

            StringBuilder outputXmlStringBuilder = new StringBuilder();
            XmlWriter xmlWriter = XmlWriter.Create(outputXmlStringBuilder, writerSettings);

            Assembly assembly = Assembly.GetExecutingAssembly();
            using (Stream xsltFileStream = assembly.GetManifestResourceStream("RunningAhead2Kml.Resources." + xsltFileName))
            {
                using (XmlReader reader = XmlReader.Create(xsltFileStream))
                {
                    xslt.Load(reader, settings, new XmlUrlResolver());
                    xslt.Transform(inputXDoc.CreateNavigator(), xmlWriter);
                }
            }
            XDocument newDoc = XDocument.Parse(outputXmlStringBuilder.ToString());
            return newDoc;
        }
Exemple #24
0
 public XPathNodeIterator SmartTextValueToXmlNode(string str)
 {
     try
     {
         var values = SmartTextValue.Instanciate(str).OrderByDescending(a => a.CreationDate);
         SmartTextValuesContainer list = new SmartTextValuesContainer();
         list.Values = values.ToList();
         str = SerializeUtility.Serialize(list);
         XDocument doc = XDocument.Parse(str);
         return doc.CreateNavigator().Select("/");
     }
     catch {
         XDocument doc = new XDocument();
         return doc.CreateNavigator().Select("/");
     }
 }
Exemple #25
0
        /// <summary>
        /// Gets the results as XML.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns>
        /// Returns an XML structure of the search results.
        /// </returns>
        internal static XPathNodeIterator GetResultsAsXml(ISearchResults results)
        {
            var legacy = uQuery.IsLegacyXmlSchema();
            var attributes = new List<string>() { "id", "nodeName", "updateDate", "writerName", "path", "nodeTypeAlias", "parentID", "loginName", "email" };
            var doc = new XDocument();

            if (results.TotalItemCount > 0)
            {
                var nodes = new XElement("results");
                foreach (SearchResult result in results)
                {
                    var node = new XElement(legacy ? "node" : result.Fields["nodeTypeAlias"]);
                    node.Add(new object[] { new XAttribute("score", result.Score) });

                    foreach (KeyValuePair<string, string> item in result.Fields)
                    {
                        // if the field key starts with '__' (double-underscore) - then skip.
                        if (item.Key.StartsWith("__"))
                        {
                            continue;
                        }
                        // if not legacy schema and 'nodeTypeAlias' - add the @isDoc attribute
                        else if (!legacy && item.Key == "nodeTypeAlias")
                        {
                            node.Add(new object[] { new XAttribute("isDoc", string.Empty) });
                        }
                        // check if the field is an attribute or a data value
                        else if (attributes.Contains(item.Key))
                        {
                            // attribute field
                            node.Add(new object[] { new XAttribute(item.Key, item.Value) });
                        }
                        else
                        {
                            // data field
                            var data = new XElement(legacy ? "data" : item.Key);

                            // if legacy add the 'alias' attribute
                            if (legacy)
                            {
                                data.Add(new object[] { new XAttribute("alias", item.Key) });
                            }

                            // CDATA the value - because we don't know what it is!
                            data.Add(new object[] { new XCData(item.Value) });

                            // add the data field to the node.
                            node.Add(data);
                        }
                    }

                    // add the node to the collection.
                    nodes.Add(node);
                }

                doc.Add(nodes);
            }
            else
            {
                doc.Add(new XElement("error", "There were no search results."));
            }

            return doc.CreateNavigator().Select("/*");
        }
Exemple #26
0
        protected virtual ParsedTemplate PrepareTemplate(TemplateData templateData)
        {
            // clone orig doc
            XDocument workingDoc = new XDocument(this._templateDefinition);

            // start by loading any parameters as they are needed for meta-template evaluation

            Dictionary<string, XPathVariable> globalParams = new Dictionary<string, XPathVariable>();

            XElement[] paramNodes = workingDoc.Root.Elements("parameter").ToArray();
            foreach (XElement paramNode in paramNodes)
            {
                var tmplVar = new XPathVariable
                                  {
                                      Name = paramNode.Attribute("name").Value,
                                      ValueExpression =
                                          paramNode.Attribute("select") == null
                                              ? null
                                              : paramNode.Attribute("select").Value,
                                  };
                globalParams.Add(tmplVar.Name, tmplVar);
            }


            CustomXsltContext customContext = new CustomXsltContext();
            Func<string, object> onFailedResolve =
                s =>
                {
                    throw new InvalidOperationException(
                        String.Format("Parameter '{0}' could not be resolved.", s));
                };

            customContext.OnResolveVariable +=
                s =>
                {
                    XPathVariable var;

                    // if it's defined
                    if (globalParams.TryGetValue(s, out var))
                    {
                        // see if the user provided a value
                        object value;
                        if (templateData.Arguments.TryGetValue(s, out value))
                            return value;

                        // evaluate default value
                        if (!String.IsNullOrWhiteSpace(var.ValueExpression))
                            return workingDoc.XPathEvaluate(var.ValueExpression,
                                                            customContext);
                    }

                    return onFailedResolve(s);
                };

            // check for meta-template directives and expand
            XElement metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault();

            // we're going to need this later
            XmlFileProviderResolver fileResolver = new XmlFileProviderResolver(this._fileProvider, this._basePath);

            while (metaNode != null)
            {
                if (EvalCondition(customContext, metaNode, this.GetAttributeValueOrDefault(metaNode, "condition")))
                {
                    #region Debug conditional

#if DEBUG
                    const bool debugEnabled = true;
#else
                    const bool debugEnabled = false;
#endif

                    #endregion

                    XslCompiledTransform metaTransform = this.LoadStylesheet(metaNode.Attribute("stylesheet").Value);

                    XsltArgumentList xsltArgList = new XsltArgumentList();

                    // TODO this is a quick fix/hack
                    xsltArgList.AddExtensionObject("urn:lostdoc-core", new TemplateXsltExtensions(null, null));

                    var metaParamNodes = metaNode.Elements("with-param");

                    foreach (XElement paramNode in metaParamNodes)
                    {
                        string pName = paramNode.Attribute("name").Value;
                        string pExpr = paramNode.Attribute("select").Value;

                        xsltArgList.AddParam(pName,
                                             string.Empty,
                                             workingDoc.XPathEvaluate(pExpr, customContext));
                    }

                    XDocument outputDoc = new XDocument();
                    using (XmlWriter outputWriter = outputDoc.CreateWriter())
                    {
                        metaTransform.Transform(workingDoc.CreateNavigator(),
                                                xsltArgList,
                                                outputWriter,
                                                fileResolver);
                    }


                    TraceSources.TemplateSource.TraceVerbose("Template after transformation by {0}",
                                                             metaNode.Attribute("stylesheet").Value);

                    TraceSources.TemplateSource.TraceData(TraceEventType.Verbose, 1, outputDoc.CreateNavigator());

                    workingDoc = outputDoc;
                }
                else
                {
                    // didn't process, so remove it
                    metaNode.Remove();
                }


                // select next template
                metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault();
            }

            // loading template
            List<Stylesheet> stylesheets = new List<Stylesheet>();
            List<Resource> resources = new List<Resource>();
            List<Index> indices = new List<Index>();
            foreach (XElement elem in workingDoc.Root.Elements())
            {
                // we alread proessed the parameters
                if (elem.Name.LocalName == "parameter")
                    continue;

                if (elem.Name.LocalName == "apply-stylesheet")
                {
                    stylesheets.Add(this.ParseStylesheet(stylesheets, elem));
                }
                else if (elem.Name.LocalName == "index")
                {
                    indices.Add(this.ParseIndex(elem));
                }
                else if (elem.Name.LocalName == "include-resource")
                {
                    resources.Add(new Resource
                                      {
                                          Path = elem.Attribute("path").Value,
                                          ConditionExpression = this.GetAttributeValueOrDefault(elem, "condition")
                                      });
                }
                else
                {
                    throw new Exception("Unknown element: " + elem.Name.LocalName);
                }
            }

            return new ParsedTemplate
                       {
                           Resources = resources.ToArray(),
                           Stylesheets = stylesheets.ToArray(),
                           Indices = indices.ToArray()
                       };
        }
Exemple #27
0
        private void Transform(System.IO.TextWriter response, XslCompiledTransform transform, XDocument transformData, XsltArgumentList arguments)
        {
            if (transform.OutputSettings.OutputMethod == XmlOutputMethod.Html)
            {
                // TODO Valutare se effettivamente serve usare un writer particolare
                // da questo sembrerebbe di si: http://stackoverflow.com/questions/887739/xslt-self-closing-tags-issue
                // ma in realtà per risolvere il problema dei self enclosing io ho dovuto togliere il namespace
                // xmlns="http://www.w3.org/1999/xhtml" da gli xslt figli, e lasciarlo solo sul padre...non ho capito perchè
                using (XhtmlTextWriter htmlOutput = new XhtmlTextWriter(response))
                {
                    transform.Transform(transformData.CreateNavigator(), arguments, htmlOutput);
                }
            }
            else
                transform.Transform(transformData.CreateNavigator(), arguments, response);

            // TODO Should I need to set content type or other response properties?
            // maybe using some of the properties of the transform.OutputSettings...
        }
Exemple #28
0
 public void TestFixtureSetup()
 {
     _input = XDocument.Load(GetType().Assembly.GetManifestResourceStream(GetType().Namespace + ".dgml.xml"));
     _output = Dgml2GraphMl.Convert(_input);
     _navigator = _output.CreateNavigator();
     _outputNamespaceManager = new XmlNamespaceManager(new NameTable());
     _outputNamespaceManager.AddNamespace("graphml", Dgml2GraphMl.GraphMlNamespace.NamespaceName);
 }
		/// <summary>
		/// transform the POS that has templates to GAFAWS format
		/// </summary>
		private void TransformPosInfoToGafawsInputFormat(XElement templateElem, string gafawsFile)
		{
			var dom = new XDocument(new XElement(templateElem));
			using (var writer = new StreamWriter(Path.Combine(Path.GetTempPath(), gafawsFile)))
				GafawsTransform.Transform(dom.CreateNavigator(), null, writer);
		}
Exemple #30
0
		public void saveTestCoreFunctionNodeSetID ()
		{
			document = XDocument.Parse (
				"<!DOCTYPE foo [" +
				"<!ELEMENT foo (bar)>" +
				"<!ELEMENT bar EMPTY>" +
				"<!ATTLIST bar baz ID #REQUIRED>" +
				"]>" +
				"<foo><bar baz='1' qux='hello' /><bar baz='2' qux='world' /></foo>");
			navigator = document.CreateNavigator ();

			Assert.AreEqual ("hello", navigator.Evaluate ("string(id('1')/@qux)").ToString (), "#1");
			Assert.AreEqual ("world", navigator.Evaluate ("string(id('2')/@qux)").ToString (), "#2");
		}