示例#1
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());
     }
 }
示例#2
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");
                        }
                }
        }
示例#3
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.True(succeed);
            CompareFiles(destFile, baselineFile);
            CompareMultiLines(expectedLog, logger.LogText);
        }
示例#4
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);
        }
示例#5
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);
        }
示例#6
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);
        }
示例#7
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);
        }
示例#8
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.Replace(CONTENT_PATH, string.Empty).Replace(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);
                        }
                    }
                }
            }
        }
        /// <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>
        public static void TransformConfig(IFileSystem fileSystem, FilePath sourceFile, FilePath transformFile, FilePath targetFile)
        {
            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, null))
                    {
                        document.Load(sourceStream);

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

                        document.Save(targetStream);
                    }
        }
示例#10
0
        private static XmlTransformableDocument LoadSourceFile(string fileToTransform)
        {
            var source = new XmlTransformableDocument {
                PreserveWhitespace = false
            };

            source.Load(fileToTransform);
            return(source);
        }
示例#11
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);
        }
示例#12
0
 private void SaveTransformedFile(XmlTransformableDocument document, string destinationFile)
 {
     try {
         document.Save(destinationFile);
     }
     catch (System.Xml.XmlException) {
         throw;
     }
     catch (Exception ex) {
         throw new Exception(string.Format("Could not write Destination file: {0}", ex.Message), ex);
     }
 }
示例#13
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);
            }
        }
示例#14
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);
        }
示例#15
0
        public void ApplyTo(XmlTransformableDocument target)
        {
            using (var ms = new MemoryStream())
            {
                this.document.Save(ms);

                ms.Seek(0, SeekOrigin.Begin);

                var transformation = new XmlTransformation(ms, this.Logger);

                transformation.Apply(target);
            }
        }
示例#16
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);
                }
            }
        }
示例#17
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}"));
        }
            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);
            }
示例#19
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);
                    }
                }
            }
        }
示例#20
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            var sourceFile = tbSourceConfigFile.Text;

            if (string.IsNullOrEmpty(sourceFile))
            {
                MessageBox.Show("Source file path is empty.");
                return;
            }
            if (!File.Exists(sourceFile))
            {
                MessageBox.Show("Source file do not exist.");
                return;
            }

            var transformFile = tbTransformConfigFile.Text;

            if (string.IsNullOrEmpty(transformFile))
            {
                MessageBox.Show("Transform file path is empty.");
                return;
            }
            if (!File.Exists(transformFile))
            {
                MessageBox.Show("Transform file do not exist.");
                return;
            }

            var resultFile = tbResultConfigFile.Text;

            if (string.IsNullOrEmpty(resultFile))
            {
                MessageBox.Show("Result file path is not specified.");
                return;
            }

            using var doc = new XmlTransformableDocument();
            doc.Load(sourceFile);
            using var tranform = new XmlTransformation(transformFile);
            if (tranform.Apply(doc))
            {
                doc.Save(resultFile);
                MessageBox.Show("OK!");
            }
            else
            {
                MessageBox.Show("Could not apply transform.");
            }
        }
示例#21
0
        public void Execute(Model.ConfigurationFile file)
        {
            var fiProductionConfigurationPath = new FileInfo(file.ProductionConfigurationPath);

            //Remove old file if one exists
            if (fiProductionConfigurationPath.Exists)
            {
                fiProductionConfigurationPath.Delete();
            }

            //Apply the transform and save to disk
            XmlTransformableDocument doc = transformConfigurationFile(file.BaseConfigurationPath, file.ProductionTransformPath);

            doc.Save(file.ProductionConfigurationPath);
        }
示例#22
0
        private static (int result, XmlTransformableDocument xml) TransformConfig(
            string configPath,
            string transformPath)
        {
            var document = new XmlTransformableDocument {
                PreserveWhitespace = true
            };

            document.Load(configPath);

            var transformation = new XmlTransformation(transformPath);

            return(transformation.Apply(document)
                ? (0, document)
                : (1, default));
示例#23
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());
        }
示例#24
0
 public void Run()
 {
     Logger.Info(this, "Transforming " + this._sourceFile + " using " + this._transformationfile + " to " + this._targetFile + "...");
     using (XmlTransformableDocument document = new XmlTransformableDocument()) {
         document.PreserveWhitespace = true;
         document.Load(this._sourceFile);
         using (XmlTransformation transform = new XmlTransformation(this._transformationfile)) {
             transform.Apply(document);
             Logger.Debug(this, "Result");
             Logger.Debug(this, document.OuterXml);
             document.Save(this._targetFile);
             Logger.Info(this, "Saved to " + this._targetFile);
         }
     }
 }
示例#25
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());
        }
示例#26
0
        public static void TransformConfig(string configFileName, string transformFileName, string targetFileName)
        {
            var document = new XmlTransformableDocument();

            document.PreserveWhitespace = true;
            document.Load(configFileName);

            var transformation = new XmlTransformation(transformFileName);

            if (!transformation.Apply(document))
            {
                throw new Exception("Transformation Failed");
            }
            document.Save(targetFileName);
        }
示例#27
0
        /// <inheritdoc/>
        public bool Transform(string sourcePath, string transformPath, string destinationPath)
        {
            if (string.IsNullOrWhiteSpace(sourcePath))
            {
                throw new ArgumentNullException(nameof(sourcePath));
            }

            if (string.IsNullOrWhiteSpace(sourcePath))
            {
                throw new ArgumentNullException(nameof(transformPath));
            }

            if (string.IsNullOrWhiteSpace(sourcePath))
            {
                throw new ArgumentNullException(nameof(destinationPath));
            }

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

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

            using (XmlTransformableDocument document = new XmlTransformableDocument())
                using (XmlTransformation transformation = new XmlTransformation(transformPath, this.logger))
                {
                    using (XmlTextReader reader = new XmlTextReader(sourcePath))
                    {
                        reader.DtdProcessing = DtdProcessing.Ignore;

                        document.PreserveWhitespace = true;
                        document.Load(reader);
                    }

                    var success = transformation.Apply(document);

                    if (success)
                    {
                        document.Save(destinationPath);
                    }

                    return(success);
                }
        }
 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);
 }
示例#29
0
        //public static void ApplyWeb(string configFilename, string outputFilename)
        //{
        //    PathEx.Delete(outputFilename);
        //    File.Copy(configFilename, outputFilename);
        //}

        public static void Transform(string configFilename, string transformFilename, string outputFilename)
        {
            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);
            }
        }
        internal static async Task PerformXdtTransformAsync(
            Func <Task <Stream> > streamTaskFactory,
            string targetPath,
            IMSBuildProjectSystem msBuildNuGetProjectSystem,
            CancellationToken cancellationToken)
        {
            if (FileSystemUtility.FileExists(msBuildNuGetProjectSystem.ProjectFullPath, targetPath))
            {
                var content = await Preprocessor.ProcessAsync(streamTaskFactory, msBuildNuGetProjectSystem, cancellationToken);

                try
                {
                    using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null))
                    {
                        using (var document = new XmlTransformableDocument())
                        {
                            // make sure we close the input stream immediately so that we can override
                            // the file below when we save to it.
                            string path = FileSystemUtility.GetFullPath(msBuildNuGetProjectSystem.ProjectFullPath, targetPath);
                            using (FileStream fileStream = File.OpenRead(path))
                            {
                                using var xmlReader = XmlReader.Create(fileStream, GetXmlReaderSettings(LoadOptions.PreserveWhitespace));
                                document.Load(xmlReader);
                            }

                            var succeeded = transformation.Apply(document);
                            if (succeeded)
                            {
                                // save the result into a memoryStream first so that if there is any
                                // exception during document.Save(), the original file won't be truncated.
                                MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, targetPath, document.Save);
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new InvalidDataException(
                              string.Format(
                                  CultureInfo.CurrentCulture,
                                  Strings.XdtError + " " + exception.Message,
                                  targetPath,
                                  msBuildNuGetProjectSystem.ProjectName),
                              exception);
                }
            }
        }
 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;
     }
 }
        private IServiceResult SaveTransformedFile(XmlTransformableDocument transformedDocument, string destinationFilePath)
        {
            try
            {
                this.filesystemAccessor.EnsureParentDirectoryExists(destinationFilePath);
                using (var textWriter = this.filesystemAccessor.GetTextWriter(destinationFilePath))
                {
                    transformedDocument.Save(textWriter);
                }

                return new SuccessResult(Resources.ConfigurationFileTransformationService.SaveSucceededMessageTemplate, destinationFilePath);
            }
            catch (Exception saveException)
            {
                return new FailureResult(
                    Resources.ConfigurationFileTransformationService.SaveFailedWithExceptionMessageTemplate, destinationFilePath, saveException.Message);
            }
        }
        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);
                }
            }
        }
示例#34
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]);
        }
示例#35
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);
        }