예제 #1
0
        public async Task TestWithMessagesForSeconds(int seconds)
        {
            var dummySQS = new GeneratedDataSqs(MakeResponse, CancelAfterSeconds(seconds));

            int receivedCount = 0;

            async Task <bool> Handler(Message message)
            {
                await Task.Delay(50);

                Console.WriteLine($"Handled message {message.Body}");

                Interlocked.Increment(ref receivedCount);
                return(true);
            }

            var wrappedHandler = Handlers.Wrap(Handler, dummySQS, OnTiming, OnException);

            var listener = new SimpleListener(dummySQS,
                                              wrappedHandler,
                                              CancelAfterSeconds(seconds),
                                              new NullListenerLogger());

            await listener.Listen();

            Assert.True(receivedCount > 10 * seconds);
        }
예제 #2
0
파일: VimTest.cs 프로젝트: louisfeng/VsVim
        protected VimTest()
        {
            _factory = new MockRepository(MockBehavior.Strict);
            _globalSettings = new GlobalSettings();
            _fileSystem = _factory.Create<IFileSystem>(MockBehavior.Strict);
            _bufferFactory = VimBufferFactory;
            _simpleListener = new SimpleListener();
            var creationListeners = new [] { new Lazy<IVimBufferCreationListener>(() => _simpleListener) };

            var map = new Dictionary<string, VariableValue>();
            _keyMap = new KeyMap(_globalSettings, map);
            _vimHost = _factory.Create<IVimHost>(MockBehavior.Strict);
            _vimHost.Setup(x => x.CreateHiddenTextView()).Returns(CreateTextView());
            _vimHost.Setup(x => x.AutoSynchronizeSettings).Returns(true);
            _vimRaw = new Vim(
                _vimHost.Object,
                _bufferFactory,
                CompositionContainer.GetExportedValue<IVimInterpreterFactory>(),
                creationListeners.ToFSharpList(),
                _globalSettings,
                _factory.Create<IMarkMap>().Object,
                _keyMap,
                MockObjectFactory.CreateClipboardDevice().Object,
                _factory.Create<ISearchService>().Object,
                _fileSystem.Object,
                new VimData(_globalSettings),
                _factory.Create<IBulkOperations>().Object,
                map,
                new EditorToSettingSynchronizer());
            _vim = _vimRaw;
            _vim.AutoLoadVimRc = false;
        }
예제 #3
0
파일: VimTest.cs 프로젝트: KinHimTang/VsVim
        protected VimTest(bool createVim = true)
        {
            _factory        = new MockRepository(MockBehavior.Strict);
            _globalSettings = new GlobalSettings();
            _fileSystem     = _factory.Create <IFileSystem>(MockBehavior.Strict);
            _bufferFactory  = VimBufferFactory;
            _simpleListener = new SimpleListener();

            _variableMap = new Dictionary <string, VariableValue>();
            _keyMap      = new KeyMap(_globalSettings, _variableMap);
            _vimHost     = _factory.Create <IVimHost>(MockBehavior.Strict);
            _vimHost.Setup(x => x.ShouldIncludeRcFile(It.IsAny <VimRcPath>())).Returns(true);
            _vimHost.Setup(x => x.CreateHiddenTextView()).Returns(CreateTextView());
            _vimHost.Setup(x => x.AutoSynchronizeSettings).Returns(true);
            _vimHost.Setup(x => x.VimCreated(It.IsAny <IVim>()));
            _vimHost.Setup(x => x.GetName(It.IsAny <ITextBuffer>())).Returns("VimTest.cs");
            _vimHost.Setup(x => x.EnsurePackageLoaded());
            _vimHost.SetupGet(x => x.DefaultSettings).Returns(DefaultSettings.GVim74);
            _vimHost.Setup(x => x.DoActionWhenTextViewReady(It.IsAny <FSharpFunc <Unit, Unit> >(), It.IsAny <ITextView>()))
            .Callback((FSharpFunc <Unit, Unit> action, ITextView textView) => action.Invoke(null));
            if (createVim)
            {
                CreateVim();
            }
        }
예제 #4
0
파일: VimTest.cs 프로젝트: zhutoulwz/VsVim
        protected VimTest()
        {
            _factory        = new MockRepository(MockBehavior.Strict);
            _globalSettings = new GlobalSettings();
            _fileSystem     = _factory.Create <IFileSystem>(MockBehavior.Strict);
            _bufferFactory  = VimBufferFactory;
            _simpleListener = new SimpleListener();
            var creationListeners = new [] { new Lazy <IVimBufferCreationListener>(() => _simpleListener) };

            var map = new Dictionary <string, VariableValue>();

            _keyMap  = new KeyMap(_globalSettings, map);
            _vimHost = _factory.Create <IVimHost>(MockBehavior.Strict);
            _vimHost.Setup(x => x.CreateHiddenTextView()).Returns(CreateTextView());
            _vimHost.Setup(x => x.AutoSynchronizeSettings).Returns(true);
            _vimRaw = new Vim(
                _vimHost.Object,
                _bufferFactory,
                CompositionContainer.GetExportedValue <IVimInterpreterFactory>(),
                creationListeners.ToFSharpList(),
                _globalSettings,
                _factory.Create <IMarkMap>().Object,
                _keyMap,
                MockObjectFactory.CreateClipboardDevice().Object,
                _factory.Create <ISearchService>().Object,
                _fileSystem.Object,
                new VimData(),
                _factory.Create <IBulkOperations>().Object,
                map,
                new EditorToSettingSynchronizer());
            _vim = _vimRaw;
            _vim.AutoLoadVimRc = false;
        }
예제 #5
0
        public async Task TestWithOneMessage()
        {
            var responses = MakeResponses(1);
            var dummySQS  = new FixedDataSqs(responses);

            int receivedCount = 0;

            async Task <bool> Handler(Message message)
            {
                await Task.Delay(100);

                Console.WriteLine($"Handled message {message.Body}");

                Interlocked.Increment(ref receivedCount);
                return(true);
            }

            var wrappedHandler = Handlers.Wrap(Handler, dummySQS, OnTiming, OnException);

            var listener = new SimpleListener(dummySQS,
                                              wrappedHandler,
                                              CancelAfterSeconds(1),
                                              new NullListenerLogger());

            await listener.Listen();

            Assert.Equal(1, receivedCount);
        }
예제 #6
0
        public async Task RunForASecond()
        {
            var dummySqs = new FixedDataSqs(Enumerable.Empty <ReceiveMessageResponse>());

            var listener = new SimpleListener(
                dummySqs,
                Handler,
                CancelAfterSeconds(1),
                new NullListenerLogger());

            await listener.Listen();
        }
예제 #7
0
        public void TriggerStaticEvent()
        {
            SimplePublisher publisher = (SimplePublisher)_container["SimplePublisher"];
            SimpleListener  listener  = (SimpleListener)_container["SimpleListener"];

            Assert.IsFalse(listener.Listened);
            Assert.IsNull(listener.Sender);

            publisher.Trigger();

            Assert.IsTrue(listener.Listened);
            Assert.AreSame(publisher, listener.Sender);
        }
예제 #8
0
        public async Task RunForFiveSeconds()
        {
            var dummySQS = new FixedDataSqs(Enumerable.Empty <ReceiveMessageResponse>());

            var handler = Handlers.Wrap(Handler, dummySQS, OnTiming, OnException);

            var listener = new SimpleListener(dummySQS,
                                              handler,
                                              CancelAfterSeconds(5),
                                              new NullListenerLogger());

            await listener.Listen();
        }
예제 #9
0
        protected VimTest(bool createVim = true)
        {
            _factory        = new MockRepository(MockBehavior.Strict);
            _globalSettings = new GlobalSettings();
            _fileSystem     = _factory.Create <IFileSystem>(MockBehavior.Strict);
            _bufferFactory  = VimBufferFactory;
            _simpleListener = new SimpleListener();

            _variableMap = new Dictionary <string, VariableValue>();
            _keyMap      = new KeyMap(_globalSettings, _variableMap);
            _vimHost     = _factory.Create <IVimHost>(MockBehavior.Strict);
            _vimHost.Setup(x => x.ShouldIncludeRcFile(It.IsAny <VimRcPath>())).Returns(true);
            _vimHost.Setup(x => x.CreateHiddenTextView()).Returns(CreateTextView());
            _vimHost.Setup(x => x.AutoSynchronizeSettings).Returns(true);
            _vimHost.Setup(x => x.VimCreated(It.IsAny <IVim>()));
            _vimHost.SetupGet(x => x.DefaultSettings).Returns(DefaultSettings.GVim73);
            if (createVim)
            {
                CreateVim();
            }
        }
예제 #10
0
        protected VimTest(bool createVim = true)
        {
            _factory = new MockRepository(MockBehavior.Strict);
            _globalSettings = new GlobalSettings();
            _fileSystem = _factory.Create<IFileSystem>(MockBehavior.Strict);
            _bufferFactory = VimBufferFactory;
            _simpleListener = new SimpleListener();

            _variableMap = new Dictionary<string, VariableValue>();
            _keyMap = new KeyMap(_globalSettings, _variableMap);
            _vimHost = _factory.Create<IVimHost>(MockBehavior.Strict);
            _vimHost.Setup(x => x.ShouldIncludeRcFile(It.IsAny<VimRcPath>())).Returns(true);
            _vimHost.Setup(x => x.CreateHiddenTextView()).Returns(CreateTextView());
            _vimHost.Setup(x => x.AutoSynchronizeSettings).Returns(true);
            _vimHost.Setup(x => x.VimGlobalSettingsCreated(It.IsAny<IVimGlobalSettings>()));
            _vimHost.SetupGet(x => x.DefaultSettings).Returns(DefaultSettings.GVim73);
            if (createVim)
            {
                CreateVim();
            }
        }
예제 #11
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);
        }
    }
예제 #12
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 (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;
		}
	}   
예제 #13
0
파일: Program.cs 프로젝트: gynorbi/home
        static void Main(string[] args)
        {
            var listener = new SimpleListener();

            listener.StartListeningOn("http://localhost:88");
        }
예제 #14
0
    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);
        }
    }
예제 #15
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);
        }
    }
예제 #16
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;
		}
	}   
예제 #17
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;
        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);
        }
    }
예제 #18
0
 private void Awake()
 {
     changeListener = new SimpleListener <IntVector2>(OnChangeCommand);
 }