// // ConsoleHost.cs // // Jason Diamond // // example: ConsoleHost test.aspx foo=bar baz=quux // using System; using System.Diagnostics; using System.IO; using System.Text; using System.Web; using System.Web.Hosting; public class ConsoleHost : MarshalByRefObject { static void Main(string[] arguments) { if (arguments.Length == 0) { Console.Error.WriteLine("Usage: ConsoleHost page (name=value)*"); } else { string page = arguments[0]; // Build a query string using the command line arguments. string query = String.Empty; for (int i = 1; i < arguments.Length; ++i) { if (query != String.Empty) { query += "&"; } int indexOfEquals = arguments[i].IndexOf('='); if (indexOfEquals != -1) { string name = arguments[i].Substring(0, indexOfEquals); string value = arguments[i].Substring(indexOfEquals + 1); query += name + "=" + EscapeValue(value); } } // CreateApplicationHost requires this assembly be in a // subdirectory called bin so copy this assembly there if it // doesn't already exist or is out of date. if (! Directory.Exists("bin")) { Directory.CreateDirectory("bin"); } string mainModuleFileName = Process.GetCurrentProcess().MainModule.FileName; string binFileName = "bin\\" + Path.GetFileName(mainModuleFileName); if (! File.Exists(binFileName) || File.GetLastWriteTime(mainModuleFileName) > File.GetLastWriteTime(binFileName)) { File.Copy(mainModuleFileName, binFileName, true); } // Create the host and process the request. ConsoleHost host = (ConsoleHost)ApplicationHost.CreateApplicationHost(typeof(ConsoleHost), "/", Directory.GetCurrentDirectory()); host.ProcessRequest(page, query); } } void ProcessRequest(string page, string query) { HttpRuntime.ProcessRequest(new SimpleWorkerRequest(page, query, Console.Out)); } // See RFC2396 for the details on why we need to do this. static string EscapeValue(string value) { StringBuilder result = new StringBuilder(); foreach (char c in value) { if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '%') { result.AppendFormat("%{0:X2}", (int)c); } else if (c == ' ') { result.Append('+'); } else { result.Append(c); } } return result.ToString(); } }