private static bool Transform(string fileFullName, string xdtPath, bool install)
        {
            var doc = new XmlTransformableDocument
            {
                PreserveWhitespace = true
            };
            doc.Load(fileFullName);

            var fileName = Path.GetFileName(fileFullName);
            var xdtName = fileName + "." + (install ? "install" : "uninstall") + ".xdt";
            var xdtFullName = Path.Combine(xdtPath, xdtName);
            if (!File.Exists(xdtFullName))
            {
                LogHelper.Info<Configure2>("Missing transform {0}.", () => xdtName);
                return true;
            }

            LogHelper.Info<Configure2>("Apply transform {0}.", () => xdtName);

            var transform = new XmlTransformation(xdtFullName, true, null);
            var result = transform.Apply(doc);

            if (!result)
                return false;

            doc.Save(fileFullName);
            return true;
        }
Ejemplo n.º 2
0
        protected virtual void Dispose(bool disposing)
        {
            if (transformationServiceContainer != null)
            {
                transformationServiceContainer.Dispose();
                transformationServiceContainer = null;
            }

            if (documentServiceContainer != null)
            {
                documentServiceContainer.Dispose();
                documentServiceContainer = null;
            }

            if (xmlTransformable != null)
            {
                xmlTransformable.Dispose();
                xmlTransformable = null;
            }

            if (xmlTransformation as XmlFileInfoDocument != null)
            {
                (xmlTransformation as XmlFileInfoDocument).Dispose();
                xmlTransformation = null;
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args) {
            if (args == null || args.Length < 3) {
                ShowUsage();
                return;
            }

            string sourceFile = args[0];
            string transformFile = args[1];
            string destFile = args[2];

            if (!File.Exists(sourceFile)) { throw new FileNotFoundException("sourceFile doesn't exist"); }
            if (!File.Exists(transformFile)) { throw new FileNotFoundException("transformFile doesn't exist"); }

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

                using (XmlTransformation transform = new XmlTransformation(transformFile)) {

                    var success = transform.Apply(document);

                    document.Save(destFile);

                    System.Console.WriteLine(
                        string.Format("\nSaved transformation at '{0}'\n\n",
                        new FileInfo(destFile).FullName));

                    // Console.WriteLine("Press enter to continue");
                    // Console.ReadLine();

                    int exitCode = (success == true) ? 0 : 1;
                    Environment.Exit(exitCode);
                }
            }
        }
Ejemplo n.º 4
0
        public void PerformTransform(string configFile, string transformFile, string destinationFile)
        {
            var transformFailed = false;
            var transformWarning = "";
            var logger = new VerboseTransformLogger(_suppressTransformationErrors, _suppressTransformationLogging);
            logger.Warning += (sender, args) =>
            {
                transformWarning = args.Message;
                transformFailed = true;
            };
            if (_suppressTransformationErrors)
            {
                Log.Info("XML Transformation warnings will be suppressed.");
            }

            var transformation = new XmlTransformation(transformFile, logger);

            var configurationFileDocument = new XmlTransformableDocument();
            configurationFileDocument.PreserveWhitespace = true;
            configurationFileDocument.Load(configFile);

            var success = transformation.Apply(configurationFileDocument);

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

            configurationFileDocument.Save(destinationFile);
        }
            public bool Execute(string packageName, System.Xml.XmlNode xmlData)
            {
                //The config file we want to modify
                var file = xmlData.Attributes.GetNamedItem("file").Value;
                string sourceDocFileName = VirtualPathUtility.ToAbsolute(file);

                //The xdt file used for tranformation
                var xdtfile = xmlData.Attributes.GetNamedItem("xdtfile").Value;
                string 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.
                            xmlDoc.Save(HttpContext.Current.Server.MapPath(sourceDocFileName));
                        }
                    }
                }

                return true;
            }
Ejemplo n.º 6
0
        private void Transform(string sourceFile, IEnumerable<string> tranformFiles, string destinationFile)
        {
            var sourceXmlString = _fileSystem.File.ReadAllText(sourceFile);
            var sourceFileEncoding = GetEncoding(sourceXmlString);
            var intermediateXmlString = sourceXmlString;

            foreach (var transformFile in tranformFiles)
            {
                var sourceDocument = new XmlTransformableDocument();
                var transformXmlString = _fileSystem.File.ReadAllText(transformFile);
                var transformFileEncoding = GetEncoding(transformXmlString);
                var transformXmlBytes = transformFileEncoding.GetBytes(transformXmlString);

                using (var memoryStream = new MemoryStream(transformXmlBytes))
                {
                    var transformation = new XmlTransformation(memoryStream, _xmlTransformationLogger);
                    sourceDocument.LoadXml(intermediateXmlString);
                    transformation.Apply(sourceDocument);
                    intermediateXmlString = sourceDocument.OuterXml;
                }
            }

            var xDocument = XDocument.Parse(intermediateXmlString, LoadOptions.PreserveWhitespace);
            intermediateXmlString = $"{xDocument.Declaration}{Environment.NewLine}{xDocument.Document}";

            _fileSystem.File.WriteAllText(destinationFile, intermediateXmlString, sourceFileEncoding);
        }
Ejemplo n.º 7
0
 public bool Apply(XmlDocument xmlTarget)
 {
     if (this.xmlTarget != null)
     {
         return(false);
     }
     this.logger.HasLoggedErrors = false;
     this.xmlTarget        = xmlTarget;
     this.xmlTransformable = xmlTarget as XmlTransformableDocument;
     try
     {
         if (this.hasTransformNamespace)
         {
             this.InitializeDocumentServices(xmlTarget);
             this.TransformLoop(this.xmlTransformation);
         }
         else
         {
             object[] messageArgs = new object[] { TransformNamespace };
             this.logger.LogMessage(MessageType.Normal, "The expected namespace {0} was not found in the transform file", messageArgs);
         }
     }
     catch (Exception exception)
     {
         this.HandleException(exception);
     }
     finally
     {
         this.ReleaseDocumentServices();
         this.xmlTarget        = null;
         this.xmlTransformable = null;
     }
     return(!this.logger.HasLoggedErrors);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sourceFile"></param>
 /// <returns></returns>
 public XmlTransformableDocument OpenSourceFile(string sourceFile)
 {
     var xml = File.ReadAllText(sourceFile);
     var document = new XmlTransformableDocument { PreserveWhitespace = true };
     document.LoadXml(xml);
     return document;
 }
Ejemplo n.º 9
0
        public void Transform(string source, string transform, string destination)
        {
            if (string.IsNullOrWhiteSpace(source)) { throw new ArgumentNullException("source"); }
            if (string.IsNullOrWhiteSpace(transform)) { throw new ArgumentNullException("transform"); }
            if (string.IsNullOrWhiteSpace(destination)) { throw new ArgumentNullException("destination"); }

            if (!File.Exists(source)) {
                throw new FileNotFoundException("File to transform not found", source);
            }
            if (!File.Exists(transform)) {
                throw new FileNotFoundException("Transform file not found", transform);
            }

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

                var success = transformation.Apply(document);
                if (!success) {
                    string message = string.Format(
                        "There was an unknown error trying while trying to apply the transform. Source file='{0}',Transform='{1}', Destination='{2}'",
                        source,transform,destination);
                    throw new TransformFailedException(message);
                }

                document.Save(destination);
            }
        }
        public static void TransformConfig(FilePath sourceFile, FilePath transformFile, FilePath targetFile)
        {
            if (sourceFile == null)
            {
                throw new ArgumentNullException(nameof(sourceFile), "Source file path is null.");
            }
            if (transformFile == null)
            {
                throw new ArgumentNullException(nameof(transformFile), "Transform file path is null.");
            }
            if (targetFile == null)
            {
                throw new ArgumentNullException(nameof(targetFile), "Target file path is null.");
            }

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

                if (!transform.Apply(document))
                {
                    throw new CakeException(
                        string.Format(
                            "Failed to transform \"{0}\" using \"{1}\" to \"{2}\"",
                            sourceFile,
                            transformFile,
                            targetFile
                            )
                        );
                }

                document.Save(targetFile.ToString());
            }
        }
Ejemplo n.º 11
0
        static int Main(string[] args)
        {
            var version = Assembly.GetEntryAssembly().GetName().Version;
            Console.WriteLine(
                  "==================\n"
                + string.Format(" FatAntelope v{0}.{1}\n", version.Major, version.Minor)
                + "==================\n");

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

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

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

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

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

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

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

                source.Save(args[3]);
            }
            Console.WriteLine("- Finished successfully!\n");
            return (int)ExitCode.Success;
        }
Ejemplo n.º 12
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);
            }
        }
Ejemplo n.º 13
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);
                }
            }
        }
Ejemplo n.º 14
0
        public void ApplyConfigTransformation(string xmlFile, string transformFile, string targetFile)
        {
            var source = new XmlTransformableDocument
              {
            PreserveWhitespace = true
              };
              source.Load(xmlFile);

              var transform = new XmlTransformation(transformFile);
              if (transform.Apply(source))
              {
            source.Save(xmlFile);
              }
        }
            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;
            }
Ejemplo n.º 16
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);
				}
			}
		}
Ejemplo n.º 17
0
        public static TransformResult Transform(string transformationPath, IDictionary<string, string> parameters, string[] targetFiles, bool preserveWhitespace = true)
        {
            if (!File.Exists(transformationPath)) throw new ArgumentException("Transformation path did not exist");

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

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

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

            transformText = ParameterizeText(transformText, parameters);

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

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

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

                    document.LoadXml(input);

                    transformation.Apply(document);

                    if (logger.HasErrors) break;

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

            return new TransformResult(logger.Messages.ToArray(), !logger.HasErrors);
        }
        private static string PerformXdtTransform(string exampleFile, string xdtFile)
        {
            var doc = new XmlTransformableDocument {PreserveWhitespace = true};
            doc.Load(exampleFile);
            var xdt = new XmlTransformation(xdtFile);

            var result = xdt.Apply(doc);

            result.ShouldBe(true);
            using (var stream = new MemoryStream())
            {
                doc.Save(stream);
                stream.Position = 0;
                var reader = new StreamReader(stream);
                return reader.ReadToEnd();
            }
        }
		string RunTransform (string input, string xdt)
		{
			using (var transformation = new XmlTransformation (xdt, isTransformAFile: false, logger: null)) {
				using (var document = new XmlTransformableDocument ()) {
					document.PreserveWhitespace = true;

					document.Load (new StringReader (input));

					bool succeeded = transformation.Apply(document);
					if (succeeded) {
						var writer = new StringWriter ();
						document.Save (writer);
						return writer.ToString ();
					}
					return null;
				}
			}
		}
        private string SetParametersToConfig(string transformationString)
        {
            using (var applicationHostStream = typeof(IisExpressConfiguration).Assembly.GetManifestResourceStream(ApplicationHostResourceName))
            {
                if (applicationHostStream != null)
                {
                    using (var transformation = new XmlTransformation(transformationString, false, null))
                    {
                        var document = new XmlTransformableDocument();
                        document.Load(applicationHostStream);
                        transformation.Apply(document);

                        return document.OuterXml;
                    }
                }
            }

            return string.Empty;
        }
Ejemplo n.º 21
0
        public bool Transform(string source, string transform, string destination)
        {
            if (string.IsNullOrEmpty(destination))
                throw new ArgumentException("destination cannot be null or empty");

            var sourceContent = _fileSystem.File.ReadAllText(source);
            var transformation = new XmlTransformation(_fileSystem.File.OpenRead(transform), null);

            var sourceDocument = new XmlTransformableDocument
            {
                PreserveWhitespace = true
            };

            sourceDocument.LoadXml(sourceContent);
            transformation.Apply(sourceDocument);
            _fileSystem.File.WriteAllText(destination, sourceDocument.OuterXml);

            return true;
        }
Ejemplo n.º 22
0
        // TODO: These methods are shared with TransformXml, we should refactor these to share the same code
        private XmlTransformableDocument OpenSourceFile(string sourceFile) {
            try {
                XmlTransformableDocument document = new XmlTransformableDocument();

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

                return document;
            }
            catch (System.Xml.XmlException) {
                throw;
            }
            catch (Exception ex) {
                throw new Exception(
                    string.Format(System.Globalization.CultureInfo.CurrentCulture,
                    "Could not open Source file: {0}", ex.Message),
                    ex);
            }
        }
Ejemplo n.º 23
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);
            }

            configurationFileDocument.Save(destinationFile);
        }
        private static void PerformXdtTransform(ZipArchiveEntry packageFile, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem)
        {
            if(FileSystemUtility.FileExists(msBuildNuGetProjectSystem.ProjectFullPath, targetPath))
            {
                string content = Preprocessor.Process(packageFile, msBuildNuGetProjectSystem);

                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 = File.OpenRead(FileSystemUtility.GetFullPath(msBuildNuGetProjectSystem.ProjectFullPath, targetPath)))
                            {
                                document.Load(inputStream);
                            }

                            bool 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);
                }
            }
        }
Ejemplo n.º 25
0
        public bool Apply(XmlDocument xmlTarget)
        {
            Debug.Assert(this.xmlTarget == null, "This method should not be called recursively");

            if (this.xmlTarget == null)
            {
                // Reset the error state
                logger.HasLoggedErrors = false;

                this.xmlTarget        = xmlTarget;
                this.xmlTransformable = xmlTarget as XmlTransformableDocument;
                try {
                    if (hasTransformNamespace)
                    {
                        InitializeDocumentServices(xmlTarget);

                        TransformLoop(xmlTransformation);
                    }
                    else
                    {
                        logger.LogMessage(MessageType.Normal, "The expected namespace {0} was not found in the transform file", TransformNamespace);
                    }
                }
                catch (Exception ex) {
                    HandleException(ex);
                }
                finally {
                    ReleaseDocumentServices();

                    this.xmlTarget        = null;
                    this.xmlTransformable = null;
                }

                return(!logger.HasLoggedErrors);
            }
            else
            {
                return(false);
            }
        }
        public ActionResult Create(string webConfigXml, string transformXml)
        {
            try
            {
                using (var document = new XmlTransformableDocument())
                {
                    document.PreserveWhitespace = true;
                    document.LoadXml(webConfigXml);

                    using (var transform = new XmlTransformation(transformXml, false, null))
                    {
                        if (transform.Apply(document))
                        {
                            var stringBuilder = new StringBuilder();
                            var xmlWriterSettings = new XmlWriterSettings();
                            xmlWriterSettings.Indent = true;
                            xmlWriterSettings.IndentChars = "    ";
                            using (var xmlTextWriter = XmlTextWriter.Create(stringBuilder, xmlWriterSettings))
                            {
                                document.WriteTo(xmlTextWriter);
                            }
                            return Content(stringBuilder.ToString(), "text/xml");
                        }
                        else
                        {
                            return ErrorXml("Transformation failed for unkown reason");
                        }
                    }
                }
            }
            catch (XmlTransformationException xmlTransformationException)
            {
                return ErrorXml(xmlTransformationException.Message);
            }
            catch (XmlException xmlException)
            {
                return ErrorXml(xmlException.Message);
            }
        }
Ejemplo n.º 27
0
        static int Main(string[] args)
        {
            if (args.Length != 2 && args.Length != 3)
            {
                Console.Error.WriteLine("Usage: config-transform config.xml transform.xml [original.xml]. If original.xml is not provided, config.xml is overwritten.");
                return -1;
            }

            var transformer = new XmlTransformableDocument { PreserveWhitespace = true };

            var sourceIndex = args.Length == 3 ? 2 : 0;

            if (File.Exists(args[sourceIndex]) == false)
            {
                Console.Error.WriteLine(string.Format("Config file {0} could not be found.", args[sourceIndex]));
                return -2;
            }

            if (File.Exists(args[1]) == false)
            {
                Console.Error.WriteLine(string.Format("Transform file {0} could not be found.", args[1]));
                return -3;
            }

            transformer.Load(args[sourceIndex]);

            var transform = new XmlTransformation(args[1]);

            if (!transform.Apply(transformer))
            {
                Console.Error.WriteLine("Transformation failed.");
                return -4;
            }

            transformer.Save(args[0]);

            return 0;
        }
Ejemplo n.º 28
0
 protected virtual void Dispose(bool disposing)
 {
     if (this.transformationServiceContainer != null)
     {
         this.transformationServiceContainer.Dispose();
         this.transformationServiceContainer = null;
     }
     if (this.documentServiceContainer != null)
     {
         this.documentServiceContainer.Dispose();
         this.documentServiceContainer = null;
     }
     if (this.xmlTransformable != null)
     {
         this.xmlTransformable.Dispose();
         this.xmlTransformable = null;
     }
     if (this.xmlTransformation is XmlFileInfoDocument)
     {
         (this.xmlTransformation as XmlFileInfoDocument).Dispose();
         this.xmlTransformation = null;
     }
 }
        private static XDocument Transform(string sourceXml, string transformationFileResourceName)
        {
            using (var document = new XmlTransformableDocument())
            {
                Stream stream = typeof(TelemetryChannelTests).Assembly.GetManifestResourceStream(transformationFileResourceName);
                using (var reader = new StreamReader(stream))
                {
                    string transform = reader.ReadToEnd();
                    using (var transformation = new XmlTransformation(transform, false, null))
                    {
                        XmlReaderSettings settings = new XmlReaderSettings();
                        settings.ValidationType = ValidationType.None;

                        using (XmlReader xmlReader = XmlReader.Create(new StringReader(sourceXml), settings))
                        {
                            document.Load(xmlReader);
                            transformation.Apply(document);
                            return XDocument.Parse(document.OuterXml);
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
        private void TransformXML(string sourcePath, string transformPath, string destinationPath)
        {
            if (!File.Exists(sourcePath))
            {
                throw new FileNotFoundException("File to transform not found", sourcePath);
            }
            if (!File.Exists(transformPath))
            {
                throw new FileNotFoundException("Transform file not found", transformPath);
            }

            using (XmlTransformableDocument document = new XmlTransformableDocument())
            using (XmlTransformation transformation = new XmlTransformation(transformPath))
            {
                document.PreserveWhitespace = true;
                document.Load(sourcePath);

                var success = transformation.Apply(document);

                if (!success)
                {
                    string message = string.Format(
                        "There was an unknown error trying while trying to apply the transform. Source file='{0}',Transform='{1}', Destination='{2}'",
                        sourcePath, transformPath, destinationPath);
                    throw new Exception(message);
                }

                var destinationInfo = new FileInfo(destinationPath);

                if (!destinationInfo.Directory.Exists)
                {
                    destinationInfo.Directory.Create();
                }

                document.Save(destinationPath);
            }
        }
        public void Transform()
        {
            if (!IsInputValid())
            {
                return;
            }

            IList<ConfigurationEntry> configurationEntries = GetConfigurationEntries();
            foreach (ConfigurationEntry entry in configurationEntries)
            {
                var transformation = new XmlTransformation(entry.TransformationFilePath);
                var transformableDocument = new XmlTransformableDocument();
                transformableDocument.Load(entry.FilePath);
                if (transformation.Apply(transformableDocument))
                {
                    if (!string.IsNullOrWhiteSpace(entry.FileName))
                    {
                        var targetDirecory = Path.Combine(TargetDirectory, entry.ParentSubfolder);
                        Directory.CreateDirectory(targetDirecory);
                        transformableDocument.Save(Path.Combine(targetDirecory, entry.FileName));
                    }
                }
            }
        }
Ejemplo n.º 32
0
        static void TransformWebConfig(Path websitePath, string transformConfiguration, Path tempWebsitePath)
        {
            if (string.IsNullOrWhiteSpace(transformConfiguration))
            {
                return;
            }

            Path transformRootFile = Path.Combine(websitePath, "web.config");

            Path transformationFile = Path.Combine(websitePath, string.Format("web.{0}.config", transformConfiguration));

            if (File.Exists(transformRootFile.FullName) && File.Exists(transformationFile.FullName))
            {
                Path targetFile = Path.Combine(tempWebsitePath, "web.config");

                string fullName = new FileInfo(targetFile.FullName).Directory.FullName;
                if (Directory.Exists(fullName))
                {
                    Console.WriteLine("Transforming root file '{0}' with transformation '{1}' into '{2}'", transformRootFile.FullName, transformationFile.FullName, targetFile.FullName);

                    var transformable = new XmlTransformableDocument();
                    transformable.Load(transformRootFile.FullName);

                    var transformation = new XmlTransformation(transformationFile.FullName);

                    if (transformation.Apply(transformable))
                    {
                        transformable.Save(targetFile.FullName);
                    }
                }
                else
                {
                    Console.WriteLine("Directory {0} does not exist", fullName);
                }
            }
        }
Ejemplo n.º 33
0
        private void ProcessInstall( PurchaseResponse purchaseResponse )
        {
            if ( purchaseResponse.PackageInstallSteps != null )
            {
                RockSemanticVersion rockVersion = RockSemanticVersion.Parse( VersionInfo.GetRockSemanticVersionNumber() );

                foreach ( var installStep in purchaseResponse.PackageInstallSteps.Where( s => s.RequiredRockSemanticVersion <= rockVersion ))
                {
                    string appRoot = Server.MapPath( "~/" );
                    string rockShopWorkingDir = appRoot + "App_Data/RockShop";
                    string packageDirectory = string.Format( "{0}/{1} - {2}", rockShopWorkingDir, purchaseResponse.PackageId, purchaseResponse.PackageName );
                    string sourceFile = installStep.InstallPackageUrl;
                    string destinationFile = string.Format("{0}/{1} - {2}.plugin", packageDirectory, installStep.VersionId, installStep.VersionLabel);

                    // check that the RockShop directory exists
                    if ( !Directory.Exists( rockShopWorkingDir ) )
                    {
                        Directory.CreateDirectory( rockShopWorkingDir );
                    }

                    // create package directory
                    if ( !Directory.Exists( packageDirectory ) )
                    {
                        Directory.CreateDirectory( packageDirectory );
                    }

                    // download file
                    try
                    {
                        WebClient wc = new WebClient();
                        wc.DownloadFile( sourceFile, destinationFile );
                    }
                    catch ( Exception ex )
                    {
                        CleanUpPackage( destinationFile );
                        lMessages.Text = string.Format( "<div class='alert alert-warning margin-t-md'><strong>Error Downloading Package</strong> An error occurred while downloading package from the store. Please try again later. <br><em>Error: {0}</em></div>", ex.Message );
                        return;
                    }

                   // process zip folder
                    try
                    {
                        using ( ZipArchive packageZip = ZipFile.OpenRead( destinationFile ) )
                        {
                            // unzip content folder and process xdts
                            foreach ( ZipArchiveEntry entry in packageZip.Entries.Where(e => e.FullName.StartsWith("content/")) )
                            {
                               if ( entry.FullName.EndsWith( _xdtExtension, StringComparison.OrdinalIgnoreCase ) )
                                {
                                    // process xdt
                                    string filename = entry.FullName.Replace( "content/", "" );
                                    string transformTargetFile = appRoot + filename.Substring( 0, filename.LastIndexOf( _xdtExtension ) );

                                    // 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 ) )
                                            {
                                                document.Save( transformTargetFile );
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    // process all content files
                                    string fullpath = Path.Combine( appRoot, entry.FullName.Replace("content/", "") );
                                    string directory = Path.GetDirectoryName( fullpath ).Replace("content/", "");

                                    // if entry is a directory ignore it
                                    if ( entry.Length != 0 )
                                    {
                                        if ( !Directory.Exists( directory ) )
                                        {
                                            Directory.CreateDirectory( directory );
                                        }

                                        entry.ExtractToFile( fullpath, true );
                                    }

                                }
                            }

                            // process install.sql
                            try
                            {
                                var sqlInstallEntry = packageZip.Entries.Where( e => e.FullName == "install/run.sql" ).FirstOrDefault();
                                if (sqlInstallEntry != null) {
                                    string sqlScript = System.Text.Encoding.Default.GetString(sqlInstallEntry.Open().ReadBytesToEnd());

                                    if ( !string.IsNullOrWhiteSpace( sqlScript ) )
                                    {
                                        using ( var context = new RockContext() )
                                        {
                                            context.Database.ExecuteSqlCommand( sqlScript );
                                        }
                                    }
                                }
                            }
                            catch ( Exception ex )
                            {
                                lMessages.Text = string.Format( "<div class='alert alert-warning margin-t-md'><strong>Error Updating Database</strong> An error occurred while updating the database. <br><em>Error: {0}</em></div>", ex.Message );
                                return;
                            }

                            // process deletefile.lst
                            try
                            {
                                var deleteListEntry = packageZip.Entries.Where( e => e.FullName == "install/deletefile.lst" ).FirstOrDefault();
                                if ( deleteListEntry != null )
                                {

                                    string deleteList = System.Text.Encoding.Default.GetString( deleteListEntry.Open().ReadBytesToEnd() );

                                    string[] itemsToDelete = deleteList.Split( new string[] { Environment.NewLine }, StringSplitOptions.None );

                                    foreach ( string deleteItem in itemsToDelete )
                                    {
                                        if ( !string.IsNullOrWhiteSpace( deleteItem ) )
                                        {
                                            string deleteItemFullPath = appRoot + deleteItem;

                                            if ( Directory.Exists( deleteItemFullPath ) )
                                            {
                                                Directory.Delete( deleteItemFullPath, true);
                                            }

                                            if ( File.Exists( deleteItemFullPath ) )
                                            {
                                                File.Delete( deleteItemFullPath );
                                            }
                                        }
                                    }

                                }
                            }
                            catch ( Exception ex )
                            {
                                lMessages.Text = string.Format( "<div class='alert alert-warning margin-t-md'><strong>Error Modifing Files</strong> An error occurred while modifing files. <br><em>Error: {0}</em></div>", ex.Message );
                                return;
                            }

                        }
                    }
                    catch ( Exception ex )
                    {
                        lMessages.Text = string.Format( "<div class='alert alert-warning margin-t-md'><strong>Error Extracting Package</strong> An error occurred while extracting the contents of the package. <br><em>Error: {0}</em></div>", ex.Message );
                        return;
                    }

                    // update package install json file
                    InstalledPackageService.SaveInstall( purchaseResponse.PackageId, purchaseResponse.PackageName, installStep.VersionId, installStep.VersionLabel, purchaseResponse.VendorId, purchaseResponse.VendorName, purchaseResponse.InstalledBy );

                    // Clear all cached items
                    Rock.Web.Cache.RockMemoryCache.Clear();

                    // Clear the static object that contains all auth rules (so that it will be refreshed)
                    Rock.Security.Authorization.Flush();

                    // show result message
                    lMessages.Text = string.Format( "<div class='alert alert-success margin-t-md'><strong>Package Installed</strong><p>{0}</p>", installStep.PostInstallInstructions );
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning margin-t-md'><strong>Error</strong> Install package was not valid. Please try again later.";
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Transforms the XML file.
        /// </summary>
        /// <param name="xmlData">
        /// The package action XML.
        /// </param>
        /// <param name="install">
        /// Install or uninstall?
        /// </param>
        private void Transform(XmlNode xmlData, string fileToTransform, bool install)
        {
            // Extract paths from XML.
            var transformAttribute = install
                ? "installTransform"
                : "uninstallTransform";
            var transformFile = GetAttributeValue(xmlData, transformAttribute);

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

            // Transform file.
            using (var doc = new XmlTransformableDocument())
            using (var transform = new XmlTransformation(transformFile))
            {
                doc.PreserveWhitespace = true;
                doc.Load(fileToTransform);
                transform.Apply(doc);
                doc.Save(fileToTransform);
            }
        }