Пример #1
0
        void ApplyTransformation(string configFile, string transformFile, string destinationFile, IXmlTransformationLogger logger)
        {
            var transformation = new XmlTransformation(transformFile, logger);

            var configurationFileDocument = new XmlTransformableDocument()
            {
                PreserveWhitespace = true
            };

            configurationFileDocument.Load(configFile);

            var success = transformation.Apply(configurationFileDocument);

            if (!suppressTransformationErrors && (!success || transformFailed))
            {
                log.ErrorFormat("The XML configuration file {0} failed with transformation file {1}.", configFile, transformFile);
                throw new CommandException(transformWarning);
            }

            if (!configurationFileDocument.ChildNodes.OfType <XmlElement>().Any())
            {
                log.WarnFormat("The XML configuration file {0} no longer has a root element and is invalid after being transformed by {1}", configFile, transformFile);
            }

            configurationFileDocument.Save(destinationFile);
        }
Пример #2
0
        private void Transform_TestRunner_ExpectSuccess(string source, string transform, string baseline, string expectedLog)
        {
            string src                      = CreateATestFile("source.config", source);
            string transformFile            = CreateATestFile("transform.config", transform);
            string baselineFile             = CreateATestFile("baseline.config", baseline);
            string destFile                 = GetTestFilePath("result.config");
            TestTransformationLogger logger = new TestTransformationLogger();

            XmlTransformableDocument x = new XmlTransformableDocument();

            x.PreserveWhitespace = true;
            x.Load(src);

            Microsoft.Web.XmlTransform.XmlTransformation xmlTransform = new Microsoft.Web.XmlTransform.XmlTransformation(transformFile, logger);

            //execute
            bool succeed = xmlTransform.Apply(x);

            x.Save(destFile);
            xmlTransform.Dispose();
            x.Dispose();
            //test
            Assert.AreEqual(true, succeed);
            CompareFiles(baselineFile, destFile);
            CompareMultiLines(ReadResource(expectedLog), logger.LogText);
        }
Пример #3
0
        private XmlTransformableDocument transformConfigurationFile(string baseConfigurationPath, string transformFilePath)
        {
            XmlTransformableDocument doc = new XmlTransformableDocument();

            //Disable DTD's and external entities
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.DtdProcessing = DtdProcessing.Prohibit;
            doc.PreserveWhitespace = true;
            doc.XmlResolver        = null;

            XmlReader reader = null;

            try
            {
                //Configure reader settings
                reader = XmlReader.Create(baseConfigurationPath, settings);
                //Load the document
                doc.Load(reader);

                //Transform the doc
                using (XmlTransformation transform = new XmlTransformation(transformFilePath))
                {
                    var success = transform.Apply(doc);
                }
            }
            finally
            {
                reader?.Dispose();
            }

            return(doc);
        }
Пример #4
0
        public void Transform(string configFilename, string transformFilename, string outputFilename)
        {
            Output?.WriteActionBlock(context, "Applying config transformation",
                                     new Dictionary <string, object> {
                ["Source"]    = configFilename,
                ["Transform"] = transformFilename,
                ["Output"]    = outputFilename,
            });

            try {
                using (var configDoc = new XmlTransformableDocument()) {
                    configDoc.PreserveWhitespace = true;
                    configDoc.Load(configFilename);

                    using (var transformDoc = new XmlTransformation(transformFilename)) {
                        if (!transformDoc.Apply(configDoc))
                        {
                            throw new ApplicationException("Failed to apply config transformation!");
                        }
                    }

                    configDoc.Save(outputFilename);
                }

                //Output?.WriteLine($"Applying configuration transform '{transformFilename}' to config file '{configFilename}'...", ConsoleColor.Gray);
            }
            catch (Exception error) {
                Output?.WriteErrorBlock(context, error.UnfoldMessages());

                throw;
            }
        }
Пример #5
0
        /// <summary>
        /// Processes the transform files.
        /// </summary>
        /// <param name="packageZip">The package zip.</param>
        private void ProcessTransformFiles(ZipArchive packageZip)
        {
            var transformFilesToProcess = packageZip
                                          .Entries
                                          .Where(e => e.FullName.StartsWith(CONTENT_PATH, StringComparison.OrdinalIgnoreCase) || e.FullName.StartsWith(CONTENT_PATH_ALT, StringComparison.OrdinalIgnoreCase))
                                          .Where(e => e.FullName.EndsWith(TRANSFORM_FILE_SUFFIX, StringComparison.OrdinalIgnoreCase));

            foreach (ZipArchiveEntry entry in transformFilesToProcess)
            {
                // process xdt
                string filename            = entry.FullName.ReplaceFirstOccurrence(CONTENT_PATH, string.Empty).ReplaceFirstOccurrence(CONTENT_PATH_ALT, string.Empty);
                string transformTargetFile = Path.Combine(FileManagementHelper.ROOT_PATH, filename.Substring(0, filename.LastIndexOf(TRANSFORM_FILE_SUFFIX)));

                // process transform
                using (XmlTransformableDocument document = new XmlTransformableDocument())
                {
                    document.PreserveWhitespace = true;
                    document.Load(transformTargetFile);

                    using (XmlTransformation transform = new XmlTransformation(entry.Open(), null))
                    {
                        if (transform.Apply(document))
                        {
                            BackupFile(transformTargetFile);
                            document.Save(transformTargetFile);
                        }
                    }
                }
            }
        }
Пример #6
0
        private static string GetBaseConfig()
        {
            var appPoolConfig = Environment.GetEnvironmentVariable("APP_POOL_CONFIG");

            if (appPoolConfig == null)
            {
                return("");
            }

            var source = new XmlTransformableDocument();

            source.Load(appPoolConfig + ".base");

            // Apply site extensions
            var siteExtensions = Environment.ExpandEnvironmentVariables(@"%HOME%\SiteExtensions");

            foreach (var directory in Directory.GetDirectories(siteExtensions))
            {
                var transformMain = CreateXmlTransformation(Path.Combine(directory, "applicationHost.xdt"));

                transformMain?.Apply(source);

                var transformScm = CreateXmlTransformation(Path.Combine(directory, "scmApplicationHost.xdt"));

                transformScm?.Apply(source);
            }

            return(source.ToFormattedString());
        }
Пример #7
0
        public void OkEncodeDecodeReplace()
        {
            // arrange
            var    encryptorDecryptor = new EncryptorDecryptor();
            var    inputFilePath      = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.config");
            var    transformFilePath  = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.Debug.config");
            string result;

            // act
            using (var input = new XmlTransformableDocument())
                using (var transformer = new XmlTransformation(transformFilePath))
                {
                    input.Load(inputFilePath);
                    transformer.Apply(input);

                    using (var stringWriter = new StringWriter())
                        using (var xmlWriter = XmlWriter.Create(stringWriter))
                        {
                            input.WriteContentTo(xmlWriter);
                            xmlWriter.Flush();
                            result = stringWriter.ToString();

                            var xmlDoc = XDocument.Parse(result);

                            var root = xmlDoc.Root;

                            // assert
                            var ecnrypteNode2          = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted2");
                            var ecnrypteNode2Attrubute = ecnrypteNode2.Attribute("serializeAs").Value;
                            encryptorDecryptor.Decrypt(ecnrypteNode2Attrubute).Should().Be("String");
                            var encryptedNode2Value = ecnrypteNode2.Value;
                            encryptorDecryptor.Decrypt(encryptedNode2Value).Should().Be("SomeNewEncryptedValue2");
                        }
                }
        }
Пример #8
0
        /// <inheritdoc/>
        public bool Transform(string source, string transform, string destination)
        {
            // Parameter validation
            Contract.Requires(!string.IsNullOrWhiteSpace(source));
            Contract.Requires(!string.IsNullOrWhiteSpace(transform));
            Contract.Requires(!string.IsNullOrWhiteSpace(destination));

            // File validation
            if (!File.Exists(source))
            {
                throw new FileNotFoundException(Resources.Resources.ErrorMessage_SourceFileNotFound, source);
            }

            if (!File.Exists(transform))
            {
                throw new FileNotFoundException(Resources.Resources.ErrorMessage_TransformFileNotFound, transform);
            }

            using (XmlTransformableDocument document = new XmlTransformableDocument())
                using (XmlTransformation transformation = new XmlTransformation(transform, this.logger))
                {
                    document.PreserveWhitespace = true;
                    document.Load(source);

                    var success = transformation.Apply(document);
                    if (success)
                    {
                        document.Save(destination);
                    }

                    return(success);
                }
        }
Пример #9
0
        /// <summary>
        /// Transforms the XML file.
        /// </summary>
        /// <param name="xmlData">
        /// The package action XML.
        /// </param>
        /// <param name="install">
        /// Install or uninstall?
        /// </param>
        private void Transform(XmlNode xmlData, bool install)
        {
            // Extract paths from XML.
            var fileToTransform    = GetAttributeValue(xmlData, "file");
            var transformAttribute = install
                ? "installTransform"
                : "uninstallTransform";
            var transformFile = GetAttributeValue(xmlData, transformAttribute);


            // Map paths.
            fileToTransform = HostingEnvironment.MapPath(fileToTransform);
            transformFile   = HostingEnvironment.MapPath(transformFile);


            // Transform file.
            using (var doc = new XmlTransformableDocument())
                using (var transform = new XmlTransformation(transformFile))
                {
                    doc.PreserveWhitespace = true;
                    doc.Load(fileToTransform);
                    transform.Apply(doc);
                    doc.Save(fileToTransform);
                }
        }
Пример #10
0
        public static void TransformConfig(FilePath sourceFile, FilePath transformFile, FilePath targetFile)
        {
            if (sourceFile == null)
            {
                throw new ArgumentNullException(nameof(sourceFile), "Source file path is null.");
            }
            if (transformFile == null)
            {
                throw new ArgumentNullException(nameof(transformFile), "Transform file path is null.");
            }
            if (targetFile == null)
            {
                throw new ArgumentNullException(nameof(targetFile), "Target file path is null.");
            }

            using (var document = new XmlTransformableDocument {
                PreserveWhitespace = true
            })
                using (var transform = new XmlTransformation(transformFile.ToString())) {
                    document.Load(sourceFile.ToString());

                    if (!transform.Apply(document))
                    {
                        throw new CakeException(
                                  $"Failed to transform \"{sourceFile}\" using \"{transformFile}\" to \"{targetFile}\""
                                  );
                    }

                    document.Save(targetFile.ToString());
                }
        }
Пример #11
0
        public void PerformTransform(string configFile, string transformFile, string destinationFile)
        {
            var transformFailed  = false;
            var transformWarning = "";
            var logger           = new VerboseTransformLogger(_suppressTransformationErrors, _suppressTransformationLogging);

            logger.Warning += (sender, args) =>
            {
                transformWarning = args.Message;
                transformFailed  = true;
            };
            if (_suppressTransformationErrors)
            {
                Log.Info("XML Transformation warnings will be suppressed.");
            }

            var transformation = new XmlTransformation(transformFile, logger);

            var configurationFileDocument = new XmlTransformableDocument();

            configurationFileDocument.PreserveWhitespace = true;
            configurationFileDocument.Load(configFile);

            var success = transformation.Apply(configurationFileDocument);

            if (!_suppressTransformationErrors && (!success || transformFailed))
            {
                Log.ErrorFormat("The XML configuration file {0} failed with transformation file {1}.", configFile, transformFile);
                throw new CommandException(transformWarning);
            }

            configurationFileDocument.Save(destinationFile);
        }
Пример #12
0
        public static void TransformConfig(string configFileName, string transformFileName)
        {
            try
            {
                using (var document = new XmlTransformableDocument())
                {
                    document.PreserveWhitespace = true;
                    document.Load(configFileName);

                    using (var transform = new XmlTransformation(transformFileName))
                    {
                        if (transform.Apply(document))
                        {
                            document.Save(configFileName);
                        }
                        else
                        {
                            throw new Exception("Transformation Failed");
                        }
                    }
                }
            }
            catch (Exception xmlException)
            {
                Console.WriteLine(xmlException.Message);
            }
        }
Пример #13
0
        static void Transform_ExpectFail(string baseFileName)
        {
            string src           = TestResource($"{baseFileName}_source.xml");
            string transformFile = TestResource($"{baseFileName}_transform.xml");
            string destFile      = OutputFile("result.xml", baseFileName);
            string expectedLog   = TestResource($"{baseFileName}.log");
            var    logger        = new TestTransformationLogger();

            bool succeed;

            using (var x = new XmlTransformableDocument {
                PreserveWhitespace = true
            })
            {
                x.Load(src);

                using (var xmlTransform = new XmlTransformation(transformFile, logger))
                {
                    //execute
                    succeed = xmlTransform.Apply(x);
                    x.Save(destFile);
                }
            }

            //test
            Assert.False(succeed, baseFileName);
            Assert.Equal(File.ReadAllText(expectedLog), logger.LogText);
        }
Пример #14
0
        static void Transform_ExpectSuccess(string baseFileName)
        {
            string src           = TestResource($"{baseFileName}_source.xml");
            string transformFile = TestResource($"{baseFileName}_transform.xml");
            string baselineFile  = TestResource($"{baseFileName}_baseline.xml");
            string destFile      = OutputFile("result.xml", baseFileName);
            string expectedLog   = TestResource($"{baseFileName}.log");
            var    logger        = new TestTransformationLogger();

            bool applied;

            using (var x = new XmlTransformableDocument {
                PreserveWhitespace = true
            })
            {
                x.Load(src);

                using (var xmlTransform = new XmlTransformation(transformFile, logger))
                {
                    //execute
                    applied = xmlTransform.Apply(x);
                    x.Save(destFile);
                }
            }

            //test
            applied.ShouldBeTrue(baseFileName);
            File.ReadAllText(destFile).ShouldBe(File.ReadAllText(baselineFile));
            logger.LogText.ShouldBe(File.ReadAllText(expectedLog));
        }
Пример #15
0
        /// <summary>
        /// Transform the web.config to inject the maximum allowed content length
        /// into the requestLimits tag of the requestFiltering section of the web.config.
        /// </summary>
        /// <returns>true if the transform was successful; false otherwise.</returns>
        protected bool SaveMaxAllowedContentLength()
        {
            string webConfig = System.Web.HttpContext.Current.Server.MapPath(Path.Combine("~", "web.config"));
            bool   isSuccess = false;

            using (XmlTransformableDocument document = new XmlTransformableDocument())
            {
                document.PreserveWhitespace = true;
                document.Load(webConfig);

                int maxContentLengthBytes = int.Parse(numbMaxSize.Text) * 1048576;

                string transformString = string.Format(@"<?xml version='1.0'?>
<configuration xmlns:xdt='http://schemas.microsoft.com/XML-Document-Transform'>  
    <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength='{0}' xdt:Transform='SetAttributes(maxAllowedContentLength)'/>
      </requestFiltering>
    </security>
    </system.webServer>
</configuration>", maxContentLengthBytes);

                using (XmlTransformation transform = new XmlTransformation(transformString, false, null))
                {
                    isSuccess = transform.Apply(document);
                    document.Save(webConfig);
                }
            }

            return(isSuccess);
        }
Пример #16
0
        public override bool Execute()
        {
            Log.LogMessage("Begin TransformXmlFiles");

            if (TransformFiles?.Any() ?? false)
            {
                Log.LogMessage("Creating Microsoft.Web.Publishing.Tasks.TransformXml");

                foreach (var inputFile in TransformFiles)
                {
                    Log.LogMessage($"Preparing to transform '{inputFile.ItemSpec}'");

                    //Get the env name
                    var fileParts = Path.GetFileNameWithoutExtension(inputFile.ItemSpec).Split('.');
                    var envName   = fileParts.LastOrDefault();

                    //Build output directory as base output directory plus environment plus project (if supplied)
                    var outDir = Path.Combine(OutputDirectory, envName);
                    if (!String.IsNullOrEmpty(ProjectName))
                    {
                        outDir = Path.Combine(outDir, ProjectName);
                    }

                    //Build the output path
                    var outFile = Path.Combine(outDir, TargetFile);

                    //Make sure the directory exists
                    if (!Directory.Exists(outDir))
                    {
                        Log.LogMessage($"Creating directory '{outDir}'");
                        Directory.CreateDirectory(outDir);
                    }
                    ;

                    //Transform the config
                    var transform      = new XmlTransformation(inputFile.ItemSpec);
                    var sourceDocument = new XmlTransformableDocument()
                    {
                        PreserveWhitespace = true
                    };
                    sourceDocument.Load(SourceFile);

                    Log.LogMessage($"Transforming file");
                    if (transform.Apply(sourceDocument))
                    {
                        sourceDocument.Save(outFile);
                    }
                    else
                    {
                        Log.LogError($"Error transforming file");
                        return(false);
                    };
                }
                ;
            }
            ;

            Log.LogMessage("End TransformXmlFiles");
            return(true);
        }
        /// <summary>
        /// Transforms config file.
        /// </summary>
        /// <param name="fileSystem">The filesystem.</param>
        /// <param name="sourceFile">Source config file.</param>
        /// <param name="transformFile">Tranformation to apply.</param>
        /// <param name="targetFile">Target config file.</param>
        /// <param name="logger">Logger for the transfomration process</param>
        public static void TransformConfig(IFileSystem fileSystem, FilePath sourceFile, FilePath transformFile, FilePath targetFile, IXmlTransformationLogger logger = null)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException(nameof(fileSystem), "File system is null.");
            }
            CheckNulls(sourceFile, transformFile, targetFile);

            IFile
                sourceConfigFile    = fileSystem.GetFile(sourceFile),
                transformConfigFile = fileSystem.GetFile(transformFile),
                targetConfigFile    = fileSystem.GetFile(targetFile);

            using (Stream
                   sourceStream = sourceConfigFile.OpenRead(),
                   transformStream = transformConfigFile.OpenRead(),
                   targetStream = targetConfigFile.OpenWrite())
                using (var document = new XmlTransformableDocument {
                    PreserveWhitespace = true
                })
                    using (var transform = new XmlTransformation(transformStream, logger))
                    {
                        document.Load(sourceStream);

                        if (!transform.Apply(document))
                        {
                            throw new CakeException(
                                      $"Failed to transform \"{sourceFile}\" using \"{transformFile}\" to \"{targetFile}\""
                                      );
                        }

                        document.Save(targetStream);
                    }
        }
Пример #18
0
        private XmlTransformableDocument OpenSourceFile(string sourceFile)
        {
            XmlTransformableDocument xmlTransformableDocument;

            try
            {
                XmlTransformableDocument xmlTransformableDocument1 = new XmlTransformableDocument()
                {
                    PreserveWhitespace = true
                };
                xmlTransformableDocument1.Load(sourceFile);
                xmlTransformableDocument = xmlTransformableDocument1;
            }
            catch (XmlException xmlException)
            {
                throw;
            }
            catch (Exception exception1)
            {
                Exception   exception      = exception1;
                CultureInfo currentCulture = CultureInfo.CurrentCulture;
                string      bUILDTASKTransformXmlSourceLoadFailed = "Could not open Source file: {0}";
                object[]    message = new object[] { exception.Message };
                throw new Exception(string.Format(currentCulture, bUILDTASKTransformXmlSourceLoadFailed, message), exception);
            }
            return(xmlTransformableDocument);
        }
        static public void XMLTransform(String sourceFile, String destinationFile, String transformFile, bool isDryRun = false)
        {
            String outFile = destinationFile;

            if (String.IsNullOrWhiteSpace(outFile))
            {
                outFile = sourceFile;
            }

            using (XmlTransformableDocument doc = new XmlTransformableDocument())
            {
                doc.PreserveWhitespace = true;

                using (io.StreamReader sr = new io.StreamReader(sourceFile))
                {
                    doc.Load(sr);
                }

                using (XmlTransformation xt = new XmlTransformation(transformFile))
                {
                    xt.Apply(doc);
                    if (!isDryRun)
                    {
                        doc.Save(outFile);
                    }
                }
            }
        }
Пример #20
0
 private void transformToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         using (var xmlDoc = new XmlTransformableDocument())
         {
             xmlDoc.PreserveWhitespace = true;
             xmlDoc.Load(new MemoryStream(Encoding.ASCII.GetBytes(fastColoredTextBoxSource.Text)));
             var logger = new TransformationLogger();
             using (var xmlTrans = new XmlTransformation(new MemoryStream(Encoding.ASCII.GetBytes(fastColoredTextBoxXDT.Text)), logger))
             {
                 if (xmlTrans.Apply(xmlDoc))
                 {
                     fastColoredTextBoxTransformed.Text = xmlDoc.OuterXml;
                 }
                 if (!string.IsNullOrEmpty(logger.Content))
                 {
                     Message(logger.Content);
                 }
             }
             tabControl1.SelectedIndex = 3;
         }
     }
     catch (Exception ex)
     {
         Message(ex.ToString());
     }
 }
        /// <summary>
        /// Validates the specified <paramref name="transformation"/> against the specififed <paramref name="source"/>.
        /// </summary>
        /// <param name="source">The name and location of the source file to apply the transformation against.</param>
        /// <param name="transformation">The name and location of the transformation file to apply against the source.</param>
        /// <param name="treatWarningsAsError"><b>true</b> if warnings should be logged as errors; otherwise <b>false</b>.</param>
        /// <returns><b>true</b> if the transformation was successful; otherwise <b>false</b>.</returns>
        /// <remarks>The <see cref="ErrorLog"/> and <see cref="VerboseLog"/> properties can be used to determine the steps the transformation has done and any errors that occurred.</remarks>
        public bool Validate(string source, string transformation, bool treatWarningsAsError)
        {
            if (string.IsNullOrEmpty(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrEmpty(transformation))
            {
                throw new ArgumentNullException(nameof(transformation));
            }

            this.transformationLogger = new XmlTransformationLogger(false, treatWarningsAsError);

            this.transformationLogger.LogMessage(MessageType.Verbose, "Applying transformations '{0}' on file '{1}'...", Path.GetFileName(transformation), Path.GetFileName(source));

            var sourceDocument = new XmlTransformableDocument {
                PreserveWhitespace = true
            };

            sourceDocument.Load(source);

            var xmlTransformation = new XmlTransformation(transformation, this.transformationLogger);

            if (!xmlTransformation.Apply(sourceDocument) || this.transformationLogger.HasLoggedErrors)
            {
                this.transformationLogger.LogMessage(MessageType.Normal, "Error while applying transformations '{0}'.", Path.GetFileName(transformation),
                                                     source);
                return(false);
            }
            return(true);
        }
Пример #22
0
        void ApplyTransformation(string configFile, string transformFile, string destinationFile, IXmlTransformationLogger logger)
        {
            errorEncountered = false;
            var transformation = new XmlTransformation(transformFile, logger);

            var configurationFileDocument = new XmlTransformableDocument()
            {
                PreserveWhitespace = true
            };

            configurationFileDocument.Load(configFile);

            var success = transformation.Apply(configurationFileDocument);

            if (!success || errorEncountered)
            {
                throw new CommandException($"The XML configuration file {configFile} failed with transformation file {transformFile}.");
            }

            if (!configurationFileDocument.ChildNodes.OfType <XmlElement>().Any())
            {
                logger.LogWarning("The XML configuration file {0} no longer has a root element and is invalid after being transformed by {1}", new object[] { configFile, transformFile });
            }

            configurationFileDocument.Save(destinationFile);
        }
Пример #23
0
        private void Transform_TestRunner_ExpectFail(string source, string transform, string expectedLog)
        {
            string src           = CreateATestFile("source.config", source);
            string transformFile = CreateATestFile("transform.config", transform);
            string destFile      = GetTestFilePath("result.config");
            var    logger        = new TestTransformationLogger();

            bool succeed;

            using (var x = new XmlTransformableDocument())
            {
                x.PreserveWhitespace = true;
                x.Load(src);

                using (var xmlTransform = new XmlTransformation(transformFile, logger))
                {
                    succeed = xmlTransform.Apply(x);
                    x.Save(destFile);
                }
            }

            //test
            Assert.AreEqual(false, succeed);
            CompareMultiLines(expectedLog, logger.LogText);
        }
Пример #24
0
        static int Main(string[] args)
        {
            var version = Assembly.GetEntryAssembly().GetName().Version;

            Console.WriteLine(
                "==================\n"
                + string.Format(" FatAntelope v{0}.{1}\n", version.Major, version.Minor)
                + "==================\n");

            if (args == null || args.Length < 3 || args.Length > 4)
            {
                Console.WriteLine(
                    "Error: Unexpected number of paramters.\n"
                    + "Usage: FatAntelope source-file target-file output-file [transformed-file]\n"
                    + "  source-file : (Input) The original config file\n"
                    + "  target-file : (Input) The final config file\n"
                    + "  output-file : (Output) The output config transform patch file\n"
                    + "  transformed-file : (Optional Output) The config file resulting from applying the output-file to the source-file\n"
                    + "                     This file should be semantically equal to the target-file.\n");
                return((int)ExitCode.InvalidParameters);
            }

            Console.WriteLine("- Building xml trees . . .\n");
            var tree1 = BuildTree(args[0]);
            var tree2 = BuildTree(args[1]);

            Console.WriteLine("- Comparing xml trees . . .\n");
            XDiff.Diff(tree1, tree2);
            if (tree1.Root.Match == MatchType.Match && tree2.Root.Match == MatchType.Match && tree1.Root.Matching == tree2.Root)
            {
                Console.WriteLine("Warning: No difference found!\n");
                return((int)ExitCode.NoDifference);
            }

            if (tree1.Root.Match == MatchType.NoMatch || tree2.Root.Match == MatchType.NoMatch)
            {
                Console.Error.WriteLine("Error: Root nodes must have the same name!\n");
                return((int)ExitCode.RootNodeMismatch);
            }

            Console.WriteLine("- Writing XDT transform . . .\n");
            var writer = new XdtDiffWriter();
            var patch  = writer.GetDiff(tree2);

            patch.Save(args[2]);

            if (args.Length > 3)
            {
                Console.WriteLine("- Applying transform to source . . .\n");
                var source = new XmlTransformableDocument();
                source.Load(args[0]);

                var transform = new XmlTransformation(patch.OuterXml, false, null);
                transform.Apply(source);

                source.Save(args[3]);
            }
            Console.WriteLine("- Finished successfully!\n");
            return((int)ExitCode.Success);
        }
Пример #25
0
        private static XmlTransformableDocument LoadSourceFile(string fileToTransform)
        {
            var source = new XmlTransformableDocument {
                PreserveWhitespace = false
            };

            source.Load(fileToTransform);
            return(source);
        }
Пример #26
0
        /// <summary>
        /// Opens the original config file to which the transformations should be applied.
        /// </summary>
        /// <param name="sourceFile">the path to the source config file.</param>
        /// <returns>the source file as a <see cref="XmlTransformableDocument"/>.</returns>
        private static XmlTransformableDocument OpenSourceFile(string sourceFile)
        {
            XmlTransformableDocument innerDoc = new XmlTransformableDocument {
                PreserveWhitespace = true
            };

            innerDoc.Load(sourceFile);
            return(innerDoc);
        }
Пример #27
0
        /// <inheritdoc />
        protected override void BeginProcessing()
        {
            if (!File.Exists(Path))
            {
                throw new FileNotFoundException(Path);
            }

            using (var appConfig = File.OpenRead(Path))
            {
                _configDocument.Load(appConfig);
            }
        }
Пример #28
0
        public static void Transform(
            this Paths paths
            )
        {
            var transformFiles = paths.GetTransformFiles();

            // preserving whitespace seems buggy when not
            // letting the library handle streams itself
            // looked through the MS source, did not see a reason
            // why this was this case
            using var document = new XmlTransformableDocument {
                      PreserveWhitespace = paths.Source == paths.Target
                  };
            document.Load(paths.Source);

            foreach (var transformFile in transformFiles)
            {
                using var transform = new XmlTransformation(transformFile);
                if (transform.Apply(document))
                {
                    Console.WriteLine(Invariant($" Applied: {transformFile}"));
                }
                else
                {
                    Console.WriteLine(Invariant($" Failed: {transformFile}"));
                    Console.WriteLine("Exiting..");
                    return;
                }
            }

            // the Save function does not Dispose its underlying Stream right away
            // but, using custom Stream objects and calling dispose on them
            // cannot be done because of issue above with whitespace
            // retries are not limited, since users can kill this program if they want
            var saved = false;

            Console.Write(" Saving..");
            while (!saved)
            {
                try {
                    document.Save(paths.Target);
                    saved = true;
                } catch (IOException) {
                    Console.Write(".");
                }
                Thread.Sleep(100);
            }
            Console.WriteLine();

            Console.WriteLine(Invariant($" Saved: {paths.Target}"));
        }
Пример #29
0
        private static void PerformXdtTransform(IPackageFile file, string targetPath, IProjectSystem projectSystem)
        {
            if (projectSystem.FileExists(targetPath))
            {
                string content = Preprocessor.Process(file, projectSystem);

                try
                {
                    using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null))
                    {
                        using (var document = new XmlTransformableDocument())
                        {
                            document.PreserveWhitespace = true;

                            // make sure we close the input stream immediately so that we can override
                            // the file below when we save to it.
                            using (var inputStream = projectSystem.OpenFile(targetPath))
                            {
                                document.Load(inputStream);
                            }

                            bool succeeded = transformation.Apply(document);
                            if (succeeded)
                            {
                                using (var memoryStream = new MemoryStream())
                                {
                                    // save the result into a memoryStream first so that if there is any
                                    // exception during document.Save(), the original file won't be truncated.
                                    document.Save(memoryStream);
                                    memoryStream.Seek(0, SeekOrigin.Begin);
                                    using (var fileStream = projectSystem.CreateFile(targetPath))
                                    {
                                        memoryStream.CopyTo(fileStream);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new InvalidDataException(
                              String.Format(
                                  CultureInfo.CurrentCulture,
                                  NuGetResources.XdtError + " " + exception.Message,
                                  targetPath,
                                  projectSystem.ProjectName),
                              exception);
                }
            }
        }
            private bool Transform(string packageName, System.Xml.XmlNode xmlData, bool uninstall = false)
            {
                // The config file we want to modify
                if (xmlData.Attributes != null)
                {
                    var file = xmlData.Attributes.GetNamedItem("file").Value;

                    var sourceDocFileName = VirtualPathUtility.ToAbsolute(file);

                    // The xdt file used for tranformation
                    var fileEnd = "install.xdt";
                    if (uninstall)
                    {
                        fileEnd = string.Format("un{0}", fileEnd);
                    }

                    var xdtfile     = string.Format("{0}.{1}", xmlData.Attributes.GetNamedItem("xdtfile").Value, fileEnd);
                    var xdtFileName = VirtualPathUtility.ToAbsolute(xdtfile);

                    // The translation at-hand
                    using (var xmlDoc = new XmlTransformableDocument())
                    {
                        xmlDoc.PreserveWhitespace = true;
                        xmlDoc.Load(HttpContext.Current.Server.MapPath(sourceDocFileName));

                        using (var xmlTrans = new XmlTransformation(HttpContext.Current.Server.MapPath(xdtFileName)))
                        {
                            if (xmlTrans.Apply(xmlDoc))
                            {
                                // If we made it here, sourceDoc now has transDoc's changes
                                // applied. So, we're going to save the final result off to
                                // destDoc.
                                try
                                {
                                    xmlDoc.Save(HttpContext.Current.Server.MapPath(sourceDocFileName));
                                }
                                catch (Exception e)
                                {
                                    // Log error message
                                    var message = "Error executing TransformConfig package action (check file write permissions): " + e.Message;
                                    LogHelper.Error(typeof(TransformConfig), message, e);
                                    return(false);
                                }
                            }
                        }
                    }
                }

                return(true);
            }
Пример #31
0
        private static void load_areas(ControllerResolver resolver)
        {
            List<string> privateBins = new List<string>() { "bin" };

            MethodInfo m = null, funsion = null;

            // check if i am running under mono at runtime. bad coding style
            bool isMono = Type.GetType("Mono.Runtime") != null;

            if (!isMono)
            {
                m = typeof(AppDomainSetup).GetMethod("UpdateContextProperty", BindingFlags.NonPublic | BindingFlags.Static);
                funsion = typeof(AppDomain).GetMethod("GetFusionContext", BindingFlags.NonPublic | BindingFlags.Instance);
            }

            foreach (var dir in Directory.GetDirectories(ServerUtil.MapPath("~")))
            {
                string areaName = Path.GetFileName(dir).ToLowerInvariant();

                if (IGNORES_DIR.Contains(areaName))
                    continue;

                // check if the dir is a valid area
                string configfile = Path.Combine(dir, "area.config");
                if (!File.Exists(configfile))
                    continue;

                // load area config
                XmlNode node = null;

                using (XmlTransformableDocument x = new XmlTransformableDocument())
                {
                    x.Load(configfile);

                    string localfile = Path.Combine(dir, "area.local.config");

                    if (File.Exists(localfile))
                    {
                        using (XmlTransformation t = new XmlTransformation(localfile))
                        {
                            t.Apply(x);
                        }
                    }

                    node = x.DocumentElement;
                }

                AreaConfig config = AreaConfig.GetConfig(node);
                config.VP = "/" + areaName;
                config.AreaKey = areaName;

                Areas.Add(@"/" + areaName, config);

                // load assemblies
                string bindir = Path.Combine(dir, "bin");

                if (Directory.Exists(bindir))
                {
                    privateBins.Add(bindir);

                    if (!isMono)
                    {
                        // hack !!!
                        if (m != null && funsion != null)
                        {
                            m.Invoke(null, new object[] { funsion.Invoke(AppDomain.CurrentDomain, null), "PRIVATE_BINPATH", privateBins.Join(";") });
                            m.Invoke(null, new object[] { funsion.Invoke(AppDomain.CurrentDomain, null), "SHADOW_COPY_DIRS", privateBins.Join(";") });
                        }
                    }

                    List<Assembly> assemblies = new List<Assembly>();

                    foreach (var item in Directory.GetFiles(bindir, "*.dll", SearchOption.TopDirectoryOnly))
                    {
                        try
                        {
                            if (isMono)
                                assemblies.Add(Assembly.Load(File.ReadAllBytes(item)));
                            else
                                assemblies.Add(AppDomain.CurrentDomain.Load(Path.GetFileNameWithoutExtension(item)));
                        }
                        catch (BadImageFormatException)
                        {
                        }
                    }

                    Dictionary<string, Type> types = new Dictionary<string, Type>();
                    foreach (var asm in assemblies)
                    {
                        foreach (var item in resolver.GetsControllerFromAssembly(asm))
                        {
                            types[item.Key] = item.Value;
                        }
                    }
                    resolver.SetSiteControllers(areaName, types);
                }
            }
        }
Пример #32
0
        static void Main(string[] args)
        {
            Console.WriteLine("TransformXml.exe source.xml transform.xml destination.xml");

            var inputStream = new MemoryStream(File.ReadAllBytes(args[0]));

            XmlTransformableDocument document = new XmlTransformableDocument();
            document.PreserveWhitespace = true;
            document.Load(inputStream);

            XmlTransformation transformation;
            transformation = new XmlTransformation(args[1], new Logger());

            transformation.Apply(document);

            document.Save(args[2]);
        }
Пример #33
0
        private void Transform_TestRunner_ExpectFail(string source, string transform, string expectedLog)
        {
            string src = CreateATestFile("source.config", source);
            string transformFile = CreateATestFile("transform.config", transform);
            string destFile = GetTestFilePath("result.config");
            TestTransformationLogger logger = new TestTransformationLogger();

            XmlTransformableDocument x = new XmlTransformableDocument();
            x.PreserveWhitespace = true;
            x.Load(src);

            Microsoft.Web.XmlTransform.XmlTransformation xmlTransform = new Microsoft.Web.XmlTransform.XmlTransformation(transformFile, logger);

            //execute
            bool succeed = xmlTransform.Apply(x);
            x.Save(destFile);
            xmlTransform.Dispose();
            x.Dispose();
            //test
            Assert.AreEqual(false, succeed);
            CompareMultiLines(expectedLog, logger.LogText);
        }
 private XmlTransformableDocument GetSourceFile(string filePath)
 {
     try
     {
         using (var textReader = this.filesystemAccessor.GetTextReader(filePath))
         {
             var transformableDocument = new XmlTransformableDocument { PreserveWhitespace = true };
             transformableDocument.Load(textReader);
             return transformableDocument;
         }
     }
     catch (Exception)
     {
         return null;
     }
 }