public virtual AndroidEmulatorInstanceInfo EnsureInstance(SingleInstanceMode mode, Guid id, string avdName, int? consolePort, bool noBootAnim, bool noWindow)
        {

            AndroidEmulatorInstanceInfo result = new AndroidEmulatorInstanceInfo(_logger);

            var adb = _adbFactory.GetAndroidDebugBridge();
            var devices = adb.GetDevices();
            var deviceOnSamePort = devices.FirstOrDefault(a => a.Port == consolePort);

            if (deviceOnSamePort != null)
            {

                switch (mode)
                {
                    case SingleInstanceMode.Abort:
                        throw new InvalidOperationException("Cannot start emulator as there is already an existing emulator running on the same port. Use argument -s to specify single instance re-use options.");

                    case SingleInstanceMode.KillExisting:
                        // TODO: issue kill command for existing emulator before proceeding.
                        _logger.LogMessage("Found existing android device listening on same console port. Will kill.");
                        deviceOnSamePort.Kill(_logger);
                        break;

                    case SingleInstanceMode.ReuseExisting:
                    case SingleInstanceMode.ReuseExistingThenKill:
                        // TODO: don't start new emulator, use existing one - and' don't terminate afterwards.
                        _logger.LogMessage("Found existing android device listening on same console port. Will re-use this device.");
                        // Get existing process
                        result.Process = new ExistingEmulatorExeProcess(_emulatorExePath);
                        result.Device = deviceOnSamePort;
                        result.LeaveDeviceOpen = mode == SingleInstanceMode.ReuseExisting;
                        return result;
                }
            }

            // did not detect existing emulator instance / process on port, so proceed to create a new one.
            StringBuilder args = new StringBuilder();
            args.AppendFormat("-avd {0}", avdName);
            if (consolePort.HasValue && consolePort != 0)
            {
                args.AppendFormat(" -port {0}", consolePort);
            }
            if (noBootAnim)
            {
                args.Append(" -no-boot-anim");
            }
            if (noWindow)
            {
                args.Append(" -no-window");
            }

            args.AppendFormat(" -prop emu.uuid={0}", id);
            var process = ProcessHelper.GetProcess(_emulatorExePath, args.ToString());

            result.Process = process;
            result.Device = null;
            result.LeaveDeviceOpen = false;

            return result;
        }
        internal static void Make(SingleInstanceMode singleInstanceModes)
        {
            var appName = Application.Current.GetType().Assembly.ManifestModule.ScopeName;

            var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
            var keyUserName     = windowsIdentity != null?windowsIdentity.User.ToString() : string.Empty;

            // Be careful! Max 260 chars!
            var eventWaitHandleName = string.Format("{0}{1}", appName, singleInstanceModes == SingleInstanceMode.ForEveryUser ? keyUserName : string.Empty);

            try
            {
                using (var eventWaitHandle = EventWaitHandle.OpenExisting(eventWaitHandleName))
                {
                    // It informs first instance about other startup attempting.
                    eventWaitHandle.Set();
                }

                Environment.Exit(0);
            }
            catch
            {
                // It's first instance.

                // Register EventWaitHandle.
                using (var eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventWaitHandleName))
                {
                    ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, OtherInstanceAttemptedToStart, null, Timeout.Infinite, false);
                }

                RemoveApplicationsStartupDeadlockForStartupCrushedWindows();
            }
        }
Example #3
0
        static public bool TryStartBlocking(SingleInstanceMode Mode)
        {
            bool   onlyInstance = false;
            string mutexName    = String.Format(Mode == SingleInstanceMode.PerMachine ? "Global\\{0}" : "Local\\{0}", Api.AssemblyGuid);

            mutex = new Mutex(true, mutexName, out onlyInstance);
            return(onlyInstance);
        }
 public AndroidSdkEmulatorFactory(ILogger logger, string emulatorExePath, IAndroidDebugBridgeFactory adbFactory, string avdName, int port, bool noBootAnim, bool noWindow, Guid id, SingleInstanceMode singleInstanceMode = SingleInstanceMode.Abort)
 {
     _Logger = logger;
     _EmulatorExePath = emulatorExePath;
     _adbFactory = adbFactory;
     _avdName = avdName;
     _port = port;
     _noBootAnim = noBootAnim;
     _noWindow = noWindow;
     _id = id;
     _SingleInstanceMode = singleInstanceMode;
 }
 public AndroidSdkEmulator(ILogger logger, string emulatorExePath, string avdName, IAndroidDebugBridgeFactory adbFactory, Guid id, int? consolePort, SingleInstanceMode instanceMode = SingleInstanceMode.KillExisting, bool noBootAnim = true, bool noWindow = true)
 {
     _logger = logger;
     _avdName = avdName;
     _adbFactory = adbFactory;
     _id = id;
     _consolePort = consolePort;
     _instanceMode = instanceMode;
     _noBootAnime = noBootAnim;
     _noWindow = noWindow;
     _instanceResolver = new AndroidEmulatorInstanceResolver(logger, adbFactory, emulatorExePath);
 }      
Example #6
0
        /// <summary>
        /// Processing single instance.
        /// </summary>
        internal static void Make(SingleInstanceMode mode, Action <object> callback)
        {
            SecondInstanceCallback = callback;

#if DEBUG
            var appName = string.Format("{0}DEBUG", Application.Current.GetType().Assembly.ManifestModule.ScopeName);
#else
            var appName = Application.Current.GetType().Assembly.ManifestModule.ScopeName;
#endif

            var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
            var keyUserName     = ((windowsIdentity != null) ? windowsIdentity.User.ToString() : string.Empty);

            // Be careful! Max 260 chars!
            var eventWaitHandleName = string.Format("{0}{1}", appName, ((mode == SingleInstanceMode.ForEveryUser) ? keyUserName : string.Empty));

            try
            {
                using (var waitHandle = EventWaitHandle.OpenExisting(eventWaitHandleName))
                {
                    // It informs first instance about other startup attempting.
                    waitHandle.Set();
                }

                // Let's terminate this posterior startup.
                // For that exit no interception.
                Environment.Exit(0);
            }
            catch
            {
                // It's first instance.
                // Register EventWaitHandle.
                using (var eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventWaitHandleName))
                {
                    ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, OtherInstanceAttemptedToStart, null, Timeout.Infinite, false);
                }

                RemoveApplicationsStartupDeadlockForStartupCrushedWindows();
            }
        }
        /// <summary>
        /// Processing single instance.
        /// </summary>
        internal static void Make( SingleInstanceMode mode, Action<object> callback )
        {
            SecondInstanceCallback = callback;

#if DEBUG
            var appName = string.Format( "{0}DEBUG", Application.Current.GetType().Assembly.ManifestModule.ScopeName );
#else
		    var appName = Application.Current.GetType().Assembly.ManifestModule.ScopeName;
#endif

            var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
            var keyUserName = ( ( windowsIdentity != null ) ? windowsIdentity.User.ToString() : string.Empty );

            // Be careful! Max 260 chars!
            var eventWaitHandleName = string.Format( "{0}{1}", appName, ( ( mode == SingleInstanceMode.ForEveryUser ) ? keyUserName : string.Empty ) );

            try
            {
                using ( var waitHandle = EventWaitHandle.OpenExisting( eventWaitHandleName ) )
                {
                    // It informs first instance about other startup attempting.
                    waitHandle.Set();
                }

                // Let's terminate this posterior startup.
                // For that exit no interception.
                Environment.Exit( 0 );
            }
            catch
            {
                // It's first instance.
                // Register EventWaitHandle.
                using ( var eventWaitHandle = new EventWaitHandle( false, EventResetMode.AutoReset, eventWaitHandleName ) )
                {
                    ThreadPool.RegisterWaitForSingleObject( eventWaitHandle, OtherInstanceAttemptedToStart, null, Timeout.Infinite, false );
                }

                RemoveApplicationsStartupDeadlockForStartupCrushedWindows();
            }
        }
        public async void Can_Detect_Existing_Device(SingleInstanceMode singleInstanceMode)
        {
            var logger = new ConsoleLogger();
            Guid emuId = Guid.NewGuid();

            // Start an emulator.
            var adbFactory = new AndroidDebugBridgeFactory(TestConfig.PathToAdbExe);
            int consolePort = 5554;
            var emuFactory = new AndroidSdkEmulatorFactory(logger, TestConfig.PathToAndroidEmulatorExe, adbFactory, TestConfig.AvdName, consolePort, true, false, emuId);

            using (IEmulator droidEmulator = emuFactory.GetEmulator())
            {
                await droidEmulator.Start(TestConfig.EmulatorStartupTimeout).ContinueWith((t) =>
                {
                    // sut
                    var adb = adbFactory.GetAndroidDebugBridge();
                    var devices = adb.GetDevices();

                    Assert.That(devices, Is.Not.Null);
                    Assert.That(devices.Length, Is.GreaterThanOrEqualTo(1));

                    var deviceFound = devices.Where(a => a.Port == consolePort).FirstOrDefault();
                    Assert.That(deviceFound, Is.Not.Null);

                    foreach (var item in devices)
                    {
                        Console.WriteLine("Device Name: {0}, Status: {1}", item.Name, item.Status);
                    }

                });


            }


        }