Ejemplo n.º 1
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);
        }
        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.º 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 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 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;
            }
        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.º 7
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.º 8
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.º 9
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);
              }
        }
Ejemplo n.º 10
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);
				}
			}
		}
            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;
            }
		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 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.º 14
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);
        }
Ejemplo n.º 15
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);
            }
        }
        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.º 17
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;
        }
        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.º 19
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.º 21
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.º 22
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.º 23
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);
            }
        }
Ejemplo n.º 24
0
 private static XmlTransformableDocument LoadSourceFile(string fileToTransform)
 {
     var source = new XmlTransformableDocument {PreserveWhitespace = false};
     source.Load(fileToTransform);
     return source;
 }
Ejemplo n.º 25
0
        /// <summary>
        ///     Searches for a suitable config transformation and applies it 
        /// </summary>
        /// <param name="info">Package info</param>
        private void ApplyTransformations(PackageInfo info, string configFile, string transform)
        {
            if (configFile != null && transform != null)
            {
                Logger.Log("Applying transform passed as parameter");

                using (var transformation = new XmlTransformation(transform, isTransformAFile: false, logger: null))
                {
                    var dest = Path.Combine(info.InstallationDirectory, configFile);

                    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(dest))
                        {
                            document.Load(inputStream);
                        }

                        bool succeeded = transformation.Apply(document);
                        if (succeeded)
                        {
                            File.Delete(dest);
                            using (var fileStream = File.OpenWrite(dest))
                            {
                                document.Save(fileStream);
                                Logger.Log("Transformation applied successfully");
                            }
                        }
                        else
                        {
                            throw new TransformException(String.Format("Unable to apply {0} transformation to {1}", dest.Replace(".config", "." + info.Configuration + ".config"), dest));
                        }
                    }
                }

                return;
            }

            var files = Directory.GetFiles(info.InstallationDirectory, "*.config", SearchOption.AllDirectories)
                                 .Where(file => File.Exists(file.Replace(".config", "." + info.Configuration + ".config")));

            foreach (var file in files)
            {
                Logger.Log(String.Format("Applying transformation {0} contained in package ...", Path.GetFileName(file)));

                var sb = new StringBuilder();
                using (StreamReader sr = new StreamReader(file.Replace(".config", "." + info.Configuration + ".config")))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        sb.AppendLine(line);
                    }
                }

                string content = sb.ToString();

                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(file))
                        {
                            document.Load(inputStream);
                        }

                        bool succeeded = transformation.Apply(document);
                        if (succeeded)
                        {
                            File.Delete(file);
                            using (var fileStream = File.OpenWrite(file))
                            {
                                document.Save(fileStream);
                                Logger.Log("Transformation applied successfully");
                            }
                        }
                        else
                        {
                            throw new TransformException(String.Format("Unable to apply {0} transformation to {1}", file.Replace(".config", "." + info.Configuration + ".config"), file));
                        }
                    }
                }
            }
        }
        private static void TransformXmlDoc(string sourceFile, string transFile, string destFile = "")
        {
            if (string.IsNullOrEmpty(destFile))
                destFile = sourceFile;
            // The translation at-hand
            using (var xmlDoc = new XmlTransformableDocument())
            {
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(sourceFile);

                using (var xmlTrans = new XmlTransformation(transFile))
                {
                    if (xmlTrans.Apply(xmlDoc))
                    {
                        xmlDoc.Save(destFile);
                    }
                }
            }
        }
Ejemplo n.º 27
0
 /// <summary>
 /// The open source file.
 /// </summary>
 /// <param name="sourceFile">
 /// The source file.
 /// </param>
 /// <returns>
 /// The <see cref="XmlTransformableDocument"/>.
 /// </returns>
 /// <exception cref="Exception">
 /// </exception>
 private XmlTransformableDocument OpenSourceFile(string sourceFile)
 {
     try
     {
         var transformableDocument = new XmlTransformableDocument();
         transformableDocument.PreserveWhitespace = true;
         transformableDocument.Load(sourceFile);
         return transformableDocument;
     }
     catch (XmlException ex)
     {
         throw;
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format((IFormatProvider)CultureInfo.CurrentCulture, "Loading transformation source failed {0}", new[] { (object)ex.Message }), ex);
     }
 }
Ejemplo n.º 28
0
        public void run(PackageResult packageResult, ChocolateyConfiguration config)
        {
            var installDirectory = packageResult != null ? packageResult.InstallLocation : string.Empty;
            if (string.IsNullOrWhiteSpace(installDirectory) || installDirectory.is_equal_to(ApplicationParameters.InstallLocation) || installDirectory.is_equal_to(ApplicationParameters.PackagesLocation))
            {
                var logMessage = "Install location is not specific enough, cannot capture files:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, installDirectory);
                if (packageResult != null) packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage));
                this.Log().Error(logMessage);
                return;
            }

            var transformFiles = _fileSystem.get_files(installDirectory, "*" + ApplicationParameters.ConfigFileTransformExtension, SearchOption.AllDirectories);
            foreach (var transformFile in transformFiles.or_empty_list_if_null())
            {
                this.Log().Debug(() => "Preparing transform for '{0}'".format_with(transformFile));
                var targetFileName = _fileSystem.get_file_name(transformFile.Replace(ApplicationParameters.ConfigFileTransformExtension, string.Empty));
                // target files must exist, otherwise one is added next to the transform
                var targetFiles = _fileSystem.get_files(installDirectory, targetFileName, SearchOption.AllDirectories);

                var targetFilesTest = targetFiles as IList<string> ?? targetFiles.ToList();
                if (!targetFilesTest.Any())
                {
                    targetFiles = new[] {transformFile.Replace(ApplicationParameters.ConfigFileTransformExtension, string.Empty)};
                    this.Log().Debug(() => "No matching files found for transform {0}.{1} Creating '{2}'".format_with(_fileSystem.get_file_name(transformFile), Environment.NewLine, targetFiles.FirstOrDefault()));
                }

                foreach (var targetFile in targetFilesTest.or_empty_list_if_null())
                {
                    FaultTolerance.try_catch_with_logging_exception(
                        () =>
                            {
                                // if there is a backup, we need to put it back in place
                                // the user has indicated they are using transforms by putting
                                // the transform file into the folder, so we will override
                                // the replacement of the file and instead pull from the last 
                                // backup and let the transform to its thing instead.
                                var backupTargetFile = targetFile.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageBackupLocation);
                                if (_fileSystem.file_exists(backupTargetFile))
                                {
                                    this.Log().Debug(()=> "Restoring backup configuration file for '{0}'.".format_with(targetFile));
                                    _fileSystem.copy_file(backupTargetFile, targetFile, overwriteExisting: true);
                                }
                            },
                        "Error replacing backup config file",
                        throwError: false,
                        logWarningInsteadOfError: true);

                    FaultTolerance.try_catch_with_logging_exception(
                        () =>
                            {
                                this.Log().Info(() => "Transforming '{0}' with the data from '{1}'".format_with(_fileSystem.get_file_name(targetFile), _fileSystem.get_file_name(transformFile)));

                                using (var transformation = new XmlTransformation(_fileSystem.read_file(transformFile), isTransformAFile: false, logger: null))
                                {
                                    using (var document = new XmlTransformableDocument {PreserveWhitespace = true})
                                    {
                                        using (var inputStream = _fileSystem.open_file_readonly(targetFile))
                                        {
                                            document.Load(inputStream);
                                        }

                                        bool succeeded = transformation.Apply(document);
                                        if (succeeded)
                                        {
                                            this.Log().Debug(() => "Transform applied successfully for '{0}'".format_with(targetFile));
                                            using (var memoryStream = new MemoryStream())
                                            {
                                                document.Save(memoryStream);
                                                memoryStream.Seek(0, SeekOrigin.Begin);
                                                using (var fileStream = _fileSystem.create_file(targetFile))
                                                {
                                                    memoryStream.CopyTo(fileStream);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            this.Log().Warn(() => "Transform failed for '{0}'".format_with(targetFile));
                                        }
                                    }
                                }
                            },
                        "Error transforming config file");
                }
            }
        }
        private static void TransformConfig(string configFileName, string transformFileName)
        {
            var document = new XmlTransformableDocument
            {
                PreserveWhitespace = true
            };

            document.Load(configFileName);

            var transformation = new XmlTransformation(transformFileName);

            if (!transformation.Apply(document))
                throw new Exception("Transformation Failed");

            document.Save(configFileName);
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            var opts = new Options();

            if (!CommandLine.Parser.Default.ParseArguments(args, opts))
            {
                return;
            }

            var dict = new Dictionary<string, string>();

            if (!File.Exists(opts.InputFile))
            {
                Console.WriteLine("Input file {0} doesn't exists", opts.InputFile);
                return;
            }

            if (!File.Exists(opts.TransformFile))
            {
                Console.WriteLine("Transform file {0} doesn't exists", opts.TransformFile);
                return;
            }

            foreach (var item in opts.Arguments)
            {
                if (item.IndexOf("=") < 1)
                {
                    Console.WriteLine("Invalid key-value pair: {0}", item);

                    Console.WriteLine(opts.GetHelp());
                    return;
                }
                else
                {
                    var index = item.IndexOf("=");
                    var key = item.Substring(0, index);
                    var value = item.Substring(index + 1);

                    dict.Add(key, value);
                }
            }

            TransformDocument transform;

            using (var fs = new FileStream(opts.TransformFile, FileMode.Open, FileAccess.Read))
            {
                transform = TransformDocument.LoadFrom(fs);
            }

            transform.ApplyArguments(dict);

            var doc = new XmlTransformableDocument();
            doc.Load(opts.InputFile);

            transform.ApplyTo(doc);

            using (var writer = XmlWriter.Create(opts.OutputFile, new XmlWriterSettings { Indent = true }))
            {
                doc.WriteTo(writer);
            }
        }