Start() public method

public Start ( ) : int
return int
コード例 #1
0
    public static int Main(string[] args)
    {
        Console.WriteLine("Touch.Unit Simple Server");
        Console.WriteLine("Copyright 2011, Xamarin Inc. All rights reserved.");

        bool help = false;
        var  port = 12345;
        var  os   = new OptionSet()
        {
            { "h|?|help", "Display help", v => help = true },
            { "p|port=", "TCP port to listen (default: 12345)", v => port = Int32.Parse(v) }
        };

        os.Parse(args);
        if (help)
        {
            ShowHelp(os);
            return(0);
        }

        try {
            var listener = new SimpleListener();

            listener.Address  = IPAddress.Any;
            listener.Port     = port;
            listener.AutoExit = true;
            listener.Initialize();

            var lastErrorDataReceived = new AutoResetEvent(true);
            var lastOutDataReceived   = new AutoResetEvent(true);

            var result = listener.Start();
            lastErrorDataReceived.WaitOne(2000);
            lastOutDataReceived.WaitOne(2000);
            return(result);
        } catch (Exception ex) {
            Console.WriteLine(ex);
            return(1);
        }
    }
コード例 #2
0
ファイル: Main.cs プロジェクト: couchbasedeps/Touch.Unit
	public static int Main (string[] args)
	{ 
		Console.WriteLine ("Touch.Unit Simple Server");
		Console.WriteLine ("Copyright 2011, Xamarin Inc. All rights reserved.");
		
		bool help = false;
		bool verbose = false;
		string address = null;
		string port = null;
		string log_path = ".";
		string log_file = null;
		string launchdev = null;
		string launchsim = null;
		bool autoexit = false;
		string device_name = String.Empty;
		string device_type = String.Empty;
		TimeSpan? timeout = null;
		TimeSpan? startup_timeout = null;
		var mtouch_arguments = new List<string> ();

		var os = new OptionSet () {
			{ "h|?|help", "Display help", v => help = true },
			{ "verbose", "Display verbose output", v => verbose = true },
			{ "ip", "IP address to listen (default: Any)", v => address = v },
			{ "port", "TCP port to listen (default: Any)", v => port = v },
			{ "logpath", "Path to save the log files (default: .)", v => log_path = v },
			{ "logfile=", "Filename to save the log to (default: automatically generated)", v => log_file = v },
			{ "launchdev=", "Run the specified app on a device (specify using bundle identifier)", v => launchdev = v },
			{ "launchsim=", "Run the specified app on the simulator (specify using path to *.app directory)", v => launchsim = v },
			{ "autoexit", "Exit the server once a test run has completed (default: false)", v => autoexit = true },
			{ "devname=", "Specify the device to connect to", v => device_name = v},
			{ "device=", "Specifies the device type to launch the simulator", v => device_type = v },
			{ "timeout=", "Specifies a timeout (in minutes), after which the simulator app will be killed (ignored for device runs)", v => timeout = TimeSpan.FromMinutes (double.Parse (v)) },
			{ "startup-timeout=", "Specifies a timeout (in seconds) for the simulator app to connect to Touch.Server (ignored for device runs)", v => startup_timeout = TimeSpan.FromSeconds (double.Parse (v)) },
			{ "mtouch-argument=", "Specifies an extra mtouch argument when launching the application", v => mtouch_arguments.Add (v) },
		};
		
		try {
			os.Parse (args);
			if (help)
				ShowHelp (os);
			
			var listener = new SimpleListener ();
			
			IPAddress ip;
			if (String.IsNullOrEmpty (address) || !IPAddress.TryParse (address, out ip))
				listener.Address = IPAddress.Any;
			
			ushort p;
			if (UInt16.TryParse (port, out p))
				listener.Port = p;
			
			listener.LogPath = log_path ?? ".";
			listener.LogFile = log_file;
			listener.AutoExit = autoexit;
			listener.Initialize ();
			
			string mt_root = Environment.GetEnvironmentVariable ("MONOTOUCH_ROOT");
			if (String.IsNullOrEmpty (mt_root))
				mt_root = "/Developer/MonoTouch";

			string mtouch = Path.Combine (mt_root, "bin", "mtouch");
			if (!File.Exists (mtouch))
				mtouch = Path.Combine (mt_root, "usr", "bin", "mtouch");

			Process proc = null;
			if (launchdev != null) {
				ThreadPool.QueueUserWorkItem ((v) => {
					{
						proc = new Process ();
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
							procArgs.Append ("--sdkroot ").Append (sdk_root);
						procArgs.Append (" --launchdev ");
						procArgs.Append (Quote (launchdev));
						if (!String.IsNullOrEmpty (device_name))
							procArgs.Append (" --devname=").Append (Quote (device_name));
						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.AppendFormat (" -argument=-app-arg:-hostport:{0}", listener.Port);
						procArgs.Append (" -argument=-app-arg:-hostname:");
						foreach (var arg in mtouch_arguments)
							procArgs.Append (" ").Append (arg);
						var ipAddresses = System.Net.Dns.GetHostEntry (System.Net.Dns.GetHostName ()).AddressList;
						for (int i = 0; i < ipAddresses.Length; i++) {
							if (i > 0)
								procArgs.Append (',');
							procArgs.Append (ipAddresses [i].ToString ());
						}
						proc.StartInfo.FileName = mtouch;
						proc.StartInfo.Arguments = procArgs.ToString ();
						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.StartInfo.RedirectStandardError = true;
						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							lock (output) {
								output.Append ("[mtouch stderr] ");
								output.AppendLine (e.Data);
							}
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							lock (output) {
								output.Append ("[mtouch stdout] ");
								output.AppendLine (e.Data);
							}
						};
						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						proc.WaitForExit ();
						if (proc.ExitCode != 0)
							listener.Cancel ();
						Console.WriteLine (output.ToString ());
					}
				});
			}

			var lastErrorDataReceived = new AutoResetEvent (true);
			var lastOutDataReceived = new AutoResetEvent (true);
			if (launchsim != null) {
				lastErrorDataReceived.Reset ();
				lastOutDataReceived.Reset ();

				ThreadPool.QueueUserWorkItem ((v) => {
					{
						proc = new Process ();
						int pid = 0;
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
							procArgs.Append ("--sdkroot ").Append (sdk_root);
						procArgs.Append (" --launchsim ");
						procArgs.Append (Quote (launchsim));
						if (!string.IsNullOrEmpty (device_type))
							procArgs.Append (" --device ").Append (device_type);
						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.Append (" -argument=-app-arg:-hostname:127.0.0.1");
						procArgs.AppendFormat (" -argument=-app-arg:-hostport:{0}", listener.Port);
						foreach (var arg in mtouch_arguments)
							procArgs.Append (" ").Append (arg);
						proc.StartInfo.FileName = mtouch;
						proc.StartInfo.Arguments = procArgs.ToString ();
						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardError = true;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.StartInfo.RedirectStandardInput = true;

						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							if (e.Data == null) {
								Console.WriteLine ("[mtouch stderr EOS]");
								lastErrorDataReceived.Set ();
								return;
							}
							Console.WriteLine ("[mtouch stderr {0}] {1}", DateTime.Now.ToLongTimeString (), e.Data);
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							if (e.Data == null){
								Console.WriteLine ("[mtouch stdout EOS]");
								lastOutDataReceived.Set ();
								return;
							}
							Console.WriteLine ("[mtouch stdout {0}] {1}", DateTime.Now.ToLongTimeString (), e.Data);

							if (e.Data.StartsWith ("Application launched. PID = ")) {
								var pidstr = e.Data.Substring ("Application launched. PID = ".Length);
								if (!int.TryParse (pidstr, out pid)) {
									Console.WriteLine ("Could not parse pid: {0}", pidstr);
								} else if (startup_timeout.HasValue) {
									ThreadPool.QueueUserWorkItem ((v2) =>
										{
											if (!listener.WaitForConnection (startup_timeout.Value))
												KillPid (proc, pid, 1000, startup_timeout.Value, "Startup");
										});
								}
							}
						};
						if (verbose)
							Console.WriteLine ("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments);
						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						if (timeout.HasValue) {
							if (!proc.WaitForExit ((int) timeout.Value.TotalMilliseconds)) {
								if (pid != 0) {
									KillPid (proc, pid, 5000, timeout.Value, "Completion");
								} else {
									proc.StandardInput.WriteLine (); // this kills as well, but we won't be able to send SIGQUIT to get a stack trace.
								}
								if (!proc.WaitForExit (5000 /* wait another 5 seconds for mtouch to finish as well */))
									Console.WriteLine ("mtouch didn't complete within 5s of killing the simulator app. Touch.Server will exit anyway.");
							}
						} else {
							proc.WaitForExit ();
						}
						listener.Cancel ();
					}
				});
			}
			
			var result = listener.Start ();
			if (proc != null && !proc.WaitForExit (10000 /* wait another 10 seconds for mtouch to finish as well */))
				Console.WriteLine ("mtouch didn't complete within 10s of the simulator app exiting. Touch.Server will exit anyway.");
			// Wait up to 2 seconds to receive the last of the error/output data. This will only be received *after*
			// mtouch has exited.
			lastErrorDataReceived.WaitOne (2000);
			lastOutDataReceived.WaitOne (2000);
			return result;
		} catch (OptionException oe) {
			Console.WriteLine ("{0} for options '{1}'", oe.Message, oe.OptionName);
			return 1;
		} catch (Exception ex) {
			Console.WriteLine (ex);
			return 1;
		}
	}   
コード例 #3
0
ファイル: Main.cs プロジェクト: rolfbjarne/Touch.Unit
    public static void Main(string[] args)
    {
        Console.WriteLine("Touch.Unit Simple Server");
        Console.WriteLine("Copyright 2011, Xamarin Inc. All rights reserved.");

        bool   help      = false;
        string address   = null;
        string port      = null;
        string log_path  = ".";
        string log_file  = null;
        string launchdev = null;
        string launchsim = null;
        bool   autoexit  = false;

        var os = new OptionSet()
        {
            { "h|?|help", "Display help", v => help = true },
            { "ip", "IP address to listen (default: Any)", v => address = v },
            { "port", "TCP port to listen (default: 16384)", v => port = v },
            { "logpath", "Path to save the log files (default: .)", v => log_path = v },
            { "logfile=", "Filename to save the log to (default: automatically generated)", v => log_file = v },
            { "launchdev=", "Run the specified app on a device (specify using bundle identifier)", v => launchdev = v },
            { "launchsim=", "Run the specified app on the simulator (specify using path to *.app directory)", v => launchsim = v },
            { "autoexit", "Exit the server once a test run has completed (default: false)", v => autoexit = true },
        };

        try {
            os.Parse(args);
            if (help)
            {
                ShowHelp(os);
            }

            var listener = new SimpleListener();

            IPAddress ip;
            if (String.IsNullOrEmpty(address) || !IPAddress.TryParse(address, out ip))
            {
                listener.Address = IPAddress.Any;
            }

            ushort p;
            if (UInt16.TryParse(port, out p))
            {
                listener.Port = p;
            }
            else
            {
                listener.Port = 16384;
            }

            listener.LogPath  = log_path ?? ".";
            listener.LogFile  = log_file;
            listener.AutoExit = autoexit;

            if (launchdev != null)
            {
                ThreadPool.QueueUserWorkItem((v) => {
                    using (Process proc = new Process()) {
                        StringBuilder procArgs = new StringBuilder();
                        procArgs.Append("--launchdev ");
                        procArgs.Append(launchdev);
                        procArgs.Append(" -argument=-connection-mode -argument=none");
                        procArgs.Append(" -argument=-app-arg:-autostart");
                        procArgs.Append(" -argument=-app-arg:-autoexit");
                        procArgs.Append(" -argument=-app-arg:-enablenetwork");
                        procArgs.AppendFormat(" -argument=-app-arg:-hostport:{0}", listener.Port);
                        procArgs.Append(" -argument=-app-arg:-hostname:");
                        var ipAddresses = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
                        for (int i = 0; i < ipAddresses.Length; i++)
                        {
                            if (i > 0)
                            {
                                procArgs.Append(',');
                            }
                            procArgs.Append(ipAddresses [i].ToString());
                        }
                        proc.StartInfo.FileName  = "/Developer/MonoTouch/usr/bin/mtouch";
                        proc.StartInfo.Arguments = procArgs.ToString();
                        proc.Start();
                        proc.WaitForExit();
                    }
                });
            }

            if (launchsim != null)
            {
                ThreadPool.QueueUserWorkItem((v) => {
                    using (Process proc = new Process()) {
                        StringBuilder output   = new StringBuilder();
                        StringBuilder procArgs = new StringBuilder();
                        procArgs.Append("--launchsim ");
                        procArgs.Append(launchsim);
                        procArgs.Append(" -sdk 5.0");
                        procArgs.Append(" -argument=-connection-mode -argument=none");
                        procArgs.Append(" -argument=-app-arg:-autostart");
                        procArgs.Append(" -argument=-app-arg:-autoexit");
                        procArgs.Append(" -argument=-app-arg:-enablenetwork");
                        procArgs.Append(" -argument=-app-arg:-hostname:127.0.0.1");
                        procArgs.AppendFormat(" -argument=-app-arg:-hostport:{0}", listener.Port);
                        proc.StartInfo.FileName               = "/Developer/MonoTouch/usr/bin/mtouch";
                        proc.StartInfo.Arguments              = procArgs.ToString();
                        proc.StartInfo.UseShellExecute        = false;
                        proc.StartInfo.RedirectStandardError  = true;
                        proc.StartInfo.RedirectStandardOutput = true;
                        proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output)
                                output.AppendLine(e.Data);
                        };
                        proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output)
                                output.AppendLine(e.Data);
                        };
                        proc.Start();
                        proc.BeginErrorReadLine();
                        proc.BeginOutputReadLine();
                        proc.WaitForExit();
                        if (proc.ExitCode != 0)
                        {
                            Console.WriteLine(output.ToString());
                        }
                    }
                });
            }

            listener.Start();
        } catch (OptionException oe) {
            Console.WriteLine("{0} for options '{1}'", oe.Message, oe.OptionName);
        }
    }
コード例 #4
0
    public static int Main(string[] args)
    {
        Console.WriteLine("Touch.Unit Simple Server");
        Console.WriteLine("Copyright 2011, Xamarin Inc. All rights reserved.");

        bool     help             = false;
        bool     verbose          = false;
        string   address          = null;
        string   port             = null;
        string   log_path         = ".";
        string   log_file         = null;
        string   launchdev        = null;
        string   launchsim        = null;
        bool     autoexit         = false;
        string   device_name      = String.Empty;
        string   device_type      = String.Empty;
        TimeSpan?timeout          = null;
        TimeSpan?startup_timeout  = null;
        var      mtouch_arguments = new List <string> ();

        var os = new OptionSet()
        {
            { "h|?|help", "Display help", v => help = true },
            { "verbose", "Display verbose output", v => verbose = true },
            { "ip", "IP address to listen (default: Any)", v => address = v },
            { "port", "TCP port to listen (default: Any)", v => port = v },
            { "logpath", "Path to save the log files (default: .)", v => log_path = v },
            { "logfile=", "Filename to save the log to (default: automatically generated)", v => log_file = v },
            { "launchdev=", "Run the specified app on a device (specify using bundle identifier)", v => launchdev = v },
            { "launchsim=", "Run the specified app on the simulator (specify using path to *.app directory)", v => launchsim = v },
            { "autoexit", "Exit the server once a test run has completed (default: false)", v => autoexit = true },
            { "devname=", "Specify the device to connect to", v => device_name = v },
            { "device=", "Specifies the device type to launch the simulator", v => device_type = v },
            { "timeout=", "Specifies a timeout (in minutes), after which the simulator app will be killed (ignored for device runs)", v => timeout = TimeSpan.FromMinutes(double.Parse(v)) },
            { "startup-timeout=", "Specifies a timeout (in seconds) for the simulator app to connect to Touch.Server (ignored for device runs)", v => startup_timeout = TimeSpan.FromSeconds(double.Parse(v)) },
            { "mtouch-argument=", "Specifies an extra mtouch argument when launching the application", v => mtouch_arguments.Add(v) },
        };

        try {
            os.Parse(args);
            if (help)
            {
                ShowHelp(os);
            }

            var listener = new SimpleListener();

            IPAddress ip;
            if (String.IsNullOrEmpty(address) || !IPAddress.TryParse(address, out ip))
            {
                listener.Address = IPAddress.Any;
            }

            ushort p;
            if (UInt16.TryParse(port, out p))
            {
                listener.Port = p;
            }

            listener.LogPath  = log_path ?? ".";
            listener.LogFile  = log_file;
            listener.AutoExit = autoexit;
            listener.Initialize();

            string mt_root = Environment.GetEnvironmentVariable("MONOTOUCH_ROOT");
            if (String.IsNullOrEmpty(mt_root))
            {
                mt_root = "/Developer/MonoTouch";
            }

            string mtouch = Path.Combine(mt_root, "bin", "mtouch");
            if (!File.Exists(mtouch))
            {
                mtouch = Path.Combine(mt_root, "usr", "bin", "mtouch");
            }

            Process proc = null;
            if (launchdev != null)
            {
                ThreadPool.QueueUserWorkItem((v) => {
                    {
                        proc = new Process();
                        StringBuilder output   = new StringBuilder();
                        StringBuilder procArgs = new StringBuilder();
                        string sdk_root        = Environment.GetEnvironmentVariable("XCODE_DEVELOPER_ROOT");
                        if (!String.IsNullOrEmpty(sdk_root))
                        {
                            procArgs.Append("--sdkroot ").Append(sdk_root);
                        }
                        procArgs.Append(" --launchdev ");
                        procArgs.Append(Quote(launchdev));
                        if (!String.IsNullOrEmpty(device_name))
                        {
                            procArgs.Append(" --devname=").Append(Quote(device_name));
                        }
                        procArgs.Append(" -argument=-connection-mode -argument=none");
                        procArgs.Append(" -argument=-app-arg:-autostart");
                        procArgs.Append(" -argument=-app-arg:-autoexit");
                        procArgs.Append(" -argument=-app-arg:-enablenetwork");
                        procArgs.AppendFormat(" -argument=-app-arg:-hostport:{0}", listener.Port);
                        procArgs.Append(" -argument=-app-arg:-hostname:");
                        foreach (var arg in mtouch_arguments)
                        {
                            procArgs.Append(" ").Append(arg);
                        }
                        var ipAddresses = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
                        for (int i = 0; i < ipAddresses.Length; i++)
                        {
                            if (i > 0)
                            {
                                procArgs.Append(',');
                            }
                            procArgs.Append(ipAddresses [i].ToString());
                        }
                        proc.StartInfo.FileName               = mtouch;
                        proc.StartInfo.Arguments              = procArgs.ToString();
                        proc.StartInfo.UseShellExecute        = false;
                        proc.StartInfo.RedirectStandardOutput = true;
                        proc.StartInfo.RedirectStandardError  = true;
                        proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output) {
                                output.Append("[mtouch stderr] ");
                                output.AppendLine(e.Data);
                            }
                        };
                        proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output) {
                                output.Append("[mtouch stdout] ");
                                output.AppendLine(e.Data);
                            }
                        };
                        proc.Start();
                        proc.BeginErrorReadLine();
                        proc.BeginOutputReadLine();
                        proc.WaitForExit();
                        if (proc.ExitCode != 0)
                        {
                            listener.Cancel();
                        }
                        Console.WriteLine(output.ToString());
                    }
                });
            }

            var lastErrorDataReceived = new AutoResetEvent(true);
            var lastOutDataReceived   = new AutoResetEvent(true);
            if (launchsim != null)
            {
                lastErrorDataReceived.Reset();
                lastOutDataReceived.Reset();

                ThreadPool.QueueUserWorkItem((v) => {
                    {
                        proc    = new Process();
                        int pid = 0;
                        StringBuilder output   = new StringBuilder();
                        StringBuilder procArgs = new StringBuilder();
                        string sdk_root        = Environment.GetEnvironmentVariable("XCODE_DEVELOPER_ROOT");
                        if (!String.IsNullOrEmpty(sdk_root))
                        {
                            procArgs.Append("--sdkroot ").Append(sdk_root);
                        }
                        procArgs.Append(" --launchsim ");
                        procArgs.Append(Quote(launchsim));
                        if (!string.IsNullOrEmpty(device_type))
                        {
                            procArgs.Append(" --device ").Append(device_type);
                        }
                        procArgs.Append(" -argument=-connection-mode -argument=none");
                        procArgs.Append(" -argument=-app-arg:-autostart");
                        procArgs.Append(" -argument=-app-arg:-autoexit");
                        procArgs.Append(" -argument=-app-arg:-enablenetwork");
                        procArgs.Append(" -argument=-app-arg:-hostname:127.0.0.1");
                        procArgs.AppendFormat(" -argument=-app-arg:-hostport:{0}", listener.Port);
                        foreach (var arg in mtouch_arguments)
                        {
                            procArgs.Append(" ").Append(arg);
                        }
                        proc.StartInfo.FileName               = mtouch;
                        proc.StartInfo.Arguments              = procArgs.ToString();
                        proc.StartInfo.UseShellExecute        = false;
                        proc.StartInfo.RedirectStandardError  = true;
                        proc.StartInfo.RedirectStandardOutput = true;
                        proc.StartInfo.RedirectStandardInput  = true;

                        proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            if (e.Data == null)
                            {
                                Console.WriteLine("[mtouch stderr EOS]");
                                lastErrorDataReceived.Set();
                                return;
                            }
                            Console.WriteLine("[mtouch stderr {0}] {1}", DateTime.Now.ToLongTimeString(), e.Data);
                        };
                        proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            if (e.Data == null)
                            {
                                Console.WriteLine("[mtouch stdout EOS]");
                                lastOutDataReceived.Set();
                                return;
                            }
                            Console.WriteLine("[mtouch stdout {0}] {1}", DateTime.Now.ToLongTimeString(), e.Data);

                            if (e.Data.StartsWith("Application launched. PID = "))
                            {
                                var pidstr = e.Data.Substring("Application launched. PID = ".Length);
                                if (!int.TryParse(pidstr, out pid))
                                {
                                    Console.WriteLine("Could not parse pid: {0}", pidstr);
                                }
                                else if (startup_timeout.HasValue)
                                {
                                    ThreadPool.QueueUserWorkItem((v2) =>
                                    {
                                        if (!listener.WaitForConnection(startup_timeout.Value))
                                        {
                                            KillPid(proc, pid, 1000, startup_timeout.Value, "Startup");
                                        }
                                    });
                                }
                            }
                        };
                        if (verbose)
                        {
                            Console.WriteLine("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments);
                        }
                        proc.Start();
                        proc.BeginErrorReadLine();
                        proc.BeginOutputReadLine();
                        if (timeout.HasValue)
                        {
                            if (!proc.WaitForExit((int)timeout.Value.TotalMilliseconds))
                            {
                                if (pid != 0)
                                {
                                    KillPid(proc, pid, 5000, timeout.Value, "Completion");
                                }
                                else
                                {
                                    proc.StandardInput.WriteLine();                                      // this kills as well, but we won't be able to send SIGQUIT to get a stack trace.
                                }
                                if (!proc.WaitForExit(5000 /* wait another 5 seconds for mtouch to finish as well */))
                                {
                                    Console.WriteLine("mtouch didn't complete within 5s of killing the simulator app. Touch.Server will exit anyway.");
                                }
                            }
                        }
                        else
                        {
                            proc.WaitForExit();
                        }
                        listener.Cancel();
                    }
                });
            }

            var result = listener.Start();
            if (proc != null && !proc.WaitForExit(30000 /* wait another 30 seconds for mtouch to finish as well */))
            {
                Console.WriteLine("mtouch didn't complete within 30s of the simulator app exiting. Touch.Server will exit anyway.");
            }
            // Wait up to 2 seconds to receive the last of the error/output data. This will only be received *after*
            // mtouch has exited.
            lastErrorDataReceived.WaitOne(2000);
            lastOutDataReceived.WaitOne(2000);
            return(result);
        } catch (OptionException oe) {
            Console.WriteLine("{0} for options '{1}'", oe.Message, oe.OptionName);
            return(1);
        } catch (Exception ex) {
            Console.WriteLine(ex);
            return(1);
        }
    }
コード例 #5
0
	public static int Main (string[] args)
	{ 
		Console.WriteLine ("Touch.Unit Simple Server");
		Console.WriteLine ("Copyright 2011, Xamarin Inc. All rights reserved.");
		
		bool help = false;
		bool verbose = false;
		string address = null;
		string port = null;
		string log_path = ".";
		string log_file = null;
		string launchdev = null;
		string launchsim = null;
		bool autoexit = false;
		string device_name = String.Empty;
		string device_type = String.Empty;

		var os = new OptionSet () {
			{ "h|?|help", "Display help", v => help = true },
			{ "verbose", "Display verbose output", v => verbose = true },
			{ "ip=", "IP address to listen (default: Any)", v => address = v },
			{ "port=", "TCP port to listen (default: Any)", v => port = v },
			{ "logpath=", "Path to save the log files (default: .)", v => log_path = v },
			{ "logfile=", "Filename to save the log to (default: automatically generated)", v => log_file = v },
			{ "launchdev=", "Run the specified app on a device (specify using bundle identifier)", v => launchdev = v },
			{ "launchsim=", "Run the specified app on the simulator (specify using path to *.app directory)", v => launchsim = v },
			{ "autoexit", "Exit the server once a test run has completed (default: false)", v => autoexit = true },
			{ "devname=", "Specify the device to connect to", v => device_name = v},
			{ "device=", "Specifies the device type to launch the simulator", v => device_type = v },
		};
		
		try 
    {
			os.Parse (args);
			if (help)
      {
				ShowHelp(os);
        return 0;
      }
			
			var listener = new SimpleListener ();
			
			IPAddress ip;
			if (String.IsNullOrEmpty (address) || !IPAddress.TryParse (address, out ip))
      {
				listener.Address = IPAddress.Any;
      }
			

			ushort p;
			if (UInt16.TryParse(port, out p))
      {
				listener.Port = p;
      }
      else
      {
        Console.WriteLine ("Unable to parse port : {0}", port);
      }
			
			listener.LogPath = log_path ?? ".";
			listener.LogFile = log_file;
			listener.AutoExit = autoexit;
			listener.Initialize();
			
			string mt_root = Environment.GetEnvironmentVariable("MONOTOUCH_ROOT");
			if (String.IsNullOrEmpty (mt_root))
      {
				mt_root = "/Developer/MonoTouch";
      }

			string mtouch = Path.Combine (mt_root, "bin", "mtouch");
			if (!File.Exists (mtouch))
      {
				mtouch = Path.Combine (mt_root, "usr", "bin", "mtouch");
      }

			if (launchdev != null) 
      {
				ThreadPool.QueueUserWorkItem ((v) => 
        {
					using (Process proc = new Process ()) 
          {
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
            {
							procArgs.Append ("--sdkroot ").Append (sdk_root);
            }

						procArgs.Append (" --launchdev ");
						procArgs.Append (launchdev);
						if (!String.IsNullOrEmpty (device_name))
            {
							procArgs.Append (" --devname=").Append (device_name);
            }

						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.AppendFormat (" -argument=-app-arg:-hostport:{0}", listener.Port);
						procArgs.Append (" -argument=-app-arg:-hostname:");
						var ipAddresses = System.Net.Dns.GetHostEntry (System.Net.Dns.GetHostName ()).AddressList;
						for (int i = 0; i < ipAddresses.Length; i++) 
            {
							if (i > 0)
              {
								procArgs.Append (',');
              }
							procArgs.Append (ipAddresses [i].ToString ());
						}
						proc.StartInfo.FileName = mtouch;

						string strArgs = procArgs.ToString ();
						Console.WriteLine("[Command] mtouch {0}", strArgs);

						proc.StartInfo.Arguments = strArgs;
						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.StartInfo.RedirectStandardError = true;
						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) 
            {
							lock (output) 
              {
								output.Append ("[mtouch stderr] ");
								output.AppendLine (e.Data);
							}
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) 
            {
							lock (output) 
              {
								output.Append ("[mtouch stdout] ");
								output.AppendLine (e.Data);
							}
						};
						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						proc.WaitForExit ();
						if (proc.ExitCode != 0)
            {
							listener.Cancel ();
            }
						Console.WriteLine(output.ToString ());
					}
				});
			}
			
			if (launchsim != null) 
      {
				ThreadPool.QueueUserWorkItem ((v) => 
        {
					using (Process proc = new Process ()) 
          {
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
            {
							procArgs.Append ("--sdkroot ").Append (sdk_root);
            }

						procArgs.Append (" --launchsim ");
						procArgs.Append (launchsim);
						if (!string.IsNullOrEmpty (device_type))
            {
							procArgs.Append (" --device ").Append (device_type);
            }

						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.Append (" -argument=-app-arg:-hostname:127.0.0.1");
						procArgs.AppendFormat(" -argument=-app-arg:-hostport:{0}", listener.Port);


						proc.StartInfo.FileName = mtouch;

                        string strArgs = procArgs.ToString();
						Console.WriteLine("[Command] mtouch {0}", strArgs);
						proc.StartInfo.Arguments = strArgs;


						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardError = true;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) 
            {
							lock (output) 
              {
								output.AppendFormat ("[mtouch stderr {0}] ", DateTime.Now.ToLongTimeString ());
								output.AppendLine (e.Data);
							}
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) 
            {
							lock (output) 
              {
								output.AppendFormat ("[mtouch stdout {0}] ", DateTime.Now.ToLongTimeString ());
								output.AppendLine (e.Data);
							}
						};
						if (verbose)
            {
							Console.WriteLine ("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments);
            }

						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						proc.WaitForExit ();
						listener.Cancel ();
						Console.WriteLine (output.ToString ());
					}
				});
			}
			
			return listener.Start ();
		} 
    catch (OptionException oe) 
    {
			Console.WriteLine ("{0} for options '{1}'", oe.Message, oe.OptionName);
			return 1;
		} 
    catch (Exception ex) 
    {
			Console.WriteLine (ex);
			return 1;
		}
	}   
コード例 #6
0
ファイル: Main.cs プロジェクト: aseratalahzan2009/Touch.Unit
    public static int Main(string[] args)
    {
        Console.WriteLine("Touch.Unit Simple Server");
        Console.WriteLine("Copyright 2011, Xamarin Inc. All rights reserved.");

        bool      help        = false;
        bool      verbose     = false;
        string    address     = null;
        string    port        = null;
        string    log_path    = ".";
        string    log_file    = null;
        string    launchdev   = null;
        string    launchsim   = null;
        bool      autoexit    = false;
        string    device_name = String.Empty;
        string    device_type = String.Empty;
        string    inte        = String.Empty;
        IPAddress ip          = null;

        var os = new OptionSet()
        {
            { "h|?|help", "Display help", v => help = true },
            { "verbose", "Display verbose output", v => verbose = true },
            { "ip=", "IP address to listen (default: Any)", v => address = v },
            { "port", "TCP port to listen (default: Any)", v => port = v },
            { "logpath", "Path to save the log files (default: .)", v => log_path = v },
            { "logfile=", "Filename to save the log to (default: automatically generated)", v => log_file = v },
            { "launchdev=", "Run the specified app on a device (specify using bundle identifier)", v => launchdev = v },
            { "launchsim=", "Run the specified app on the simulator (specify using path to *.app directory)", v => launchsim = v },
            { "autoexit", "Exit the server once a test run has completed (default: false)", v => autoexit = true },
            { "devname=", "Specify the device to connect to", v => device_name = v },
            { "device=", "Specifies the device type to launch the simulator", v => device_type = v },
            { "interface=", "Specifies the listening interface, in form of et0", v => inte = v },
        };


        try {
            os.Parse(args);
            if (help)
            {
                ShowHelp(os);
            }

            var listener = new SimpleListener();


            if
            (String.IsNullOrEmpty(address) || !IPAddress.TryParse(address, out ip))
            {
                listener.Address = IPAddress.Any;
            }
            else
            {
                listener.Address = ip;
            }

            ushort p;
            if (UInt16.TryParse(port, out p))
            {
                listener.Port = p;
            }

            listener.LogPath  = log_path ?? ".";
            listener.LogFile  = log_file;
            listener.AutoExit = autoexit;
            listener.Initialize();

            string mt_root = Environment.GetEnvironmentVariable("MONOTOUCH_ROOT");
            if (String.IsNullOrEmpty(mt_root))
            {
                mt_root = "/Developer/MonoTouch";
            }


            string mtouch = Path.Combine(mt_root, "bin", "mtouch");
            if (!File.Exists(mtouch))
            {
                mtouch = Path.Combine(mt_root, "usr", "bin", "mtouch");
            }

            if (launchdev != null)
            {
                ThreadPool.QueueUserWorkItem((v) => {
                    using (Process proc = new Process()) {
                        StringBuilder output   = new StringBuilder();
                        StringBuilder procArgs = new StringBuilder();
                        string sdk_root        = Environment.GetEnvironmentVariable("XCODE_DEVELOPER_ROOT");
                        if (!String.IsNullOrEmpty(sdk_root))
                        {
                            procArgs.Append("--sdkroot ").Append(sdk_root);
                        }
                        procArgs.Append(" --launchdev ");
                        procArgs.Append(launchdev);
                        if (!String.IsNullOrEmpty(device_name))
                        {
                            procArgs.Append(" --devname=").Append(device_name);
                        }
                        procArgs.Append(" -argument=-connection-mode -argument=none");
                        procArgs.Append(" -argument=-app-arg:-autostart");
                        procArgs.Append(" -argument=-app-arg:-autoexit");
                        procArgs.Append(" -argument=-app-arg:-enablenetwork");
                        procArgs.AppendFormat(" -argument=-app-arg:-hostport:{0}", listener.Port);
                        procArgs.Append(" -argument=-app-arg:-hostname:");

                        if (ip != null)
                        {
                            procArgs.Append(ip.ToString());
                        }
                        else
                        {
                            bool foundIP = false;
                            if (inte != "")
                            {
                                foreach (NetworkInterface net in NetworkInterface.GetAllNetworkInterfaces())
                                {
                                    if (net.Name == inte)
                                    {
                                        IPInterfaceProperties properties = net.GetIPProperties();
                                        foreach (IPAddressInformation unicast in properties.UnicastAddresses)
                                        {
                                            if (unicast.Address.AddressFamily == AddressFamily.InterNetwork)
                                            {
                                                foundIP = true;
                                            }
                                            procArgs.Append(unicast.Address.ToString());
                                        }
                                        break;
                                    }
                                }
                            }

                            if (!foundIP)
                            {
                                if (inte != "")
                                {
                                    Console.WriteLine("Could not find interface {0}, defaulting to ip address of your first available interface", inte);
                                }

                                var ipAddresses = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
                                for (int i = 0; i < ipAddresses.Length; i++)
                                {
                                    if (i > 0)
                                    {
                                        procArgs.Append(',');
                                    }
                                    procArgs.Append(ipAddresses [i].ToString());
                                }
                            }
                        }

                        proc.StartInfo.FileName               = mtouch;
                        proc.StartInfo.Arguments              = procArgs.ToString();
                        proc.StartInfo.UseShellExecute        = false;
                        proc.StartInfo.RedirectStandardOutput = true;
                        proc.StartInfo.RedirectStandardError  = true;
                        proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output) {
                                output.Append("[mtouch stderr] ");
                                output.AppendLine(e.Data);
                            }
                        };
                        proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output) {
                                output.Append("[mtouch stdout] ");
                                output.AppendLine(e.Data);
                            }
                        };
                        proc.Start();
                        proc.BeginErrorReadLine();
                        proc.BeginOutputReadLine();
                        proc.WaitForExit();
                        if (proc.ExitCode != 0)
                        {
                            listener.Cancel();
                        }

                        Console.WriteLine(output.ToString());
                    }
                });
            }

            if (launchsim != null)
            {
                ThreadPool.QueueUserWorkItem((v) => {
                    using (Process proc = new Process()) {
                        StringBuilder output   = new StringBuilder();
                        StringBuilder procArgs = new StringBuilder();
                        string sdk_root        = Environment.GetEnvironmentVariable("XCODE_DEVELOPER_ROOT");
                        if (!String.IsNullOrEmpty(sdk_root))
                        {
                            procArgs.Append("--sdkroot ").Append(sdk_root);
                        }
                        procArgs.Append(" --launchsim ");
                        procArgs.Append(launchsim);
                        if (!string.IsNullOrEmpty(device_type))
                        {
                            procArgs.Append(" --device ").Append(device_type);
                        }
                        procArgs.Append(" -argument=-connection-mode -argument=none");
                        procArgs.Append(" -argument=-app-arg:-autostart");
                        procArgs.Append(" -argument=-app-arg:-autoexit");
                        procArgs.Append(" -argument=-app-arg:-enablenetwork");
                        procArgs.Append(" -argument=-app-arg:-hostname:127.0.0.1");
                        procArgs.AppendFormat(" -argument=-app-arg:-hostport:{0}", listener.Port);
                        proc.StartInfo.FileName               = mtouch;
                        proc.StartInfo.Arguments              = procArgs.ToString();
                        proc.StartInfo.UseShellExecute        = false;
                        proc.StartInfo.RedirectStandardError  = true;
                        proc.StartInfo.RedirectStandardOutput = true;
                        proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output) {
                                output.AppendFormat("[mtouch stderr {0}] ", DateTime.Now.ToLongTimeString());
                                output.AppendLine(e.Data);
                            }
                        };
                        proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
                            lock (output) {
                                output.AppendFormat("[mtouch stdout {0}] ", DateTime.Now.ToLongTimeString());
                                output.AppendLine(e.Data);
                            }
                        };
                        if (verbose)
                        {
                            Console.WriteLine("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments);
                        }
                        proc.Start();
                        proc.BeginErrorReadLine();
                        proc.BeginOutputReadLine();
                        proc.WaitForExit();
                        listener.Cancel();
                        Console.WriteLine(output.ToString());
                    }
                });
            }

            return(listener.Start());
        } catch (OptionException oe) {
            Console.WriteLine("{0} for options '{1}'", oe.Message, oe.OptionName);
            return(1);
        } catch (Exception ex) {
            Console.WriteLine(ex);
            return(1);
        }
    }