protected override void ProcessRecord()
        {
            this.TransformPath = this.TransformPath.Select(this.GetUnresolvedProviderPathFromPSPath).ToArray();

            foreach (var t in this.TransformPath)
            {
                if (!File.Exists(t))
                {
                    throw new FileNotFoundException($"A transform, '{t}', could not be found.");
                }
            }

            foreach (var t in this.TransformPath)
            {
                using (var transformation = new XmlTransformation(t))
                {
                    this.WriteVerbose($"Applying '{t}' transform...");

                    if (!transformation.Apply(this._Document))
                    {
                        throw new Microsoft.Web.XmlTransform.XmlTransformationException($"Failed to apply transform '{t}'.");
                    }
                }
            }
        }
Exemple #2
0
        private XmlTransformableDocument transformConfigurationFile(string baseConfigurationPath, string transformFilePath)
        {
            using (XmlTransformableDocument doc = new XmlTransformableDocument())
            {
                //Disable DTD's and external entities
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.DtdProcessing = DtdProcessing.Prohibit;
                doc.PreserveWhitespace = true;
                doc.XmlResolver        = null;

                //Configure reader settings
                using (XmlReader 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);
                    }
                }

                return(doc);
            }
        }
        public void InsertOrAppend_NoExesitingLine_InsertsLine()
        {
            var transform = new XmlTransformation(Path.GetFullPath("transform.xdt"));
            var doc       = new XmlDocument();

            doc.Load("config_empty.xml");
            Assert.True(transform.Apply(doc));

            Assert.Equal(2, doc.ChildNodes.Count);
            var configurationNode = doc["configuration"];

            Assert.Equal(2, configurationNode.ChildNodes.Count);

            var firstChild = configurationNode.FirstChild;

            Assert.Equal("add", firstChild.Name);
            Assert.Equal("KeyName1", firstChild.Attributes["name"].Value);
            Assert.Equal("InsertValue1", firstChild.Attributes["value"].Value);

            var secondChild = firstChild.NextSibling;

            Assert.Equal("add", secondChild.Name);
            Assert.Equal("KeyName2", secondChild.Attributes["name"].Value);
            Assert.Equal("InsertValue2", secondChild.Attributes["value"].Value);
        }
Exemple #4
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);
        }
Exemple #5
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);
        }
Exemple #6
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);
                    }
        }
Exemple #8
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");
                        }
                }
        }
Exemple #9
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);
        }
 public ActionResult Create(string webConfigXml, string transformXml)
 {
     try
     {
         var transformation = new XmlTransformation(transformXml, false, null);
         var document = new XmlDocument();
         document.LoadXml(webConfigXml);
         var success = transformation.Apply(document);
         if (success)
         {
             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);
     }
 }
Exemple #11
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());
     }
 }
Exemple #12
0
 public ActionResult Create(string webConfigXml, string transformXml)
 {
     try
     {
         var transformation = new XmlTransformation(transformXml, false, null);
         var document       = new XmlDocument();
         document.LoadXml(webConfigXml);
         var success = transformation.Apply(document);
         if (success)
         {
             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));
     }
 }
Exemple #13
0
        /// <summary>
        /// Make transformation of file <see cref="SourceFilePath"/> with transform file <see cref="TransformFile"/> to <paramref name="destinationFilePath"/>.
        /// </summary>
        /// <param name="destinationFilePath">File path of destination transformation.</param>
        /// <param name="forceParametersTask">Invoke parameters task even if the parameters are not set with <see cref="SetParameters" />.</param>
        /// <returns>Return true if transformation finish successfully, otherwise false.</returns>
        public bool Execute(string destinationFilePath, bool forceParametersTask = false)
        {
            if (string.IsNullOrWhiteSpace(destinationFilePath))
            {
                throw new ArgumentException("Destination file can't be empty.", "destinationFilePath");
            }

            this.log.WriteLine("Start tranformation to '{0}'.", destinationFilePath);

            if (string.IsNullOrWhiteSpace(this.SourceFilePath) || !File.Exists(this.SourceFilePath))
            {
                throw new FileNotFoundException("Can't find source file.", this.SourceFilePath);
            }

            if (string.IsNullOrWhiteSpace(this.TransformFile) || !File.Exists(this.TransformFile))
            {
                throw new FileNotFoundException("Can't find transform  file.", this.TransformFile);
            }

            this.log.WriteLine("Source file: '{0}'.", this.SourceFilePath);
            this.log.WriteLine("Transform  file: '{0}'.", this.TransformFile);

            try
            {
                var transformFile = ReadContent(this.TransformFile);

                if ((this.parameters != null && this.parameters.Count > 0) || forceParametersTask)
                {
                    ParametersTask parametersTask = new ParametersTask();
                    if (this.parameters != null)
                    {
                        parametersTask.AddParameters(this.parameters);
                    }

                    transformFile = parametersTask.ApplyParameters(transformFile);
                }

                XmlDocument document = new XmlDocument();
                document.Load(this.SourceFilePath);

                XmlTransformation transformation = new XmlTransformation(transformFile, false, this.transfomrationLogger);

                bool result = transformation.Apply(document);

                document.Save(destinationFilePath);

                return(result);
            }
            catch (Exception e)
            {
                this.log.WriteLine("Exception while transforming: {0}.", e);
                return(false);
            }
        }
Exemple #14
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);
            }
        }
        /// <summary>
        /// Return transformed xml string
        /// </summary>
        /// <param name="sourcePath">app.config</param>
        /// <param name="targetPath">app.debug.config</param>
        /// <returns>Transformed xml string</returns>
        public static string GetTransformString(string sourcePath, string targetPath)
        {
            var xmlDocument = OpenSourceFile(sourcePath);

            var xmlTransformation = new XmlTransformation(targetPath);

            xmlTransformation.Apply(xmlDocument);

            var xmlString = xmlDocument.OuterXml;

            return(xmlString);
        }
        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);
        }
        public XmlDocument Apply()
        {
            using (var tranform = new XmlTransformation(new MemoryStream(Encoding.UTF8.GetBytes(Transform.InnerXml)), new TraceTransformationLogger()))
            {
                if (tranform.Apply(Source))
                {
                    return(Source);
                }

                throw new ApplicationException("the transformation was not successful");
            }
        }
Exemple #18
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);
            }
        }
Exemple #19
0
        /// <inheritdoc />
        protected override void ProcessRecord()
        {
            if (!File.Exists(XdtTranformPath))
            {
                throw new FileNotFoundException(XdtTranformPath);
            }

            using (var xdtConfig = File.OpenRead(XdtTranformPath))
                using (var tranformation = new XmlTransformation(xdtConfig, new PsXdtConfigTransformLog(this)))
                {
                    tranformation.Apply(_configDocument);
                }
        }
Exemple #20
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}"));
        }
Exemple #21
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);
                }
            }
        }
        public static string ApplyTransformation(object caller, string documentResourceName, string transformationResourceName)
        {
            var transformation = ReadTransformation(caller, transformationResourceName);

            var document = ReadDocument(caller, documentResourceName);

            var xmlTransformation = new XmlTransformation(transformation, null);

            xmlTransformation.Apply(document);

            var transformedDocument = document;

            return(transformedDocument.OuterXml);
        }
            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);
            }
Exemple #24
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);
                    }
                }
            }
        }
Exemple #25
0
        private static XmlDocument LoadDocAndRunTransform(string docName)
        {
            // Microsoft.Web.Hosting.Transformers.ApplicationHost.SiteExtensionDefinition.Transform
            // (See Microsoft.Web.Hosting, Version=7.1.0.0) replaces variables for you in Azure.
            var transformFile = File.ReadAllText("applicationHost.xdt");

            transformFile = transformFile.Replace("%XDT_EXTENSIONPATH%", XdtExtensionPath);
            var transform = new XmlTransformation(transformFile, isTransformAFile: false, logger: null);
            var doc       = new XmlDocument();

            doc.Load(docName);
            Assert.True(transform.Apply(doc));
            return(doc);
        }
        /// <summary>
        /// Applies transforms to a workflow definition code so that multiple versions can be uploaded to Campaign.
        /// Transforms are defined in workflowName.transformName.config files, using xdt syntax, analagous to ASP.NET config transforms.
        /// </summary>
        /// <param name="template">Source content</param>
        /// <param name="parameters">Parameters to determine transform behaviour</param>
        /// <returns>A collection of transformed templates</returns>
        public IEnumerable <Template> Transform(Template template, TransformParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (!parameters.ApplyTransforms)
            {
                return(new[] { template });
            }

            var directoryName            = Path.GetDirectoryName(parameters.OriginalFileName);
            var transformFilenamePattern = $"{Path.GetFileNameWithoutExtension(parameters.OriginalFileName)}.*{TransformFileExtension}";
            var transformFiles           = Directory.GetFiles(directoryName, transformFilenamePattern);

            var templates = new List <Template>();

            foreach (var transformFile in transformFiles)
            {
                var transformName = Regex.Replace(Path.GetFileNameWithoutExtension(transformFile), $@"^{Path.GetFileNameWithoutExtension(parameters.OriginalFileName)}\.", string.Empty);

                var doc = new XmlDocument();
                doc.LoadXml(template.Code);

                var transformation = new XmlTransformation(transformFile);
                var s = transformation.Apply(doc);
                var transformedCode     = doc.OuterXml;
                var transformedTemplate = new Template
                {
                    FileExtension = template.FileExtension,
                    Metadata      = new TemplateMetadata
                    {
                        Name   = new InternalName(null, $"{template.Metadata.Name}_{transformName}"),
                        Label  = $"{template.Metadata.Label} ({transformName.Humanize()})",
                        Schema = template.Metadata.Schema,
                    },
                    Code = transformedCode,
                };
                foreach (var property in template.Metadata.AdditionalProperties)
                {
                    transformedTemplate.Metadata.AdditionalProperties.Add(property);
                }

                templates.Add(transformedTemplate);
            }

            return(templates);
        }
        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.");
            }
        }
Exemple #28
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));
 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);
         }
     }
 }
Exemple #30
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);
        }
Exemple #31
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);
                }
        }
Exemple #32
0
        /// <summary>
        /// Make transformation of file <see cref="SourceFilePath"/> with transform file <see cref="TransformFile"/> to <paramref name="destinationFilePath"/>.
        /// </summary>
        /// <param name="destinationFilePath">File path of destination transformation.</param>
        /// <returns>Return true if transformation finish successfully, otherwise false.</returns>
        public void Execute(string destinationFilePath)
        {
            if (string.IsNullOrWhiteSpace(destinationFilePath))
            {
                throw new ArgumentException("Destination file can't be empty.", "destinationFilePath");
            }

            if (string.IsNullOrWhiteSpace(SourceFilePath) || !File.Exists(SourceFilePath))
            {
                throw new FileNotFoundException("Can't find source file.", SourceFilePath);
            }

            if (string.IsNullOrWhiteSpace(TransformFile) || !File.Exists(TransformFile))
            {
                throw new FileNotFoundException("Can't find transform  file.", TransformFile);
            }

            string transformFileContents = File.ReadAllText(TransformFile);

            var document = new XmlDocument();

            try
            {
                document.Load(SourceFilePath);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error loading source '{0}': {1}", SourceFilePath, ex.Message), ex);
            }

            var transformation = new XmlTransformation(transformFileContents, false, _transformationLogger);

            try
            {
                bool result = transformation.Apply(document);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error generating '{0}': {1}", destinationFilePath, ex.Message), ex);
            }

            document.Save(destinationFilePath);
        }
Exemple #33
0
        /// <summary>
        /// 	Make transformation of file <see cref="SourceFilePath" /> with transform file <see cref="TransformFile" /> to <paramref
        /// 	 name="destinationFilePath" />.
        /// </summary>
        /// <param name="destinationFilePath"> File path of destination transformation. </param>
        /// <param name="forceParametersTask"> Invoke parameters task even if the parameters are not set with <see
        /// 	 cref="SetParameters" /> . </param>
        /// <returns> Return true if transformation finish successfully, otherwise false. </returns>
        public bool Execute(string destinationFilePath, bool forceParametersTask = false)
        {
            if (string.IsNullOrWhiteSpace(destinationFilePath))
                throw new ArgumentException("Destination file can't be empty.", "destinationFilePath");

            Trace.TraceInformation("Start tranformation to '{0}'.", destinationFilePath);

            if (string.IsNullOrWhiteSpace(SourceFilePath) || !File.Exists(SourceFilePath))
                throw new FileNotFoundException("Can't find source file.", SourceFilePath);

            if (string.IsNullOrWhiteSpace(TransformFile) || !File.Exists(TransformFile))
                throw new FileNotFoundException("Can't find transform  file.", TransformFile);

            Trace.TraceInformation("Source file: '{0}'.", SourceFilePath);
            Trace.TraceInformation("Transform  file: '{0}'.", TransformFile);

            try
            {
                var transformFile = ReadContent(TransformFile);

                if ((_parameters != null && _parameters.Count > 0) || forceParametersTask)
                {
                    ParametersTask parametersTask = new ParametersTask();
                    if (_parameters != null)
                        parametersTask.AddParameters(_parameters);
                    transformFile = parametersTask.ApplyParameters(transformFile);
                }

                XmlDocument document = new XmlDocument();
                document.Load(SourceFilePath);

                XmlTransformation transformation = new XmlTransformation(transformFile, false, _transfomrationLogger);

                bool result = transformation.Apply(document);

                document.Save(destinationFilePath);

                return result;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                return false;
            }
        }
        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);
                }
            }
        }
Exemple #35
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]);
        }