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 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); } }
protected void TelemetryInitializerInstall(string sourceDocument, params string[] telemetryInitializerTypes) { string resourceName = "Microsoft.ApplicationInsights.Resources.ApplicationInsights.config.install.xdt"; Stream stream = typeof(ModuleTransformTests).Assembly.GetManifestResourceStream(resourceName); using (StreamReader reader = new StreamReader(stream)) { string transform = reader.ReadToEnd(); XmlTransformation transformation = new XmlTransformation(transform, false, null); XmlDocument targetDocument = new XmlDocument(); targetDocument.LoadXml(sourceDocument); transformation.Apply(targetDocument); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); manager.AddNamespace("ai", AppInsightsNamespace); int moduleIndex = 0; foreach (XPathNavigator module in targetDocument.CreateNavigator().Select("/ai:ApplicationInsights/ai:TelemetryInitializers/ai:Add/@Type", manager)) { string contextInitializerType = telemetryInitializerTypes[moduleIndex++]; Assert.Equal(module.Value, contextInitializerType); } Assert.Equal(moduleIndex, telemetryInitializerTypes.Length); } }
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 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 void Transform(string sourceFile, IEnumerable<string> tranformFiles, string destinationFile) { var sourceXmlString = _fileSystem.File.ReadAllText(sourceFile); var sourceFileEncoding = GetEncoding(sourceXmlString); var intermediateXmlString = sourceXmlString; foreach (var transformFile in tranformFiles) { var sourceDocument = new XmlTransformableDocument(); var transformXmlString = _fileSystem.File.ReadAllText(transformFile); var transformFileEncoding = GetEncoding(transformXmlString); var transformXmlBytes = transformFileEncoding.GetBytes(transformXmlString); using (var memoryStream = new MemoryStream(transformXmlBytes)) { var transformation = new XmlTransformation(memoryStream, _xmlTransformationLogger); sourceDocument.LoadXml(intermediateXmlString); transformation.Apply(sourceDocument); intermediateXmlString = sourceDocument.OuterXml; } } var xDocument = XDocument.Parse(intermediateXmlString, LoadOptions.PreserveWhitespace); intermediateXmlString = $"{xDocument.Declaration}{Environment.NewLine}{xDocument.Document}"; _fileSystem.File.WriteAllText(destinationFile, intermediateXmlString, sourceFileEncoding); }
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 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()); } }
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; }
public XmlDocument Apply() { using (var tranform = new XmlTransformation(new MemoryStream(Encoding.UTF8.GetBytes(Transform.InnerXml)), new TraceTransformationLogger())) { if (tranform.Apply(Source)) { return Source; } throw new ApplicationException("the transformation was not successful"); } }
public void ApplyTo(XmlTransformableDocument target) { using (var ms = new MemoryStream()) { this.document.Save(ms); ms.Seek(0, SeekOrigin.Begin); var transformation = new XmlTransformation(ms, this.Logger); transformation.Apply(target); } }
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); } } }
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 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); } } }
public override bool Execute() { var originalFileXml = new System.Xml.XmlDocument(); originalFileXml.Load(Source.ItemSpec); using (var xmlTransform = new XmlTransformation(Transform.ItemSpec)) { if (xmlTransform.Apply(originalFileXml) == false) return false; originalFileXml.Save(Destination.ItemSpec); } 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); }
/// <summary> /// /// </summary> /// <param name="transformFile"></param> /// <returns></returns> public XmlTransformation OpenTransformFile(string transformFile) { XmlTransformation transformation; try { transformation = new XmlTransformation(transformFile); } catch (XmlException exception) { throw exception; } catch (Exception exception2) { throw; } return transformation; }
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); }
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); } } }
public void CS_D_XDT_TestInstallThenUninstall() { var tests = new int[] { 0, 2, 3 }; foreach(int i in tests) { var filenameIn = String.Format("Package{0}.appxmanifest", i); var filenameInstalled = String.Format("Package{0}.installed.appxmanifest", i); var filenameUninstalled = String.Format("Package{0}.uninstalled.appxmanifest", i); var filenameReference = String.Format("Package{0}.reference.appxmanifest", i); Console.WriteLine("Loading {0}", filenameIn); var xml = new XmlDocument(); xml.Load(filenameIn); Console.WriteLine("Installing XML"); using (var transform = new XmlTransformation("Package.appxmanifest.install.xdt")) { Assert.IsTrue(transform.Apply(xml)); } Console.WriteLine("Saving {0}", filenameInstalled); xml.Save(filenameInstalled); Console.WriteLine("Verifying output"); string actual = File.ReadAllText(filenameInstalled); string expected = File.ReadAllText(filenameReference); Assert.AreEqual(expected, actual); Console.WriteLine("Uninstalling XML"); using (var transform = new XmlTransformation("Package.appxmanifest.uninstall.xdt")) { Assert.IsTrue(transform.Apply(xml)); } Console.WriteLine("Saving {0}", filenameUninstalled); xml.Save(filenameUninstalled); Console.WriteLine("Verifying output"); actual = File.ReadAllText(filenameUninstalled); expected = File.ReadAllText(filenameIn); Assert.AreEqual(expected, actual); } }
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; }
public bool Transform(string source, string transform, string destination) { if (string.IsNullOrEmpty(destination)) throw new ArgumentException("destination cannot be null or empty"); var sourceContent = _fileSystem.File.ReadAllText(source); var transformation = new XmlTransformation(_fileSystem.File.OpenRead(transform), null); var sourceDocument = new XmlTransformableDocument { PreserveWhitespace = true }; sourceDocument.LoadXml(sourceContent); transformation.Apply(sourceDocument); _fileSystem.File.WriteAllText(destination, sourceDocument.OuterXml); return true; }
public ActionResult Create(string webConfigXml, string transformXml) { try { using (var document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; document.LoadXml(webConfigXml); using (var transform = new XmlTransformation(transformXml, false, null)) { if (transform.Apply(document)) { var stringBuilder = new StringBuilder(); var xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.IndentChars = " "; using (var xmlTextWriter = XmlTextWriter.Create(stringBuilder, xmlWriterSettings)) { document.WriteTo(xmlTextWriter); } return Content(stringBuilder.ToString(), "text/xml"); } else { return ErrorXml("Transformation failed for unkown reason"); } } } } catch (XmlTransformationException xmlTransformationException) { return ErrorXml(xmlTransformationException.Message); } catch (XmlException xmlException) { return ErrorXml(xmlException.Message); } }
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); } } } } }
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); } }
protected void ModulesUninstall(string sourceDocument) { string resourceName = "Microsoft.ApplicationInsights.Resources.ApplicationInsights.config.install.xdt"; string intermediaryDocument; Assembly assembly = typeof(ModuleTransformTests).Assembly; Stream stream = assembly.GetManifestResourceStream(resourceName); using (StreamReader reader = new StreamReader(stream)) { string transform = reader.ReadToEnd(); XmlTransformation transformation = new XmlTransformation(transform, false, null); XmlDocument targetDocument = new XmlDocument(); targetDocument.LoadXml(sourceDocument); transformation.Apply(targetDocument); intermediaryDocument = targetDocument.OuterXml; } resourceName = "Microsoft.ApplicationInsights.Resources.ApplicationInsights.config.uninstall.xdt"; stream = assembly.GetManifestResourceStream(resourceName); using (StreamReader reader = new StreamReader(stream)) { string transform = reader.ReadToEnd(); XmlTransformation transformation = new XmlTransformation(transform, false, null); XmlDocument targetDocument = new XmlDocument(); targetDocument.LoadXml(intermediaryDocument); transformation.Apply(targetDocument); string uninstalledDocument = targetDocument.OuterXml; XElement cleanDocument = XElement.Parse(sourceDocument); XElement dirtyDocument = XElement.Parse(uninstalledDocument); Assert.True(XNode.DeepEquals(cleanDocument, dirtyDocument)); } }
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)); } } } }
public ExitCode TransformFile( [NotNull] FileInfo originalFile, [NotNull] FileInfo transformationFile, [NotNull] DirectoryInfo originalFileRootDirectory, [NotNull] DirectoryInfo transformationFileRootDirectory) { if (originalFile == null) { throw new ArgumentNullException(nameof(originalFile)); } if (transformationFile == null) { throw new ArgumentNullException(nameof(transformationFile)); } if (originalFileRootDirectory == null) { throw new ArgumentNullException(nameof(originalFileRootDirectory)); } if (transformationFileRootDirectory == null) { throw new ArgumentNullException(nameof(transformationFileRootDirectory)); } if (!originalFile.Exists) { _logger.Error("The original file to transform '{FullName}' does not exist", originalFile.FullName); return(ExitCode.Failure); } if (!transformationFile.Exists) { _logger.Error( "The transformation file '{FullName}' to transform '{FullName1}' does not exist", transformationFile.FullName, originalFile.FullName); return(ExitCode.Failure); } string destFilePath = Path.GetTempFileName(); _logger.Debug( "Transforming original '{FullName}' with transformation '{FullName1}' using temp target '{DestFilePath}'", originalFile.FullName, transformationFile.FullName, destFilePath); using (var xmlTransformableDocument = new XmlTransformableDocument { PreserveWhitespace = true }) { xmlTransformableDocument.Load(originalFile.FullName); bool succeed; using ( var transform = new Microsoft.Web.XmlTransform.XmlTransformation(transformationFile.FullName)) { succeed = transform.Apply(xmlTransformableDocument); } if (!succeed) { _logger.Error( "Transforming failed, original '{FullName}' with transformation '{FullName1}' using temp target '{DestFilePath}'", originalFile.FullName, transformationFile.FullName, destFilePath); return(ExitCode.Failure); } _logger.Debug( "Transforming succeeded, original '{FullName}' with transformation '{FullName1}' using temp target '{DestFilePath}'", originalFile.FullName, transformationFile.FullName, destFilePath); using (var destinationFileStream = new FileStream(destFilePath, FileMode.OpenOrCreate)) { xmlTransformableDocument.Save(destinationFileStream); } } File.Copy(destFilePath, originalFile.FullName, true); _logger.Debug( "Rewritten original '{FullName}' with transformation '{FullName1}' using temp target '{DestFilePath}'", originalFile.FullName, transformationFile.FullName, destFilePath); string originalRelativePath = originalFile.GetRelativePath(originalFileRootDirectory); string transformRelativePath = transformationFile.GetRelativePath(transformationFileRootDirectory); _logger.Information( "Transformed original '{OriginalRelativePath}' with transformation '{TransformRelativePath}'", originalRelativePath, transformRelativePath); if (File.Exists(destFilePath)) { File.Delete(destFilePath); _logger.Debug("Deleted temp transformation destination file '{DestFilePath}'", destFilePath); } return(ExitCode.Success); }
public static void Transform([NotNull] DeploymentExecutionDefinition deploymentExecutionDefinition, [NotNull] DirectoryInfo contentDirectory, [NotNull] ILogger logger) { if (deploymentExecutionDefinition is null) { throw new ArgumentNullException(nameof(deploymentExecutionDefinition)); } if (contentDirectory is null) { throw new ArgumentNullException(nameof(contentDirectory)); } if (logger is null) { throw new ArgumentNullException(nameof(logger)); } try { if (string.IsNullOrWhiteSpace(deploymentExecutionDefinition.WebConfigTransformFile)) { return; } logger.Debug( "Found web config transformation {Transformation} for deployment execution definition {Deployment}", deploymentExecutionDefinition.WebConfigTransformFile, deploymentExecutionDefinition); var transformFile = new FileInfo(deploymentExecutionDefinition.WebConfigTransformFile); if (transformFile.Exists) { string tempFileName = Path.GetRandomFileName(); var webConfig = new FileInfo(Path.Combine(contentDirectory.FullName, "web.config")); if (webConfig.Exists) { using var x = new XmlTransformableDocument { PreserveWhitespace = true }; x.Load(webConfig.FullName); using var transform = new Microsoft.Web.XmlTransform.XmlTransformation(transformFile.FullName); bool succeed = transform.Apply(x); if (succeed) { using var fsDestFileStream = new FileStream(tempFileName, FileMode.OpenOrCreate); x.Save(fsDestFileStream); } } var tempFileInfo = new FileInfo(tempFileName); if (tempFileInfo.Exists && tempFileInfo.Length > 0) { logger.Information( "Successfully transformed web.config with transformation {Transformation}", deploymentExecutionDefinition.WebConfigTransformFile); tempFileInfo.CopyTo(webConfig.FullName, true); } else { logger.Warning( "Failed to transform web.config with transformation {Transformation}", deploymentExecutionDefinition.WebConfigTransformFile); } tempFileInfo.Delete(); } } catch (Exception ex) when(!ex.IsFatal()) { logger.Error(ex, "Could not apply web.config transform with {Transform}", deploymentExecutionDefinition.WebConfigTransformFile); throw; } }