static void Main(string[] args) { if (args.Length != 3) { Console.WriteLine("Wrong number of arguments"); Console.WriteLine("WebConfigTransformer ConfigFilename TransformFilename ResultFilename"); Environment.Exit(1); } if (!System.IO.File.Exists(args[0]) && !System.IO.File.Exists(args[1])) { Console.WriteLine("The config or transform file do not exist!"); Environment.Exit(2); } using (var doc = new Microsoft.Web.XmlTransform.XmlTransformableDocument()) { doc.Load(args[0]); using (var tranform = new Microsoft.Web.XmlTransform.XmlTransformation(args[1])) { if (tranform.Apply(doc)) { doc.Save(args[2]); } else { Console.WriteLine("Could not apply transform"); Environment.Exit(3); } } } }
public void XmlTransform_Support_WriteToStream() { string src = CreateATestFile("Web.config", "Web.config"); string transformFile = CreateATestFile("Web.Release.config", "Web.Release.config"); string destFile = GetTestFilePath("MyWeb.config"); //execute Microsoft.Web.XmlTransform.XmlTransformableDocument x = new Microsoft.Web.XmlTransform.XmlTransformableDocument(); x.PreserveWhitespace = true; x.Load(src); Microsoft.Web.XmlTransform.XmlTransformation transform = new Microsoft.Web.XmlTransform.XmlTransformation(transformFile); bool succeed = transform.Apply(x); FileStream fsDestFile = new FileStream(destFile, FileMode.OpenOrCreate); x.Save(fsDestFile); //verify, we have a success transform Assert.AreEqual(true, succeed); //verify, the stream is not closed Assert.AreEqual(true, fsDestFile.CanWrite, "The file stream can not be written. was it closed?"); //sanity verify the content is right, (xml was transformed) fsDestFile.Dispose(); string content = File.ReadAllText(destFile); Assert.IsFalse(content.Contains("debug=\"true\"")); List <string> lines = new List <string>(File.ReadLines(destFile)); //sanity verify the line format is not lost (otherwsie we will have only one long line) Assert.IsTrue(lines.Count > 10); //be nice transform.Dispose(); x.Dispose(); }
public void XmlTransform_Support_WriteToStream() { string src = CreateATestFile("Web.config", Properties.Resources.Web); string transformFile = CreateATestFile("Web.Release.config", Properties.Resources.Web_Release); string destFile = GetTestFilePath("MyWeb.config"); //execute Microsoft.Web.XmlTransform.XmlTransformableDocument x = new Microsoft.Web.XmlTransform.XmlTransformableDocument(); x.PreserveWhitespace = true; x.Load(src); Microsoft.Web.XmlTransform.XmlTransformation transform = new Microsoft.Web.XmlTransform.XmlTransformation(transformFile); bool succeed = transform.Apply(x); FileStream fsDestFile = new FileStream(destFile, FileMode.OpenOrCreate); x.Save(fsDestFile); //verify, we have a success transform Assert.AreEqual(true, succeed); //verify, the stream is not closed Assert.AreEqual(true, fsDestFile.CanWrite, "The file stream can not be written. was it closed?"); //sanity verify the content is right, (xml was transformed) fsDestFile.Close(); string content = File.ReadAllText(destFile); Assert.IsFalse(content.Contains("debug=\"true\"")); List<string> lines = new List<string>(File.ReadLines(destFile)); //sanity verify the line format is not lost (otherwsie we will have only one long line) Assert.IsTrue(lines.Count>10); //be nice transform.Dispose(); x.Dispose(); }
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(ReadResource(expectedLog), logger.LogText); }
static int Main(string[] args) { SystemEvents.SetConsoleEventHandler(ConsoleEventCallback); IDisposable impresonationContext = null; var config = new ConfigurationBuilder().AddCloudFoundry().Build(); var isConfigServerBound = config.AsEnumerable().Select(x => x.Key).Any(x => x == "vcap:services:p-config-server:0"); Console.WriteLine(isConfigServerBound); foreach (var item in config.AsEnumerable()) { Console.WriteLine($"{item.Key}: {item.Value}"); } try { _options = LoadOptions(args); var impersonationRequired = !string.IsNullOrEmpty(_options.User); if (impersonationRequired) { Impersonate(); } else { if (_options.UseSSL) { var netshargs = $"http delete urlacl http://*:{_options.Port}/"; var processStartInfo1 = new ProcessStartInfo("netsh", netshargs) { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, CreateNoWindow = true, Verb = "runas" }; _childProcess = Process.Start(processStartInfo1); if (_childProcess == null) { throw new Exception("Can't add ssl cert binding"); } _childProcess.BeginOutputReadLine(); _childProcess.BeginErrorReadLine(); _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data); _childProcess.ErrorDataReceived += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data); _childProcess.WaitForExit(10000); var netshargs2 = $"http add urlacl https://*:{_options.Port}/ user={_options.OriginalUsername}"; var processStartInfo2 = new ProcessStartInfo("netsh", netshargs2) { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, CreateNoWindow = true, Verb = "runas" }; _childProcess = Process.Start(processStartInfo2); if (_childProcess == null) { throw new Exception("Can't add ssl cert binding"); } _childProcess.BeginOutputReadLine(); _childProcess.BeginErrorReadLine(); _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data); _childProcess.ErrorDataReceived += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data); _childProcess.WaitForExit(10000); var addSslArgs = $"http add sslcert ipport=0.0.0.0:{_options.Port} appid={{{_options.ApplicationInstanceId}}} certhash={_options.Thumbprint}"; var processStartInfo = new ProcessStartInfo("netsh", addSslArgs) { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, CreateNoWindow = true, Verb = "runas" }; _childProcess = Process.Start(processStartInfo); if (_childProcess == null) { throw new Exception("Can't add ssl cert binding"); } _childProcess.BeginOutputReadLine(); _childProcess.BeginErrorReadLine(); _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data); _childProcess.ErrorDataReceived += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data); _childProcess.WaitForExit(10000); } var appConfigTemplate = new ApplicationHostConfig { Model = _options }; var appConfigText = appConfigTemplate.TransformText(); ValidateRequiredDllDependencies(appConfigText); var webConfigText = new WebConfig() { Model = _options }.TransformText(); var aspNetText = new AspNetConfig().TransformText(); Directory.CreateDirectory(_options.TempDirectory); Directory.CreateDirectory(_options.ConfigDirectory); File.WriteAllText(_options.ApplicationHostConfigPath, appConfigText); File.WriteAllText(_options.WebConfigPath, webConfigText); File.WriteAllText(_options.AspnetConfigPath, aspNetText); var webConfig = Path.Combine(_options.AppRootPath, "web.config"); var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var xdt = Path.Combine(_options.AppRootPath, $"web.{environment}.config"); if (!string.IsNullOrEmpty(environment) && File.Exists(xdt)) { Console.WriteLine($"Applying {xdt} to web.config"); var transform = new Microsoft.Web.XmlTransform.XmlTransformation(xdt); var doc = new XmlDocument(); doc.Load(webConfig); transform.Apply(doc); if (!File.Exists(webConfig + ".bak")) // backup original web.config as we're gonna transform into it's place { File.Move(webConfig, webConfig + ".bak"); } doc.Save(webConfig); } if (isConfigServerBound) { config = new ConfigurationBuilder().AddConfigServer().Build(); Console.WriteLine("Config server binding found - replacing matching veriables in web.config"); var webConfigContent = File.ReadAllText(webConfig); foreach (var configEntry in config.AsEnumerable()) { webConfigContent = webConfigContent.Replace("#{" + configEntry.Key + "}", configEntry.Value); } File.WriteAllText(webConfig, webConfigContent); } Console.WriteLine("Activating HWC with following settings:"); try { Console.WriteLine($"ApplicationHost.config: {_options.ApplicationHostConfigPath}"); Console.WriteLine($"Web.config: {_options.WebConfigPath}"); // var process = Process.Start("cmd"); // var job = new Job(); // job.AddProcess(process.Handle); HostableWebCore.Activate(_options.ApplicationHostConfigPath, _options.WebConfigPath, _options.ApplicationInstanceId); } catch (UnauthorizedAccessException) { Console.Error.WriteLine("Access denied starting hostable web core. Start the application as administrator"); Console.WriteLine("==========================="); throw; } Console.WriteLine($"Server ID {_options.ApplicationInstanceId} started"); Console.WriteLine("PRESS Enter to shutdown"); // we gonna read on different thread here because Console.ReadLine is not the only way the program can end // we're also listening to the system events where the app is ordered to shutdown. exitWaitHandle is used to // hook up both of these events } new Thread(() => { Console.ReadLine(); _exitWaitHandle.Set(); }).Start(); _exitWaitHandle.WaitOne(); return(0); } catch (ValidationException ve) { Console.Error.WriteLine(ve.Message); } catch (Exception ex) { Console.Error.WriteLine(ex); } finally { Shutdown(); // impresonationContext?.Dispose(); } return(1); }
private string Transform(string inputXml, string xdtPath) { using (StringWriter outStream = new StringWriter()) { Microsoft.Web.XmlTransform.XmlTransformation xtr = new Microsoft.Web.XmlTransform.XmlTransformation(xdtPath); XmlDocument doc = new XmlDocument(); doc.LoadXml(inputXml); xtr.Apply(doc); doc.Save(outStream); return outStream.ToString(); } }
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); }
/// <example>mono MonoWebPublisher.exe sample.csproj /var/www/sample-dest-publish-dir</example> static void Main(string[] args) { if (args.Length != 2 && args.Length != 3) { Console.WriteLine("Parameter not match!"); Environment.Exit(1); } var projectFile = args[0]; var destDir = args[1]; var configuration = "Release"; if (args.Length == 3) { if (!string.IsNullOrWhiteSpace(args[2])) { configuration = args[2]; } } var sourceDir = Path.GetDirectoryName(projectFile); // Find out if web.config should be transformed var webConfig = Path.Combine(sourceDir, "Web.config"); var webConfigTransform = Path.Combine(sourceDir, "Web." + configuration + ".config"); var shouldTransformWebConfig = File.Exists(webConfig) && File.Exists(webConfigTransform); //delete everything in destDir but .git folder if (Directory.Exists(destDir)) { var destDirs = Directory.GetDirectories(destDir, "*", SearchOption.TopDirectoryOnly); destDirs.ToList <string>().ForEach(n => { if (Path.GetFileName(n) != ".git") { Directory.Delete(n, true); } }); Directory.GetFiles(destDir, "*", SearchOption.TopDirectoryOnly).ToList().ForEach(File.Delete); } //copy included files var fileList = GetIncludedFiles(projectFile); fileList.ForEach(n => { bool isWebConfig = n.StartsWith("Web.") && n.EndsWith(".config"); if (!shouldTransformWebConfig || !isWebConfig) { Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(destDir, n))); File.Copy(Path.Combine(sourceDir, n), Path.Combine(destDir, n), true); } }); //copy bin folder string[] binFiles = Directory.GetFiles(Path.Combine(sourceDir, "bin")); Directory.CreateDirectory(Path.Combine(destDir, "bin")); binFiles.ToList <string>().ForEach(n => { File.Copy(n, Path.Combine(Path.Combine(destDir, "bin"), Path.GetFileName(n)), true); }); // Transform web.config if (shouldTransformWebConfig) { var xmlDoc = new XmlDataDocument { PreserveWhitespace = true }; xmlDoc.Load(webConfig); var transformation = new Microsoft.Web.XmlTransform.XmlTransformation(webConfigTransform); transformation.Apply(xmlDoc); var outputWebConfig = Path.Combine(destDir, "Web.config"); var xmlWriter = XmlWriter.Create(outputWebConfig); xmlDoc.WriteTo(xmlWriter); xmlWriter.Close(); } }