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; } }
private void transformToolStripMenuItem_Click(object sender, EventArgs e) { try { using (var xmlDoc = new XmlTransformableDocument()) { xmlDoc.PreserveWhitespace = true; xmlDoc.Load(new MemoryStream(Encoding.ASCII.GetBytes(fastColoredTextBoxSource.Text))); var logger = new TransformationLogger(); using (var xmlTrans = new XmlTransformation(new MemoryStream(Encoding.ASCII.GetBytes(fastColoredTextBoxXDT.Text)), logger)) { if (xmlTrans.Apply(xmlDoc)) { fastColoredTextBoxTransformed.Text = xmlDoc.OuterXml; } if (!string.IsNullOrEmpty(logger.Content)) { Message(logger.Content); } } tabControl1.SelectedIndex = 3; } } catch (Exception ex) { Message(ex.ToString()); } }
/// <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); } } } } }
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); }
public ActionResult Create(string webConfigXml, string transformXml) { try { var transformation = new XmlTransformation(transformXml, false, null); var document = new XmlDocument(); document.LoadXml(webConfigXml); var success = transformation.Apply(document); if (success) { 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)); } }
public ActionResult Create(string webConfigXml, string transformXml) { try { var transformation = new XmlTransformation(transformXml, false, null); var document = new XmlDocument(); document.LoadXml(webConfigXml); var success = transformation.Apply(document); if (success) { 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); } }
protected override void ProcessRecord() { this.TransformPath = this.TransformPath.Select(this.GetUnresolvedProviderPathFromPSPath).ToArray(); foreach (var t in this.TransformPath) { if (!File.Exists(t)) { throw new FileNotFoundException($"A transform, '{t}', could not be found."); } } foreach (var t in this.TransformPath) { using (var transformation = new XmlTransformation(t)) { this.WriteVerbose($"Applying '{t}' transform..."); if (!transformation.Apply(this._Document)) { throw new Microsoft.Web.XmlTransform.XmlTransformationException($"Failed to apply transform '{t}'."); } } } }
public void OkEncodeDecodeReplace() { // arrange var encryptorDecryptor = new EncryptorDecryptor(); var inputFilePath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.config"); var transformFilePath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.Debug.config"); string result; // act using (var input = new XmlTransformableDocument()) using (var transformer = new XmlTransformation(transformFilePath)) { input.Load(inputFilePath); transformer.Apply(input); using (var stringWriter = new StringWriter()) using (var xmlWriter = XmlWriter.Create(stringWriter)) { input.WriteContentTo(xmlWriter); xmlWriter.Flush(); result = stringWriter.ToString(); var xmlDoc = XDocument.Parse(result); var root = xmlDoc.Root; // assert var ecnrypteNode2 = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted2"); var ecnrypteNode2Attrubute = ecnrypteNode2.Attribute("serializeAs").Value; encryptorDecryptor.Decrypt(ecnrypteNode2Attrubute).Should().Be("String"); var encryptedNode2Value = ecnrypteNode2.Value; encryptorDecryptor.Decrypt(encryptedNode2Value).Should().Be("SomeNewEncryptedValue2"); } } }
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]); }
private static void load_areas(ControllerResolver resolver) { List<string> privateBins = new List<string>() { "bin" }; MethodInfo m = null, funsion = null; // check if i am running under mono at runtime. bad coding style bool isMono = Type.GetType("Mono.Runtime") != null; if (!isMono) { m = typeof(AppDomainSetup).GetMethod("UpdateContextProperty", BindingFlags.NonPublic | BindingFlags.Static); funsion = typeof(AppDomain).GetMethod("GetFusionContext", BindingFlags.NonPublic | BindingFlags.Instance); } foreach (var dir in Directory.GetDirectories(ServerUtil.MapPath("~"))) { string areaName = Path.GetFileName(dir).ToLowerInvariant(); if (IGNORES_DIR.Contains(areaName)) continue; // check if the dir is a valid area string configfile = Path.Combine(dir, "area.config"); if (!File.Exists(configfile)) continue; // load area config XmlNode node = null; using (XmlTransformableDocument x = new XmlTransformableDocument()) { x.Load(configfile); string localfile = Path.Combine(dir, "area.local.config"); if (File.Exists(localfile)) { using (XmlTransformation t = new XmlTransformation(localfile)) { t.Apply(x); } } node = x.DocumentElement; } AreaConfig config = AreaConfig.GetConfig(node); config.VP = "/" + areaName; config.AreaKey = areaName; Areas.Add(@"/" + areaName, config); // load assemblies string bindir = Path.Combine(dir, "bin"); if (Directory.Exists(bindir)) { privateBins.Add(bindir); if (!isMono) { // hack !!! if (m != null && funsion != null) { m.Invoke(null, new object[] { funsion.Invoke(AppDomain.CurrentDomain, null), "PRIVATE_BINPATH", privateBins.Join(";") }); m.Invoke(null, new object[] { funsion.Invoke(AppDomain.CurrentDomain, null), "SHADOW_COPY_DIRS", privateBins.Join(";") }); } } List<Assembly> assemblies = new List<Assembly>(); foreach (var item in Directory.GetFiles(bindir, "*.dll", SearchOption.TopDirectoryOnly)) { try { if (isMono) assemblies.Add(Assembly.Load(File.ReadAllBytes(item))); else assemblies.Add(AppDomain.CurrentDomain.Load(Path.GetFileNameWithoutExtension(item))); } catch (BadImageFormatException) { } } Dictionary<string, Type> types = new Dictionary<string, Type>(); foreach (var asm in assemblies) { foreach (var item in resolver.GetsControllerFromAssembly(asm)) { types[item.Key] = item.Value; } } resolver.SetSiteControllers(areaName, types); } } }
/// <summary> /// Make transformation of file <see cref="SourceFilePath" /> with transform file <see cref="TransformFile" /> to <paramref /// name="destinationFilePath" />. /// </summary> /// <param name="destinationFilePath"> File path of destination transformation. </param> /// <param name="forceParametersTask"> Invoke parameters task even if the parameters are not set with <see /// cref="SetParameters" /> . </param> /// <returns> Return true if transformation finish successfully, otherwise false. </returns> public bool Execute(string destinationFilePath, bool forceParametersTask = false) { if (string.IsNullOrWhiteSpace(destinationFilePath)) throw new ArgumentException("Destination file can't be empty.", "destinationFilePath"); Trace.TraceInformation("Start tranformation to '{0}'.", destinationFilePath); if (string.IsNullOrWhiteSpace(SourceFilePath) || !File.Exists(SourceFilePath)) throw new FileNotFoundException("Can't find source file.", SourceFilePath); if (string.IsNullOrWhiteSpace(TransformFile) || !File.Exists(TransformFile)) throw new FileNotFoundException("Can't find transform file.", TransformFile); Trace.TraceInformation("Source file: '{0}'.", SourceFilePath); Trace.TraceInformation("Transform file: '{0}'.", TransformFile); try { var transformFile = ReadContent(TransformFile); if ((_parameters != null && _parameters.Count > 0) || forceParametersTask) { ParametersTask parametersTask = new ParametersTask(); if (_parameters != null) parametersTask.AddParameters(_parameters); transformFile = parametersTask.ApplyParameters(transformFile); } XmlDocument document = new XmlDocument(); document.Load(SourceFilePath); XmlTransformation transformation = new XmlTransformation(transformFile, false, _transfomrationLogger); bool result = transformation.Apply(document); document.Save(destinationFilePath); return result; } catch (Exception e) { Trace.TraceError(e.Message); return false; } }
/// <summary> /// Make transformation of file <see cref="SourceFilePath"/> with transform file <see cref="TransformFile"/> to <paramref name="destinationFilePath"/>. /// </summary> /// <param name="destinationFilePath">File path of destination transformation.</param> /// <returns>Return true if transformation finish successfully, otherwise false.</returns> public void Execute(string destinationFilePath) { if (string.IsNullOrWhiteSpace(destinationFilePath)) { throw new ArgumentException("Destination file can't be empty.", "destinationFilePath"); } if (string.IsNullOrWhiteSpace(SourceFilePath) || !File.Exists(SourceFilePath)) { throw new FileNotFoundException("Can't find source file.", SourceFilePath); } if (string.IsNullOrWhiteSpace(TransformFile) || !File.Exists(TransformFile)) { throw new FileNotFoundException("Can't find transform file.", TransformFile); } string transformFileContents = File.ReadAllText(TransformFile); var document = new XmlDocument(); try { document.Load(SourceFilePath); } catch (Exception ex) { throw new Exception(string.Format("Error loading source '{0}': {1}", SourceFilePath, ex.Message), ex); } var transformation = new XmlTransformation(transformFileContents, false, _transformationLogger); try { bool result = transformation.Apply(document); } catch (Exception ex) { throw new Exception(string.Format("Error generating '{0}': {1}", destinationFilePath, ex.Message), ex); } document.Save(destinationFilePath); }