コード例 #1
0
        public static TransformResult Transform(string transformationPath, IDictionary <string, string> parameters, string[] targetFiles, bool preserveWhitespace = true)
        {
            if (!File.Exists(transformationPath))
            {
                throw new ArgumentException("Transformation path did not exist");
            }

            if (targetFiles == null || targetFiles.Length == 0)
            {
                return(null);
            }

            foreach (var file in targetFiles)
            {
                if (!File.Exists(file))
                {
                    throw new ArgumentException("Target file " + file + " did not exist");
                }
            }

            var logger        = new CollectionXmlTransformationLogger();
            var transformText = File.ReadAllText(transformationPath);

            transformText = ParameterizeText(transformText, parameters);

            var transformation = new XmlTransformation(transformText, false, logger);

            try
            {
                foreach (var file in targetFiles)
                {
                    var input = File.ReadAllText(file);

                    var document = new XmlTransformableDocument();
                    document.PreserveWhitespace = preserveWhitespace;

                    document.LoadXml(input);

                    transformation.Apply(document);

                    if (logger.HasErrors)
                    {
                        break;
                    }

                    if (document.IsChanged)
                    {
                        document.Save(file);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new XmlTransformationException(
                          "Transform failed. Log output was: " +
                          string.Join("\n", logger.Messages.Select(x => x.Type.ToString() + ": " + x.Text)), ex);
            }

            return(new TransformResult(logger.Messages.ToArray(), !logger.HasErrors));
        }
コード例 #2
0
        private XDocument ApplyTransformation(string originalConfiguration, string transformationResourceName)
        {
            XDocument result;
            Stream    stream = null;

            try
            {
                stream = typeof(WebConfigTransformTest).Assembly.GetManifestResourceStream(transformationResourceName);
                var document = new XmlTransformableDocument();
                using (var transformation = new XmlTransformation(stream, null))
                {
                    stream = null;
                    document.LoadXml(originalConfiguration);
                    transformation.Apply(document);
                    result = XDocument.Parse(document.OuterXml);
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            return(result);
        }
コード例 #3
0
        private XmlDocument Transform(XmlDocument sourceXml, XmlDocument patchXml)
        {
            var source = new XmlTransformableDocument();

            source.LoadXml(sourceXml.OuterXml);

            var patch = new XmlTransformation(patchXml.OuterXml, false, null);

            patch.Apply(source);

            return(source);
        }
コード例 #4
0
        public String Transform(String sourceXml, String transformXml)
        {
            if (String.IsNullOrEmpty(sourceXml))
            {
                throw new ArgumentNullException("sourceXml");
            }
            if (String.IsNullOrEmpty(transformXml))
            {
                throw new ArgumentNullException("transformXml");
            }

            try
            {
                using (var doc = new XmlTransformableDocument())
                {
                    logger.Debug($"Beginning transformation");

                    doc.PreserveWhitespace = this.PreserveWhitespace;
                    doc.LoadXml(sourceXml);

                    using (var xDoc = new XmlTransformation(transformXml, false, null))
                    {
                        if (xDoc.Apply(doc))
                        {
                            var builder           = new StringBuilder();
                            var xmlWriterSettings = new XmlWriterSettings
                            {
                                Indent      = true,
                                IndentChars = "  "
                            };
                            using (var xmlWriter = XmlTextWriter.Create(builder, xmlWriterSettings))
                            {
                                doc.WriteTo(xmlWriter);
                            }

                            logger.Debug("Successfully transformed document");

                            return(builder.ToString());
                        }
                        else
                        {
                            logger.Warn("Unable to transform - xDoc.Apply failed");
                            throw new XdtTransformException("Unable to transform");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"Unable to transform, exception: {ex.Message}");
                throw new XdtTransformException($"Unable to transform, exception: {ex.Message}", ex);
            }
        }
コード例 #5
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: program.exe <web config XML> <transformation XDT> <expected XML>");
            }
            var webConfigXml = File.ReadAllText(args[0]);
            var transformXml = File.ReadAllText(args[1]);

            var expectedDoc = new XmlDocument();

            expectedDoc.Load(args[2]);
            using (var document = new XmlTransformableDocument())
            {
                document.PreserveWhitespace = true;
                document.LoadXml(webConfigXml);

                using (var transform = new XmlTransformation(transformXml, false, null))
                {
                    if (transform.Apply(document))
                    {
                        var xmlWriterSettings = new XmlWriterSettings();
                        xmlWriterSettings.Indent      = true;
                        xmlWriterSettings.IndentChars = "    ";

                        var  diffBuilder = new StringBuilder();
                        bool bIdentical;
                        using (var diffgramWriter = XmlWriter.Create(diffBuilder, xmlWriterSettings))
                        {
                            var xmldiff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder |
                                                      XmlDiffOptions.IgnoreNamespaces |
                                                      XmlDiffOptions.IgnorePrefixes);
                            bIdentical = xmldiff.Compare(expectedDoc.DocumentElement, document.DocumentElement,
                                                         diffgramWriter);
                        }
                        if (!bIdentical)
                        {
                            Console.Error.WriteLine("Actual differs from expected. Differences are:");
                            Console.Error.WriteLine(diffBuilder.ToString());
                            Environment.Exit(1);
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine("Transformation failed for unkown reason");
                        Environment.Exit(2);
                    }
                }
            }
        }
コード例 #6
0
        public static string GenerateConfig(string newXdt)
        {
            var baseConfig = GetBaseConfig();

            var source = new XmlTransformableDocument();

            source.LoadXml(baseConfig);

            // force default XDT path
            var transform = CreateXmlTransformation(_xdtPath, newXdt);

            transform.Apply(source);

            return(source.ToFormattedString());
        }
コード例 #7
0
        public static string GetCurrentConfig()
        {
            var baseConfig = GetBaseConfig();

            // Apply D:\home\site\applicationHost.xdt
            var source = new XmlTransformableDocument();

            source.LoadXml(baseConfig);

            var transform = CreateXmlTransformation(_xdtPath);

            transform?.Apply(source);

            return(source.ToFormattedString());
        }
 public string Transform(string sourceData, string transformData)
 {
     using (var document = new XmlTransformableDocument())
     {
         document.PreserveWhitespace = true;
         document.LoadXml(sourceData);
         using (var transformation = new XmlTransformation(transformData, false, null))
         {
             if (transformation.Apply(document))
             {
                 return(XElement.Load(new XmlNodeReader(document)).ToString());
             }
         }
     }
     return(null);
 }
コード例 #9
0
        public String Transform(String sourceXml, String transformXml)
        {
            if (String.IsNullOrEmpty(sourceXml))
            {
                throw new ArgumentNullException("sourceXml");
            }
            if (String.IsNullOrEmpty(transformXml))
            {
                throw new ArgumentNullException("transformXml");
            }

            try
            {
                using (var doc = new XmlTransformableDocument())
                {
                    doc.PreserveWhitespace = this.PreserveWhitespace;
                    doc.LoadXml(sourceXml);

                    using (var xDoc = new XmlTransformation(transformXml, false, null))
                    {
                        if (xDoc.Apply(doc))
                        {
                            var builder           = new StringBuilder();
                            var xmlWriterSettings = new XmlWriterSettings
                            {
                                Indent      = true,
                                IndentChars = "  "
                            };
                            using (var xmlWriter = XmlTextWriter.Create(builder, xmlWriterSettings))
                            {
                                doc.WriteTo(xmlWriter);
                            }
                            return(builder.ToString());
                        }
                        else
                        {
                            throw new XdtTransformException("Unable to transform");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new XdtTransformException("Unable to transform", ex);
            }
        }
コード例 #10
0
        private void PrepareForStart()
        {
            if (!Directory.Exists(_wwwroot))
            {
                Directory.CreateDirectory(_wwwroot);
            }

            var binDirectory = Path.Combine(_wwwroot, "bin");

            if (!Directory.Exists(binDirectory))
            {
                Directory.CreateDirectory(binDirectory);
            }

            CopyFileToDirectory(ConfigTransformPath, _wwwroot);
            CopyFileToDirectory(typeof(IisExpress).Assembly.Location, binDirectory);

            var document = new XmlTransformableDocument();

            document.LoadXml(WebConfigTemplate);

            using (var transform = new XmlTransformation(ConfigTransformPath))
            {
                transform.Apply(document);
            }

            var list = document.SelectNodes("//*[@configSource]");

            if (list != null)
            {
                foreach (var node in list.Cast <XmlNode>())
                {
                    var source = document.CreateDocumentFragment();

                    source.InnerXml = File.ReadAllText(node.Attributes["configSource"].Value);

                    var newNode = source.ChildNodes.Cast <XmlNode>().First(x => x.NodeType == XmlNodeType.Element);

                    node.ParentNode.ReplaceChild(newNode, node);
                }
            }

            document.Save(Path.Combine(_wwwroot, "Web.config"));
        }
コード例 #11
0
        public static XDocument Transform(string appConfig, string transformConfig)
        {
            var transformation = new XmlTransformation(transformConfig, false, null);

            var configurationFileDocument = new XmlTransformableDocument();

            configurationFileDocument.LoadXml(appConfig);

            transformation.Apply(configurationFileDocument);

            var sb = new StringBuilder();

            using (var writer = XmlWriter.Create(sb))
            {
                configurationFileDocument.WriteContentTo(writer);
            }

            return(XDocument.Parse(sb.ToString()));
        }
コード例 #12
0
        public void ApplyTransform()
        {
            lock (_lock)
            {
                var logger = new TransformLogger();
                try
                {
                    Log = "";
                    using (var document = new XmlTransformableDocument()
                    {
                        PreserveWhitespace = true
                    })
                        using (var transform = new XmlTransformation(TransformXML, false, logger))
                        {
                            document.LoadXml(SourceXML);

                            if (!transform.Apply(document))
                            {
                                Log           = logger.GetMessages();
                                DiffResultXML = SourceXML;
                            }
                            else
                            {
                                // save to get the final formatting
                                document.Save(new MemoryStream());
                                DiffResultXML = document.OuterXml;
                            }
                        }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + ex.StackTrace);
                    Log           = ex.Message + "\n" + logger.GetMessages();
                    DiffResultXML = SourceXML;
                }
                finally
                {
                    DiffSourceXML = SourceXML;
                }
            }
        }
コード例 #13
0
        public ActionResult Create(string webConfigXml, string transformXml)
        {
            try
            {
                using (var document = new XmlTransformableDocument())
                {
                    document.PreserveWhitespace = true;
                    document.LoadXml(webConfigXml);

                    using (var transform = new XmlTransformation(transformXml, false, null))
                    {
                        if (transform.Apply(document))
                        {
                            var stringBuilder     = new StringBuilder();
                            var xmlWriterSettings = new XmlWriterSettings();
                            xmlWriterSettings.Indent      = true;
                            xmlWriterSettings.IndentChars = "    ";
                            using (var xmlTextWriter = XmlTextWriter.Create(stringBuilder, xmlWriterSettings))
                            {
                                document.WriteTo(xmlTextWriter);
                            }
                            return(Content(stringBuilder.ToString(), "text/xml"));
                        }
                        else
                        {
                            return(ErrorXml("Transformation failed for unkown reason"));
                        }
                    }
                }
            }
            catch (XmlTransformationException xmlTransformationException)
            {
                return(ErrorXml(xmlTransformationException.Message));
            }
            catch (XmlException xmlException)
            {
                return(ErrorXml(xmlException.Message));
            }
        }
コード例 #14
0
        public string Transform(string sourceXml, string transformXml)
        {
            // Remove the BOM (Byte Order Mark) from the source XML if it's there.
            // This will most likely be the case when you try to call this multiple times.
            sourceXml = TrimStart(sourceXml);

            using (var document = new XmlTransformableDocument())
            {
                document.PreserveWhitespace = true;
                document.LoadXml(sourceXml);

                using (var transform = new XmlTransformation(transformXml, false, null))
                {
                    if (transform.Apply(document))
                    {
                        var stringBuilder     = new StringBuilder();
                        var xmlWriterSettings = new XmlWriterSettings();
                        xmlWriterSettings.Indent      = true;
                        xmlWriterSettings.IndentChars = "    ";

                        using (var xmlTextWriter = XmlTextWriter.Create(stringBuilder, xmlWriterSettings))
                            using (var ms = new MemoryStream())
                            {
                                document.Save(ms);
                                ms.Seek(0, SeekOrigin.Begin);
                                ms.Flush();

                                var bytes = ms.ToArray();
                                return(System.Text.Encoding.UTF8.GetString(bytes));
                            }
                    }
                    else
                    {
                        throw new Exception("Transformation failed.");
                    }
                }
            }
        }
コード例 #15
0
        private static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Required Arguments: [ConfigPath] [TransformPath] [TargetPath]");
                return(400);
            }

            WriteVersion();


            var configPath = args[0];

            if (!File.Exists(configPath))

            {
                Console.WriteLine($"Config not found {configPath}");
                return(404);
            }

            var transformPath = args[1];

            if (!File.Exists(transformPath))
            {
                Console.WriteLine($"Transform not found {transformPath}");
                return(404);
            }

            try
            {
                var targetPath   = args[2];
                var configXml    = File.ReadAllText(configPath);
                var transformXml = File.ReadAllText(transformPath);

                Console.WriteLine($"Source File: {configPath}");
                Console.WriteLine($"Transform: {transformPath}");
                Console.WriteLine($"Target: {targetPath}");

                using (var document = new XmlTransformableDocument())

                {
                    document.PreserveWhitespace = true;
                    document.LoadXml(configXml);
                    using (var transform = new XmlTransformation(transformXml, false, null))
                    {
                        if (transform.Apply(document))
                        {
                            var stringBuilder     = new StringBuilder();
                            var xmlWriterSettings = new XmlWriterSettings
                            {
                                Indent      = true,
                                IndentChars = "  "
                            };

                            using (var xmlTextWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
                            {
                                document.WriteTo(xmlTextWriter);
                            }

                            var resultXml = stringBuilder.ToString();
                            File.WriteAllText(targetPath, resultXml);
                            return(0);
                        }

                        Console.WriteLine("Transformation failed for unknown reason");
                    }
                }
            }
            catch (XmlTransformationException xmlTransformationException)
            {
                Console.WriteLine(xmlTransformationException.Message);
            }
            catch (XmlException xmlException)

            {
                Console.WriteLine(xmlException.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(500);
        }