Пример #1
0
 public override void TreeToTreeTransform()
 {
     if (sourceDocument != null)
     {
         XdmNavigator           contextItem = sourceDocument.CreateNavigator();
         var                    documentSet = new DocumentSet(nameTable, stylesheet.InputSettings, schemaAware ? documentResolverSchemaAware : documentResolver, null, resourceResolver);
         DynamicContextSettings settings    = new DynamicContextSettings();
         settings.ContextItem = contextItem;
         settings.DocumentSet = documentSet;
         //DynamicContextSettings settings = new DynamicContextSettings { ContextItem = contextItem };
         using (XdmDocumentWriter writer = XdmDocumentWriter.Create())
         {
             stylesheet.ApplyTemplates(settings, writer);
             resultDocument = writer.Document;
         }
     }
     else
     {
         var documentSet = new DocumentSet(nameTable, stylesheet.InputSettings, documentResolver, null, resourceResolver);
         DynamicContextSettings settings = new DynamicContextSettings {
             DocumentSet = documentSet
         };
         XmlQualifiedName qname = new XmlQualifiedName("main");
         using (XdmDocumentWriter writer = XdmDocumentWriter.Create())
         {
             stylesheet.CallTemplate(qname, settings, writer);
             resultDocument = writer.Document;
         }
     }
 }
Пример #2
0
        public override void FileToFileTransform(Uri sourceUri, string resultFileLocation)
        {
            if (sourceUri != null)
            {
                using (XmlReader reader = XmlReader.Create(sourceUri.ToString(), schemaAware ? xmlReaderSettingsSchemaAware : xmlReaderSettings))
                {
                    document = new XdmDocument(reader, XmlSpace.Preserve);
                    reader.Close();
                }
                XdmNavigator           contextItem = document.CreateNavigator();
                var                    documentSet = new DocumentSet(nameTable, stylesheet.InputSettings, schemaAware ? documentResolverSchemaAware : documentResolver, null, resourceResolver);
                DynamicContextSettings settings    = new DynamicContextSettings();
                settings.ContextItem = contextItem;
                settings.DocumentSet = documentSet;
                //DynamicContextSettings settings = new DynamicContextSettings { ContextItem = contextItem };
                stylesheet.SerializationSettings.CloseOutput = true;
                TextWriter writer = new StreamWriter(resultFileLocation);
                stylesheet.ApplyTemplates(settings, writer);
                writer.Close();
            }
            else
            {
                var documentSet = new DocumentSet(nameTable, stylesheet.InputSettings, documentResolver, null, resourceResolver);
                DynamicContextSettings settings = new DynamicContextSettings {
                    DocumentSet = documentSet
                };
                stylesheet.SerializationSettings.CloseOutput = true;
                XmlQualifiedName qname  = new XmlQualifiedName("main");
                TextWriter       writer = new StreamWriter(resultFileLocation);
                stylesheet.CallTemplate(qname, settings, writer);
                writer.Close();
            }

            this.resultFile = resultFileLocation;
        }
Пример #3
0
        private bool TryAddPathParameterr([NotNull] DynamicContextSettings dynamicContextSettings,
                                          [NotNull] XmlQualifiedName parameterName,
                                          [NotNull] string path)
        {
            Assert.ArgumentNotNull(dynamicContextSettings, "dynamicContextSettings");
            Assert.ArgumentNotNull(parameterName, "parameterName");
            Assert.ArgumentNotNull(path, "path");

            Log.LogMessage(MessageImportance.Low, "adding parameter '{0}' as document '{1}'", parameterName, path);

            try
            {
                //TODO: use AnyURI when it supports windows paths
                var fileInfo  = new FileInfo(path);
                var inputUri  = new Uri(fileInfo.FullName);
                var navigable = dynamicContextSettings.DocumentSet.Document(new AnyUri(inputUri));
                dynamicContextSettings.Parameters.Add(parameterName, navigable.CreateNavigator());
                return(true);
            }
            catch (XmlException ex)
            {
                Log.LogErrorFromException(ex, false, true, ex.SourceUri);
                return(false);
            }
            catch (ArgumentException ex)
            {
                Log.LogErrorFromException(ex, false, true, null);
                return(false);
            }
            catch (InvalidOperationException ex)
            {
                Log.LogErrorFromException(ex, false, true, null);
                return(false);
            }
        }
        public void Transform()
        {
            var nameTable = new NameTable();

            var xmlReaderSettings = new XmlReaderSettings {
                NameTable = nameTable
            };

            XdmDocument document;

            using (var reader = XmlReader.Create(_rootPath + "\\XmlPrimeXsltTransformer\\data.xml", xmlReaderSettings))
            {
                document = new XdmDocument(reader);
            }

            var xsltSettings = new XsltSettings(nameTable)
            {
                ContextItemType = XdmType.Node
            };

            var xslt = Xslt.Compile(_rootPath + "\\XmlPrimeXsltTransformer\\template.xsl", xsltSettings);

            var contextItem = document.CreateNavigator();
            var settings    = new DynamicContextSettings {
                ContextItem = contextItem
            };

            using (var outputStream = File.Create(outputPath))

                xslt.ApplyTemplates(settings, outputStream);
        }
Пример #5
0
        private bool TryAddExpressionParameterr([NotNull] DynamicContextSettings dynamicContextSettings,
                                                [NotNull] XmlQualifiedName parameterName,
                                                [NotNull] string select,
                                                [NotNull] XPathSettings settings)
        {
            Assert.ArgumentNotNull(dynamicContextSettings, "dynamicContextSettings");
            Assert.ArgumentNotNull(parameterName, "parameterName");
            Assert.ArgumentNotNull(select, "select");
            Assert.ArgumentNotNull(settings, "settings");

            Log.LogMessage(MessageImportance.Low,
                           "adding parameter '{0}' as expression '{1}'", parameterName,
                           select);

            try
            {
                // TODO: Set base URI, handle errors differently
                var selectExpr = XPath.Compile(select, settings);

                if (selectExpr == null)
                {
                    Log.LogWarning("Parameter '{0}' has invalid value '{1}'", parameterName, select);
                    return(false);
                }

                var definition = selectExpr.Evaluate(dynamicContextSettings);
                dynamicContextSettings.Parameters.Add(parameterName, definition);
                return(true);
            }
            catch (XdmException e)
            {
                LogXdmException(Severity.Error, e.InnerException);
                return(false);
            }
        }
Пример #6
0
        /// <summary>
        ///     Loads the collections.
        /// </summary>
        /// <param name = "dynamicContextSettings">The dynamic context settings.</param>
        /// <param name = "staticSettings">The static settings.</param>
        protected void LoadCollections([NotNull] DynamicContextSettings dynamicContextSettings,
                                       [NotNull] StaticContextSettings staticSettings)
        {
            Assert.ArgumentNotNull(dynamicContextSettings, "dynamicContextSettings");
            Assert.ArgumentNotNull(staticSettings, "staticSettings");

            // TODO: We should be specifying collections as a list of URIs, not as a list of files.
            // This way the collection can contain nodes wihtin a document (with fragment identifiers).
            // We are going to have to move this way anyway to handle uri-collection

            if (Collections == null)
            {
                return;
            }

            var collections = new Dictionary <AnyUri, List <IXPathNavigable> >();

            foreach (var item in Collections)
            {
                var uriString = item.GetMetadata("CollectionURI");
                Log.LogMessage(MessageImportance.Low, "adding " + item.ItemSpec + " to collection " + uriString);

                //TODO: use AnyURI when it supports windows paths
                var itemUri   = new Uri(item.GetMetadata("FullPath"));
                var navigable = dynamicContextSettings.DocumentSet.Document(new AnyUri(itemUri));

                if (string.IsNullOrEmpty(uriString))
                {
                    uriString = DefaultCollection;
                }
                List <IXPathNavigable> list;
                var uri = new AnyUri(uriString);
                if (!collections.TryGetValue(uri, out list))
                {
                    list             = new List <IXPathNavigable>();
                    collections[uri] = list;
                }
                list.Add(navigable);
            }

            foreach (var collection in collections)
            {
                dynamicContextSettings.DocumentSet.AddCollection(collection.Key, collection.Value.ToArray());
            }
            dynamicContextSettings.DefaultCollectionURI = new AnyUri(DefaultCollection);
            staticSettings.CollectionTypeResolver       = dynamicContextSettings.DocumentSet.CollectionTypeResolver;
        }
Пример #7
0
        private DynamicContextSettings GetDynamicContextSettings([NotNull] DocumentSet documentSet)
        {
            Assert.ArgumentNotNull(documentSet, "documentSet");

            //TODO: switch to constructing directly when AnyUri fully supports windows paths
            var outputPath = Output == null ? BuildEngine.ProjectFileOfTaskNode : Output.GetMetadata("FullPath");
            var outputUri  = new Uri(outputPath);
            var baseOutput = new AnyUri(outputUri);

            var dynamicContextSettings = new DynamicContextSettings
            {
                BaseOutputURI = baseOutput,
                DocumentSet   = documentSet
            };

            dynamicContextSettings.Trace += OnTrace;
            return(dynamicContextSettings);
        }
Пример #8
0
        /// <summary>
        /// Loads the context item.
        /// </summary>
        /// <param name="dynamicContextSettings">The dynamic context settings.</param>
        /// <returns><see langword="true" /> if the loading the context item succeeded; otherwise <see langword="false" />.</returns>
        protected bool LoadContextItem([NotNull] DynamicContextSettings dynamicContextSettings)
        {
            Assert.ArgumentNotNull(dynamicContextSettings, "dynamicContextSettings");

            if (Input == null)
            {
                return(true);
            }

            var item = LoadContextItem(dynamicContextSettings.DocumentSet, Input);

            if (item == null)
            {
                return(false);
            }

            dynamicContextSettings.ContextItem = item.CreateNavigator();

            return(true);
        }
Пример #9
0
        private DynamicContextSettings GetDynamicContextSettings([NotNull] DocumentSet documentSet)
        {
            Assert.ArgumentNotNull(documentSet, "documentSet");

            //TODO: switch to constructing directly when AnyUri fully supports windows paths
            var outputUri  = new Uri(Output.GetMetadata("FullPath"));
            var baseOutput = new AnyUri(outputUri);

            var dynamicContextSettings = new DynamicContextSettings
            {
                BaseOutputURI = baseOutput,
                DocumentSet   = documentSet,
                AvailableEnvironmentVariables =
                    EnvironmentVariables.Create()
            };

            dynamicContextSettings.Message += OnMessage;
            dynamicContextSettings.Trace   += OnTrace;

            return(dynamicContextSettings);
        }
Пример #10
0
        public override bool TestAssertion(string assertion)
        {
            bool DocOK  = true;
            bool FileOK = true;

            if (resultDocument != null)
            {
                XPathSettings xpathSettings = new XPathSettings(nameTable)
                {
                    ContextItemType = XdmType.Node
                };
                var xpath       = XPath.Compile(assertion, xpathSettings);
                var contextItem = resultDocument.CreateNavigator();
                var settings    = new DynamicContextSettings {
                    ContextItem = contextItem
                };
                DocOK = xpath.EvaluateToItem(contextItem).ValueAsBoolean;
            }
            if (resultFile != null)
            {
                XdmDocument resultDoc;
                using (var reader = XmlReader.Create(resultFile, xmlReaderSettings))
                {
                    resultDoc = new XdmDocument(reader);
                    reader.Close();
                }
                XPathSettings xpathSettings = new XPathSettings(nameTable)
                {
                    ContextItemType = XdmType.Node
                };
                var xpath       = XPath.Compile(assertion, xpathSettings);
                var contextItem = resultDoc.CreateNavigator();
                var settings    = new DynamicContextSettings {
                    ContextItem = contextItem
                };
                FileOK = xpath.EvaluateToItem(contextItem).ValueAsBoolean;
            }
            return(DocOK && FileOK);
        }
Пример #11
0
        private static void PerformTransformation(string inputPath, string xsltPath, string outputPath)
        {
            Debug.Assert(inputPath != null, "inputPath in null");
            Debug.Assert(xsltPath != null, "xsltPath in null");
            Debug.Assert(inputPath != null, "outputPath in null");

            // First, we create a new XmlNameTable instance. This will be used to share information such
            // as element and attribute names between the XML documents and the transformation.
            var nameTable = new NameTable();

            // Next we create an XmlReaderSettings instance and set its NameTable property.
            // In order for XmlPrime to work correctly all documents passed in to Xslt must be loaded
            // with the XmlNameTable used to compile the query.
            var xmlReaderSettings = new XmlReaderSettings {
                NameTable = nameTable
            };

            // In order to transform  the document we load it into an XdmDocument.
            XdmDocument document;

            using (var reader = XmlReader.Create(inputPath, xmlReaderSettings))
            {
                document = new XdmDocument(reader);
            }



            // In order to describe how the transformation should be compiled we need set up an XsltSettings
            // object.  This describes all the settings used for compilation.
            // In particular, we will set the name table used by the transformation to match the one we used
            // earlier and we will set the context item type.
            // By default the context item type is set to none, and so the context item cannot be set unless
            // we override the type here.
            var xsltSettings = new XsltSettings(nameTable)
            {
                ContextItemType = XdmType.Node,
            };

            // We can then compile the transformation using the Compile method.
            // This returns us an Xslt object encapsulating the transformation.
            var xslt = Xslt.Compile(xsltPath, xsltSettings);


            // Now we have our transformation object we now just need to execute it.
            // We use a DynamicContextSettings object which describes the parameters used to evaluate the query.
            // In particular we will set the context item to be the document that we loaded earlier.
            var contextItem = document.CreateNavigator();

            //ParameterDictionary parameters=new ParameterDictionary();
            //parameters.Add(new XmlQualifiedName("titleStyleId"),2);

            var settings = new DynamicContextSettings {
                ContextItem = contextItem
            };

            settings.Parameters.Add(new XmlQualifiedName("titleStyleId"), 2);

            // We will use the ApplyTemplates method to initiate a transformation by applying templates
            // in the default mode and serializing the primary result document to a stream.
            using (var outputStream = File.Create(outputPath))
            {
                xslt.ApplyTemplates(settings, outputStream);
            }
        }
Пример #12
0
        /// <summary>
        /// Performs the transformation.
        /// </summary>
        /// <param name="inputPath">The filename of the context item document.</param>
        /// <param name="xsltPath">The filename of the XSLT transformation.</param>
        /// <param name="outputPath">The filename of the primary output.</param>
        private static void PerformTransformation(string inputPath, string xsltPath, string outputPath)
        {
            Debug.Assert(inputPath != null, "inputPath in null");
            Debug.Assert(xsltPath != null, "xsltPath in null");
            Debug.Assert(inputPath != null, "outputPath in null");

            // First, we create a new XmlNameTable instance. This will be used to share information such
            // as element and attribute names between the XML documents and the transformation.
            var nameTable = new NameTable();

            // Next we create an XmlReaderSettings instance and set its NameTable property.
            // In order for XmlPrime to work correctly all documents passed in to Xslt must be loaded
            // with the XmlNameTable used to compile the query.
            var xmlReaderSettings = new XmlReaderSettings { NameTable = nameTable };

            // In order to transform  the document we load it into an XdmDocument.
            XdmDocument document;
            using (var reader = XmlReader.Create(inputPath, xmlReaderSettings))
            {
                document = new XdmDocument(reader);
            }

            // In order to describe how the transformation should be compiled we need set up an XsltSettings
            // object.  This describes all the settings used for compilation.
            // In particular, we will set the name table used by the transformation to match the one we used
            // earlier and we will set the context item type.
            // By default the context item type is set to none, and so the context item cannot be set unless
            // we override the type here.
            var xsltSettings = new XsltSettings(nameTable) { ContextItemType = XdmType.Node };

            // We can then compile the transformation using the Compile method.
            // This returns us an Xslt object encapsulating the transformation.
            var xslt = Xslt.Compile(xsltPath, xsltSettings);

            // Now we have our transformation object we now just need to execute it.
            // We use a DynamicContextSettings object which describes the parameters used to evaluate the query.
            // In particular we will set the context item to be the document that we loaded earlier.
            var contextItem = document.CreateNavigator();
            var settings = new DynamicContextSettings { ContextItem = contextItem };

            // We will use the ApplyTemplates method to initiate a transformation by applying templates
            // in the default mode and serializing the primary result document to a stream.
            using (var outputStream = File.Create(outputPath))
            {
                xslt.ApplyTemplates(settings, outputStream);
            }

            // NOTE: We could just have used xslt.ApplyTemplates(contextItem, outputStream) in this simple case.
        }
Пример #13
0
        /// <summary>
        ///     Sets the parameters from the <see cref = "Parameters" /> property.
        /// </summary>
        /// <param name = "dynamicContextSettings">The dynamic context settings.</param>
        /// <param name = "staticContextSettings">The static context settings.</param>
        /// <returns><see langword="true" /> if settings the parameters succeeded; otherwise, <see langword="false" />.</returns>
        protected bool SetParameters([NotNull] DynamicContextSettings dynamicContextSettings,
                                     [NotNull] StaticContextSettings staticContextSettings)
        {
            Assert.ArgumentNotNull(dynamicContextSettings, "dynamicContextSettings");
            Assert.ArgumentNotNull(staticContextSettings, "staticContextSettings");

            if (string.IsNullOrEmpty(Parameters))
            {
                return(true);
            }

            var settings = new XPathSettings(staticContextSettings.NameTable)
            {
                BaseURI                  = staticContextSettings.BaseURI,
                CollationResolver        = staticContextSettings.CollationResolver,
                CollectionTypeResolver   = staticContextSettings.CollectionTypeResolver,
                DefaultCollation         = staticContextSettings.DefaultCollation,
                DocumentTypeResolver     = staticContextSettings.DocumentTypeResolver,
                DefaultFunctionNamespace = staticContextSettings.DefaultFunctionNamespace,
                Schemas                  = staticContextSettings.Schemas,
                XmlVersion               = staticContextSettings.XmlVersion,
                Libraries                = staticContextSettings.Libraries
            };

            var xmlReaderSettings = new XmlReaderSettings {
                ConformanceLevel = ConformanceLevel.Fragment
            };

            try
            {
                using (var reader = XmlReader.Create(new StringReader(Parameters), xmlReaderSettings))
                {
                    reader.Read();
                    while (!reader.EOF)
                    {
                        switch (reader.NodeType)
                        {
                        case XmlNodeType.Element:
                        {
                            if (reader.LocalName != "Parameter")
                            {
                                continue;
                            }

                            var name         = reader.GetAttribute("Name");
                            var namespaceUri = reader.GetAttribute("Namespace") ?? string.Empty;

                            if (name == null)
                            {
                                Log.LogWarning(
                                    "Invalid parameter declaration: {0}\nParameter must contain a Name attribute",
                                    reader.ReadOuterXml());
                                continue;
                            }

                            var value  = reader.GetAttribute("Value");
                            var select = reader.GetAttribute("Select");
                            var path   = reader.GetAttribute("Path");

                            if (value == null &&
                                select == null &&
                                path == null)
                            {
                                Log.LogWarning(
                                    "Invalid parameter declaration: {0}\nParameter must contain either a Value, Select or Path attribute",
                                    reader.ReadOuterXml());
                                continue;
                            }

                            if (value != null &&
                                (select != null || path != null) ||
                                (select != null && path != null))
                            {
                                Log.LogWarning(
                                    "Invalid parameter declaration: {0}\nParameter must contain either a Value, Select or Path attribute",
                                    reader.ReadOuterXml());
                                continue;
                            }

                            var parameterName = new XmlQualifiedName(name, namespaceUri);

                            if (!dynamicContextSettings.Parameters.Contains(parameterName))
                            {
                                if (value != null)
                                {
                                    Log.LogMessage(MessageImportance.Low, "adding parameter '{0}' as value '{1}'",
                                                   parameterName, value);

                                    dynamicContextSettings.Parameters.AddUntypedAtomic(parameterName, value);
                                }
                                else if (path != null)
                                {
                                    if (TryAddPathParameterr(dynamicContextSettings,
                                                             parameterName,
                                                             path) == false)
                                    {
                                        return(false);
                                    }
                                }
                                else
                                {
                                    settings.Namespaces = (IXmlNamespaceResolver)reader;

                                    if (TryAddExpressionParameterr(dynamicContextSettings,
                                                                   parameterName,
                                                                   select,
                                                                   settings) == false)
                                    {
                                        return(false);
                                    }
                                }
                            }
                            else
                            {
                                Log.LogWarning("Parameter '{0}' has multiple definitions", parameterName);
                            }

                            reader.Skip();
                            break;
                        }

                        default:
                            reader.Skip();
                            break;
                        }
                    }
                }

                return(true);
            }
            catch (XmlException e)
            {
                LogXmlException(Severity.Error, e);
                return(false);
            }
        }