public static void TransformConfig(string configFileName, string transformFileName) { try { using (var document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; document.Load(configFileName); using (var transform = new XmlTransformation(transformFileName)) { if (transform.Apply(document)) { document.Save(configFileName); } else { throw new Exception("Transformation Failed"); } } } } catch (Exception xmlException) { Console.WriteLine(xmlException.Message); } }
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( $"Failed to transform \"{sourceFile}\" using \"{transformFile}\" to \"{targetFile}\"" ); } document.Save(targetFile.ToString()); } }
/// <inheritdoc/> public bool Transform(string source, string transform, string destination) { // Parameter validation Contract.Requires(!string.IsNullOrWhiteSpace(source)); Contract.Requires(!string.IsNullOrWhiteSpace(transform)); Contract.Requires(!string.IsNullOrWhiteSpace(destination)); // File validation if (!File.Exists(source)) { throw new FileNotFoundException(Resources.Resources.ErrorMessage_SourceFileNotFound, source); } if (!File.Exists(transform)) { throw new FileNotFoundException(Resources.Resources.ErrorMessage_TransformFileNotFound, transform); } using (XmlTransformableDocument document = new XmlTransformableDocument()) using (XmlTransformation transformation = new XmlTransformation(transform, this.logger)) { document.PreserveWhitespace = true; document.Load(source); var success = transformation.Apply(document); if (success) { document.Save(destination); } return(success); } }
public override bool Execute() { Log.LogMessage("Begin TransformXmlFiles"); if (TransformFiles?.Any() ?? false) { Log.LogMessage("Creating Microsoft.Web.Publishing.Tasks.TransformXml"); foreach (var inputFile in TransformFiles) { Log.LogMessage($"Preparing to transform '{inputFile.ItemSpec}'"); //Get the env name var fileParts = Path.GetFileNameWithoutExtension(inputFile.ItemSpec).Split('.'); var envName = fileParts.LastOrDefault(); //Build output directory as base output directory plus environment plus project (if supplied) var outDir = Path.Combine(OutputDirectory, envName); if (!String.IsNullOrEmpty(ProjectName)) { outDir = Path.Combine(outDir, ProjectName); } //Build the output path var outFile = Path.Combine(outDir, TargetFile); //Make sure the directory exists if (!Directory.Exists(outDir)) { Log.LogMessage($"Creating directory '{outDir}'"); Directory.CreateDirectory(outDir); } ; //Transform the config var transform = new XmlTransformation(inputFile.ItemSpec); var sourceDocument = new XmlTransformableDocument() { PreserveWhitespace = true }; sourceDocument.Load(SourceFile); Log.LogMessage($"Transforming file"); if (transform.Apply(sourceDocument)) { sourceDocument.Save(outFile); } else { Log.LogError($"Error transforming file"); return(false); }; } ; } ; Log.LogMessage("End TransformXmlFiles"); return(true); }
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 void Transform(string configFilename, string transformFilename, string outputFilename) { Output?.WriteActionBlock(context, "Applying config transformation", new Dictionary <string, object> { ["Source"] = configFilename, ["Transform"] = transformFilename, ["Output"] = outputFilename, }); try { using (var configDoc = new XmlTransformableDocument()) { configDoc.PreserveWhitespace = true; configDoc.Load(configFilename); using (var transformDoc = new XmlTransformation(transformFilename)) { if (!transformDoc.Apply(configDoc)) { throw new ApplicationException("Failed to apply config transformation!"); } } configDoc.Save(outputFilename); } //Output?.WriteLine($"Applying configuration transform '{transformFilename}' to config file '{configFilename}'...", ConsoleColor.Gray); } catch (Exception error) { Output?.WriteErrorBlock(context, error.UnfoldMessages()); throw; } }
/// <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, bool install) { // Extract paths from XML. var fileToTransform = GetAttributeValue(xmlData, "file"); 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> /// Transforms config file. /// </summary> /// <param name="fileSystem">The filesystem.</param> /// <param name="sourceFile">Source config file.</param> /// <param name="transformFile">Tranformation to apply.</param> /// <param name="targetFile">Target config file.</param> /// <param name="logger">Logger for the transfomration process</param> public static void TransformConfig(IFileSystem fileSystem, FilePath sourceFile, FilePath transformFile, FilePath targetFile, IXmlTransformationLogger logger = null) { if (fileSystem == null) { throw new ArgumentNullException(nameof(fileSystem), "File system is null."); } CheckNulls(sourceFile, transformFile, targetFile); IFile sourceConfigFile = fileSystem.GetFile(sourceFile), transformConfigFile = fileSystem.GetFile(transformFile), targetConfigFile = fileSystem.GetFile(targetFile); using (Stream sourceStream = sourceConfigFile.OpenRead(), transformStream = transformConfigFile.OpenRead(), targetStream = targetConfigFile.OpenWrite()) using (var document = new XmlTransformableDocument { PreserveWhitespace = true }) using (var transform = new XmlTransformation(transformStream, logger)) { document.Load(sourceStream); if (!transform.Apply(document)) { throw new CakeException( $"Failed to transform \"{sourceFile}\" using \"{transformFile}\" to \"{targetFile}\"" ); } document.Save(targetStream); } }
private void Transform_TestRunner_ExpectFail(string source, string transform, string expectedLog) { string src = CreateATestFile("source.config", source); string transformFile = CreateATestFile("transform.config", transform); string destFile = GetTestFilePath("result.config"); var logger = new TestTransformationLogger(); bool succeed; using (var x = new XmlTransformableDocument()) { x.PreserveWhitespace = true; x.Load(src); using (var xmlTransform = new XmlTransformation(transformFile, logger)) { succeed = xmlTransform.Apply(x); x.Save(destFile); } } //test Assert.AreEqual(false, succeed); CompareMultiLines(expectedLog, logger.LogText); }
void ApplyTransformation(string configFile, string transformFile, string destinationFile, IXmlTransformationLogger logger) { errorEncountered = false; var transformation = new XmlTransformation(transformFile, logger); var configurationFileDocument = new XmlTransformableDocument() { PreserveWhitespace = true }; configurationFileDocument.Load(configFile); var success = transformation.Apply(configurationFileDocument); if (!success || errorEncountered) { throw new CommandException($"The XML configuration file {configFile} failed with transformation file {transformFile}."); } if (!configurationFileDocument.ChildNodes.OfType <XmlElement>().Any()) { logger.LogWarning("The XML configuration file {0} no longer has a root element and is invalid after being transformed by {1}", new object[] { configFile, transformFile }); } configurationFileDocument.Save(destinationFile); }
static public void XMLTransform(String sourceFile, String destinationFile, String transformFile, bool isDryRun = false) { String outFile = destinationFile; if (String.IsNullOrWhiteSpace(outFile)) { outFile = sourceFile; } using (XmlTransformableDocument doc = new XmlTransformableDocument()) { doc.PreserveWhitespace = true; using (io.StreamReader sr = new io.StreamReader(sourceFile)) { doc.Load(sr); } using (XmlTransformation xt = new XmlTransformation(transformFile)) { xt.Apply(doc); if (!isDryRun) { doc.Save(outFile); } } } }
static void Transform_ExpectSuccess(string baseFileName) { string src = TestResource($"{baseFileName}_source.xml"); string transformFile = TestResource($"{baseFileName}_transform.xml"); string baselineFile = TestResource($"{baseFileName}_baseline.xml"); string destFile = OutputFile("result.xml", baseFileName); string expectedLog = TestResource($"{baseFileName}.log"); var logger = new TestTransformationLogger(); bool applied; using (var x = new XmlTransformableDocument { PreserveWhitespace = true }) { x.Load(src); using (var xmlTransform = new XmlTransformation(transformFile, logger)) { //execute applied = xmlTransform.Apply(x); x.Save(destFile); } } //test applied.ShouldBeTrue(baseFileName); File.ReadAllText(destFile).ShouldBe(File.ReadAllText(baselineFile)); logger.LogText.ShouldBe(File.ReadAllText(expectedLog)); }
/// <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 void Transform_ExpectFail(string baseFileName) { string src = TestResource($"{baseFileName}_source.xml"); string transformFile = TestResource($"{baseFileName}_transform.xml"); string destFile = OutputFile("result.xml", baseFileName); string expectedLog = TestResource($"{baseFileName}.log"); var logger = new TestTransformationLogger(); bool succeed; using (var x = new XmlTransformableDocument { PreserveWhitespace = true }) { x.Load(src); using (var xmlTransform = new XmlTransformation(transformFile, logger)) { //execute succeed = xmlTransform.Apply(x); x.Save(destFile); } } //test Assert.False(succeed, baseFileName); Assert.Equal(File.ReadAllText(expectedLog), logger.LogText); }
void ApplyTransformation(string configFile, string transformFile, string destinationFile, IXmlTransformationLogger logger) { var transformation = new XmlTransformation(transformFile, logger); var configurationFileDocument = new XmlTransformableDocument() { PreserveWhitespace = true }; configurationFileDocument.Load(configFile); var success = transformation.Apply(configurationFileDocument); if (!suppressTransformationErrors && (!success || transformFailed)) { log.ErrorFormat("The XML configuration file {0} failed with transformation file {1}.", configFile, transformFile); throw new CommandException(transformWarning); } if (!configurationFileDocument.ChildNodes.OfType <XmlElement>().Any()) { log.WarnFormat("The XML configuration file {0} no longer has a root element and is invalid after being transformed by {1}", configFile, transformFile); } configurationFileDocument.Save(destinationFile); }
private void Transform_TestRunner_ExpectSuccess(string source, string transform, string baseline, string expectedLog) { string src = CreateATestFile("source.config", source); string transformFile = CreateATestFile("transform.config", transform); string baselineFile = CreateATestFile("baseline.config", baseline); string destFile = GetTestFilePath("result.config"); TestTransformationLogger logger = new TestTransformationLogger(); XmlTransformableDocument x = new XmlTransformableDocument(); x.PreserveWhitespace = true; x.Load(src); Microsoft.Web.XmlTransform.XmlTransformation xmlTransform = new Microsoft.Web.XmlTransform.XmlTransformation(transformFile, logger); //execute bool succeed = xmlTransform.Apply(x); x.Save(destFile); xmlTransform.Dispose(); x.Dispose(); //test Assert.AreEqual(true, succeed); CompareFiles(baselineFile, destFile); CompareMultiLines(ReadResource(expectedLog), logger.LogText); }
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)); }
/// <summary> /// Processes the transform files. /// </summary> /// <param name="packageZip">The package zip.</param> private void ProcessTransformFiles(ZipArchive packageZip) { var transformFilesToProcess = packageZip .Entries .Where(e => e.FullName.StartsWith(CONTENT_PATH, StringComparison.OrdinalIgnoreCase) || e.FullName.StartsWith(CONTENT_PATH_ALT, StringComparison.OrdinalIgnoreCase)) .Where(e => e.FullName.EndsWith(TRANSFORM_FILE_SUFFIX, StringComparison.OrdinalIgnoreCase)); foreach (ZipArchiveEntry entry in transformFilesToProcess) { // process xdt string filename = entry.FullName.ReplaceFirstOccurrence(CONTENT_PATH, string.Empty).ReplaceFirstOccurrence(CONTENT_PATH_ALT, string.Empty); string transformTargetFile = Path.Combine(FileManagementHelper.ROOT_PATH, filename.Substring(0, filename.LastIndexOf(TRANSFORM_FILE_SUFFIX))); // process transform using (XmlTransformableDocument document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; document.Load(transformTargetFile); using (XmlTransformation transform = new XmlTransformation(entry.Open(), null)) { if (transform.Apply(document)) { BackupFile(transformTargetFile); document.Save(transformTargetFile); } } } } }
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 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); } }
private static void PerformXdtTransform(IPackageFile file, string targetPath, IProjectSystem projectSystem) { if (projectSystem.FileExists(targetPath)) { string content = Preprocessor.Process(file, projectSystem); try { using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null)) { using (var document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; // make sure we close the input stream immediately so that we can override // the file below when we save to it. using (var inputStream = projectSystem.OpenFile(targetPath)) { document.Load(inputStream); } bool succeeded = transformation.Apply(document); if (succeeded) { using (var memoryStream = new MemoryStream()) { // save the result into a memoryStream first so that if there is any // exception during document.Save(), the original file won't be truncated. document.Save(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using (var fileStream = projectSystem.CreateFile(targetPath)) { memoryStream.CopyTo(fileStream); } } } } } } catch (Exception exception) { throw new InvalidDataException( String.Format( CultureInfo.CurrentCulture, NuGetResources.XdtError + " " + exception.Message, targetPath, projectSystem.ProjectName), exception); } } }
public static void Transform( this Paths paths ) { var transformFiles = paths.GetTransformFiles(); // preserving whitespace seems buggy when not // letting the library handle streams itself // looked through the MS source, did not see a reason // why this was this case using var document = new XmlTransformableDocument { PreserveWhitespace = paths.Source == paths.Target }; document.Load(paths.Source); foreach (var transformFile in transformFiles) { using var transform = new XmlTransformation(transformFile); if (transform.Apply(document)) { Console.WriteLine(Invariant($" Applied: {transformFile}")); } else { Console.WriteLine(Invariant($" Failed: {transformFile}")); Console.WriteLine("Exiting.."); return; } } // the Save function does not Dispose its underlying Stream right away // but, using custom Stream objects and calling dispose on them // cannot be done because of issue above with whitespace // retries are not limited, since users can kill this program if they want var saved = false; Console.Write(" Saving.."); while (!saved) { try { document.Save(paths.Target); saved = true; } catch (IOException) { Console.Write("."); } Thread.Sleep(100); } Console.WriteLine(); Console.WriteLine(Invariant($" Saved: {paths.Target}")); }
private bool Transform(string packageName, System.Xml.XmlNode xmlData, bool uninstall = false) { // The config file we want to modify if (xmlData.Attributes != null) { var file = xmlData.Attributes.GetNamedItem("file").Value; var sourceDocFileName = VirtualPathUtility.ToAbsolute(file); // The xdt file used for tranformation var fileEnd = "install.xdt"; if (uninstall) { fileEnd = string.Format("un{0}", fileEnd); } var xdtfile = string.Format("{0}.{1}", xmlData.Attributes.GetNamedItem("xdtfile").Value, fileEnd); var xdtFileName = VirtualPathUtility.ToAbsolute(xdtfile); // The translation at-hand using (var xmlDoc = new XmlTransformableDocument()) { xmlDoc.PreserveWhitespace = true; xmlDoc.Load(HttpContext.Current.Server.MapPath(sourceDocFileName)); using (var xmlTrans = new XmlTransformation(HttpContext.Current.Server.MapPath(xdtFileName))) { if (xmlTrans.Apply(xmlDoc)) { // If we made it here, sourceDoc now has transDoc's changes // applied. So, we're going to save the final result off to // destDoc. try { xmlDoc.Save(HttpContext.Current.Server.MapPath(sourceDocFileName)); } catch (Exception e) { // Log error message var message = "Error executing TransformConfig package action (check file write permissions): " + e.Message; LogHelper.Error(typeof(TransformConfig), message, e); return(false); } } } } } return(true); }
private void btnExecute_Click(object sender, EventArgs e) { var sourceFile = tbSourceConfigFile.Text; if (string.IsNullOrEmpty(sourceFile)) { MessageBox.Show("Source file path is empty."); return; } if (!File.Exists(sourceFile)) { MessageBox.Show("Source file do not exist."); return; } var transformFile = tbTransformConfigFile.Text; if (string.IsNullOrEmpty(transformFile)) { MessageBox.Show("Transform file path is empty."); return; } if (!File.Exists(transformFile)) { MessageBox.Show("Transform file do not exist."); return; } var resultFile = tbResultConfigFile.Text; if (string.IsNullOrEmpty(resultFile)) { MessageBox.Show("Result file path is not specified."); return; } using var doc = new XmlTransformableDocument(); doc.Load(sourceFile); using var tranform = new XmlTransformation(transformFile); if (tranform.Apply(doc)) { doc.Save(resultFile); MessageBox.Show("OK!"); } else { MessageBox.Show("Could not apply transform."); } }
public void Execute(Model.ConfigurationFile file) { var fiProductionConfigurationPath = new FileInfo(file.ProductionConfigurationPath); //Remove old file if one exists if (fiProductionConfigurationPath.Exists) { fiProductionConfigurationPath.Delete(); } //Apply the transform and save to disk XmlTransformableDocument doc = transformConfigurationFile(file.BaseConfigurationPath, file.ProductionTransformPath); doc.Save(file.ProductionConfigurationPath); }
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); } } }
public static void TransformConfig(string configFileName, string transformFileName, string targetFileName) { var document = new XmlTransformableDocument(); document.PreserveWhitespace = true; document.Load(configFileName); var transformation = new XmlTransformation(transformFileName); if (!transformation.Apply(document)) { throw new Exception("Transformation Failed"); } document.Save(targetFileName); }
/// <inheritdoc/> public bool Transform(string sourcePath, string transformPath, string destinationPath) { if (string.IsNullOrWhiteSpace(sourcePath)) { throw new ArgumentNullException(nameof(sourcePath)); } if (string.IsNullOrWhiteSpace(sourcePath)) { throw new ArgumentNullException(nameof(transformPath)); } if (string.IsNullOrWhiteSpace(sourcePath)) { throw new ArgumentNullException(nameof(destinationPath)); } if (!File.Exists(sourcePath)) { throw new FileNotFoundException(Resources.Resources.ErrorMessage_SourceFileNotFound, sourcePath); } if (!File.Exists(transformPath)) { throw new FileNotFoundException(Resources.Resources.ErrorMessage_TransformFileNotFound, transformPath); } using (XmlTransformableDocument document = new XmlTransformableDocument()) using (XmlTransformation transformation = new XmlTransformation(transformPath, this.logger)) { using (XmlTextReader reader = new XmlTextReader(sourcePath)) { reader.DtdProcessing = DtdProcessing.Ignore; document.PreserveWhitespace = true; document.Load(reader); } var success = transformation.Apply(document); if (success) { document.Save(destinationPath); } return(success); } }
//public static void ApplyWeb(string configFilename, string outputFilename) //{ // PathEx.Delete(outputFilename); // File.Copy(configFilename, outputFilename); //} public static void Transform(string configFilename, string transformFilename, string outputFilename) { using (var configDoc = new XmlTransformableDocument()) { configDoc.PreserveWhitespace = true; configDoc.Load(configFilename); using (var transformDoc = new XmlTransformation(transformFilename)) { if (!transformDoc.Apply(configDoc)) { throw new ApplicationException("Failed to apply config transformation!"); } } configDoc.Save(outputFilename); } }
public static void TransformConfig(string configFileName, string transformFileName, string targetFileName) { var document = new XmlTransformableDocument(); document.PreserveWhitespace = true; document.Load(configFileName); var transformation = new XmlTransformation(transformFileName); if (!transformation.Apply(document)) { throw new Exception($"An error occurred applying the transform {transformFileName}"); } document.Save(targetFileName); Console.WriteLine($" Saved {targetFileName}"); }
private void Transform_TestRunner_ExpectFail(string source, string transform, string expectedLog) { string src = CreateATestFile("source.config", source); string transformFile = CreateATestFile("transform.config", transform); string destFile = GetTestFilePath("result.config"); TestTransformationLogger logger = new TestTransformationLogger(); XmlTransformableDocument x = new XmlTransformableDocument(); x.PreserveWhitespace = true; x.Load(src); Microsoft.Web.XmlTransform.XmlTransformation xmlTransform = new Microsoft.Web.XmlTransform.XmlTransformation(transformFile, logger); //execute bool succeed = xmlTransform.Apply(x); x.Save(destFile); xmlTransform.Dispose(); x.Dispose(); //test Assert.AreEqual(false, succeed); CompareMultiLines(expectedLog, logger.LogText); }
private IServiceResult SaveTransformedFile(XmlTransformableDocument transformedDocument, string destinationFilePath) { try { this.filesystemAccessor.EnsureParentDirectoryExists(destinationFilePath); using (var textWriter = this.filesystemAccessor.GetTextWriter(destinationFilePath)) { transformedDocument.Save(textWriter); } return new SuccessResult(Resources.ConfigurationFileTransformationService.SaveSucceededMessageTemplate, destinationFilePath); } catch (Exception saveException) { return new FailureResult( Resources.ConfigurationFileTransformationService.SaveFailedWithExceptionMessageTemplate, destinationFilePath, saveException.Message); } }
static void Main(string[] args) { Console.WriteLine("TransformXml.exe source.xml transform.xml destination.xml"); var inputStream = new MemoryStream(File.ReadAllBytes(args[0])); XmlTransformableDocument document = new XmlTransformableDocument(); document.PreserveWhitespace = true; document.Load(inputStream); XmlTransformation transformation; transformation = new XmlTransformation(args[1], new Logger()); transformation.Apply(document); document.Save(args[2]); }