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); }
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); } } }
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 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); } }
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; }
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()); } }
private static void PerformXdtTransform(IPackageFile file, string targetPath, IProjectSystem projectSystem) { if (projectSystem.FileExists(targetPath)) { string content = Preprocessor.Process(file, projectSystem); try { using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null)) { using (var document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; // make sure we close the input stream immediately so that we can override // the file below when we save to it. using (var inputStream = projectSystem.OpenFile(targetPath)) { document.Load(inputStream); } bool succeeded = transformation.Apply(document); if (succeeded) { using (var memoryStream = new MemoryStream()) { // save the result into a memoryStream first so that if there is any // exception during document.Save(), the original file won't be truncated. document.Save(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using (var fileStream = projectSystem.CreateFile(targetPath)) { memoryStream.CopyTo(fileStream); } } } } } } catch (Exception exception) { throw new InvalidDataException( String.Format( CultureInfo.CurrentCulture, NuGetResources.XdtError + " " + exception.Message, targetPath, projectSystem.ProjectName), exception); } } }
public 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); } }
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; }
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); }
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; } } }
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); }
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 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)); } } } }
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); } } }
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."; } }
/// <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); } }
/// <summary> /// Perform an XDT transform using the transformFile against the sourceFile and save the results to the destinationFile. /// </summary> /// <param name="transformFile">an XDT file</param> /// <param name="sourceFile">an XML source file suitable for Xml Document Transforming</param> /// <param name="destinationFile">a full path to the destination file where you want to save the transformed file.</param> /// <returns></returns> private bool ProcessXmlDocumentTransformation( string transformFile, string sourceFile, string destinationFile ) { bool isSuccess = true; if ( !File.Exists( sourceFile ) ) { ExceptionLogService.LogException( new FileNotFoundException( string.Format( "Source transform file ({0}) does not exist.", sourceFile ) ), System.Web.HttpContext.Current ); return false; } // This really shouldn't happen since it was theoretically just added before // we were called. if ( !File.Exists( transformFile ) ) { ExceptionLogService.LogException( new FileNotFoundException( string.Format( "Transform file ({0}) does not exist.", transformFile ) ), System.Web.HttpContext.Current ); return false; } try { using ( XmlTransformableDocument document = new XmlTransformableDocument() ) { document.PreserveWhitespace = true; document.Load( sourceFile ); using ( XmlTransformation transform = new XmlTransformation( transformFile ) ) { isSuccess = transform.Apply( document ); if ( isSuccess ) { document.Save( destinationFile ); File.Delete( transformFile ); } } } } catch ( Exception ex ) { isSuccess = false; ExceptionLogService.LogException( new FileNotFoundException( string.Format( "Error while transforming {0} : {1}.", sourceFile, ex.Message ) ), System.Web.HttpContext.Current ); } return isSuccess; }
/// <summary> /// Transform the web.config to inject the maximum allowed content length /// into the requestLimits tag of the requestFiltering section of the web.config. /// </summary> /// <returns>true if the transform was successful; false otherwise.</returns> protected bool SaveMaxAllowedContentLength() { string webConfig = System.Web.HttpContext.Current.Server.MapPath( Path.Combine( "~", "web.config" ) ); bool isSuccess = false; using ( XmlTransformableDocument document = new XmlTransformableDocument() ) { document.PreserveWhitespace = true; document.Load( webConfig ); int maxContentLengthBytes = int.Parse( numbMaxSize.Text ) * 1048576; string transformString = string.Format( @"<?xml version='1.0'?> <configuration xmlns:xdt='http://schemas.microsoft.com/XML-Document-Transform'> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength='{0}' xdt:Transform='SetAttributes(maxAllowedContentLength)'/> </requestFiltering> </security> </system.webServer> </configuration>", maxContentLengthBytes ); using ( XmlTransformation transform = new XmlTransformation( transformString, false, null ) ) { isSuccess = transform.Apply( document ); document.Save( webConfig ); } } return isSuccess; }
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; }
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(); } }
/// <summary> /// The save transformed file. /// </summary> /// <param name="document"> /// The document. /// </param> /// <param name="destinationFile"> /// The destination file. /// </param> /// <exception cref="Exception"> /// </exception> private void SaveTransformedFile(XmlTransformableDocument document, string destinationFile) { try { document.Save(destinationFile); } catch (XmlException ex) { throw; } catch (Exception ex) { throw new Exception(string.Format((IFormatProvider)CultureInfo.CurrentCulture, "Writing to destination failed {0}", new[] { (object)ex.Message }), ex); } }
/// <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); } } } }
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); }
private void SaveTransformedFile(XmlTransformableDocument document, string destinationFile) { try { document.Save(destinationFile); } catch (System.Xml.XmlException) { throw; } catch (Exception ex) { throw new Exception(string.Format("Could not write Destination file: {0}", ex.Message), ex); } }
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"); } } }
/// <summary> /// Transforms the file for the corresponding XDT file. /// </summary> /// <param name="transformFile">The transform file.</param> /// <returns> /// true if the transformation was successful; false otherwise. /// </returns> private bool ProcessXmlDocumentTransformation( string transformFile ) { bool isSuccess = true; string sourceFile = transformFile.Remove( transformFile.Length - _transformFilePrefix.Length ); transformFile = System.Web.HttpContext.Current.Server.MapPath( Path.Combine( "~", transformFile ) ); sourceFile = System.Web.HttpContext.Current.Server.MapPath( Path.Combine( "~", sourceFile ) ); if ( !File.Exists( sourceFile ) ) { ExceptionLogService.LogException( new FileNotFoundException( string.Format( "Source transform file ({0}) does not exist.", sourceFile ) ), System.Web.HttpContext.Current ); return false; } // This really shouldn't happen since it was theoretically just added before // we were called. if ( !File.Exists( transformFile ) ) { ExceptionLogService.LogException( new FileNotFoundException( string.Format( "Transform file ({0}) does not exist.", transformFile ) ), System.Web.HttpContext.Current ); return false; } string destFile = sourceFile; using ( XmlTransformableDocument document = new XmlTransformableDocument() ) { document.PreserveWhitespace = true; document.Load( sourceFile ); using ( XmlTransformation transform = new XmlTransformation( transformFile ) ) { isSuccess = transform.Apply( document ); document.Save( destFile ); } } if ( isSuccess ) { File.Delete( transformFile ); } return isSuccess; }