Wednesday, September 30, 2015

XDT Console Application

XML Document Transformations, or XTD, is a great way to transform your app and web config files between environments or builds. It is directly supported by Visual Studio and other third party tools, such as Octopus Deploy.

So how can you transform config files on your own? For starters uou can use great free tools like the Web.config Transformation Tester (which is open source) from AppHarbor.

Would you rather transform your files via command line? Then just do it yourself! Pull down the Microsoft.Web.Xdt package from NuGet, and then copy and paste this code to implement your own simple console app...

Program.cs

namespace XDT
{
  using System;
  using System.IO;
  using System.Text;
  using System.Xml;
 
  using Microsoft.Web.XmlTransform;
 
  public class Program
  {
    private static int Main(string[] args)
    {
      if (args.Length != 3)
      {
        Console.WriteLine("Required Arguments: [ConfigPath] [TransformPath] [TargetPath]");
        return 400;
      }
 
      var configPath = args[0];
      if (!File.Exists(configPath))
      {
        Console.WriteLine("Config not found");
        return 404;
      }
 
      var transformPath = args[1];
      if (!File.Exists(transformPath))
      {
        Console.WriteLine("Transform not found");
        return 404;
      }
 
      try
      {
        var targetPath = args[2];
        var configXml = File.ReadAllText(configPath);
        var transformXml = File.ReadAllText(transformPath);
 
        using (var document = new XmlTransformableDocument())
        {
          document.PreserveWhitespace = true;
          document.LoadXml(configXml);
 
          using (var transform = new XmlTransformation(transformXml, false, null))
          {
            if (transform.Apply(document))
            {
              var stringBuilder = new StringBuilder();
              var xmlWriterSettings = new XmlWriterSettings
              {
                Indent = true,
                IndentChars = "  "
              };
 
              using (var xmlTextWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
              {
                document.WriteTo(xmlTextWriter);
              }
 
              var resultXml = stringBuilder.ToString();
              File.WriteAllText(targetPath, resultXml);
              return 0;
            }
 
            Console.WriteLine("Transformation failed for unknown reason");
          }
        }
      }
      catch (XmlTransformationException xmlTransformationException)
      {
        Console.WriteLine(xmlTransformationException.Message);
      }
      catch (XmlException xmlException)
      {
        Console.WriteLine(xmlException.Message);
      }
 
      return 500;
    }
  }
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics