Пример #1
0
 public void Dispose()
 {
     _ready = false;
     npine?.Dispose();
     _mutexc?.Close();
     _mutexs?.Close();
 }
Пример #2
0
 internal void Stop()
 {
     _service?.Close();
     _service = null;
     _sync?.Close();
     _sync = null;
 }
Пример #3
0
 private void wpfApp_Exit(object sender, ExitEventArgs e)
 {
     try
     {
         Task mutexCleanup = new Task(() =>
         {
             if (HasMutex)
             {
                 s_mutex?.Close();
                 s_mutex?.Dispose();
                 s_mutex = null;
             }
             else if (!GainMutexTask.IsCompleted)
             {
                 AbortMutex = true;
                 GainMutexTask.Wait();
             }
         });
         mutexCleanup.Start();
         mutexCleanup.Wait();
     }
     catch (Exception ex)
     {
         LogHelper.LogException(ex, ex.Message);
     }
     finally
     {
         LogHelper.LogMessage(LogLevel.Info, string.Format("Shutdown Application {0}", Assembly.GetExecutingAssembly().FullName));
     }
 }
Пример #4
0
 protected override void OnExit(ExitEventArgs e)
 {
     base.OnExit(e);
     LockObject?.ReleaseMutex();
     LockObject?.Close();
     LockObject = null;
 }
Пример #5
0
 public void Dispose()
 {
     _reader?.Dispose();
     _writer?.Dispose();
     _memoryMappedFile?.Dispose();
     _keystoreLock?.Close();
 }
        private static void Main(string[] args)
        {
            Mutex lck  = (Mutex)null;
            bool  flag = false;

            Strings.CurrentDefaultVmName = "Android";
            int num1 = ProcessUtils.CheckAlreadyRunningAndTakeLock(Strings.GetPlayerLockName(Strings.CurrentDefaultVmName, "bgp"), out lck) ? 1 : 0;

            lck?.Close();
            if (num1 == 0 && BlueStacks.GuestCommandRunner.GuestCommandRunner.LaunchBlueStacks())
            {
                flag = true;
                Console.WriteLine("Successfully Launched AppPlayer");
            }
            lck?.Close();
            if (!BlueStacks.GuestCommandRunner.GuestCommandRunner.CheckIfGuestStarted())
            {
                Environment.Exit(-1);
            }
            AdbCommandRunner adbCommandRunner = new AdbCommandRunner(Strings.CurrentDefaultVmName);

            for (int index = 0; index < VMCommand.COMMAND.Length; ++index)
            {
                if (!string.IsNullOrEmpty(VMCommand.COMMAND[index]) && string.Compare(VmCmdHandler.RunCommand(VMCommand.COMMAND[index], Strings.CurrentDefaultVmName, "bgp"), "ok", true) != 0)
                {
                    if (Oem.Instance.IsHideMessageBoxIconInTaskBar)
                    {
                        int num2 = (int)MessageBox.Show((IWin32Window) new Form(), "Error, Something went wrong!");
                    }
                    else
                    {
                        int num3 = (int)MessageBox.Show("Error, Something went wrong!");
                    }
                    adbCommandRunner.Dispose();
                    Environment.Exit(-1);
                }
            }
            adbCommandRunner.Dispose();
            Thread.Sleep(2000);
            BlueStacks.GuestCommandRunner.GuestCommandRunner.StopZygote();
            BlueStacks.GuestCommandRunner.GuestCommandRunner.StartZygote();
            if (!flag)
            {
                return;
            }
            BlueStacks.GuestCommandRunner.GuestCommandRunner.ExitBlueStacks();
        }
Пример #7
0
        protected override void OnExit(ExitEventArgs e)
        {
            Mutex?.Close();
            Mutex?.Dispose();
            Mutex = null;

            base.OnExit(e);
        }
Пример #8
0
        /// <summary>
        /// System.Windows.Application.Exit イベント を発生させます。
        /// </summary>
        /// <param name="e">イベントデータ を格納している ExitEventArgs</param>
        protected override void OnExit(ExitEventArgs e)
        {
            mutex?.Close();

            base.OnExit(e);

            this.notifyIcon?.Dispose();
        }
        public void Stop()
        {
            _isRunning = false;
            _pipeServer?.Close();
            _pipeServer = null;

            _mutex?.Close();
            _mutex = null;
        }
Пример #10
0
        protected override void OnExit(ExitEventArgs e)
        {
            mutex?.Close();
            mutex?.Dispose();
            mutex = null;

            UnityContainer.Dispose();

            base.OnExit(e);
        }
Пример #11
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                _Mutex?.Close();
                _Mutex?.Dispose();
                _Mutex = null;

                disposed = true;
            }
        }
Пример #12
0
        protected override void OnExit(ExitEventArgs e)
        {
            if (NormaConstants.IsSupportedNewToast)
            {
                NotificationActivatorBase.UnregisterComType();
            }
            (Shell.TaskbarIcon.DataContext as IDisposable)?.Dispose();
            Shell.TaskbarIcon.Dispose();

            _mutex?.ReleaseMutex();
            _mutex?.Close();
            base.OnExit(e);
        }
Пример #13
0
Файл: test.cs Проект: mono/gert
	static void Main ()
	{
		// allow only one instance of the process
		Mutex onlyOne = new Mutex (true, "bug349680");

		if (onlyOne.WaitOne (0, false)) {
			try {
				new Program ();
			} finally {
				onlyOne.Close ();
				onlyOne = null;
			}
		}
	}
Пример #14
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            lock (this)
            {
                if (!Disposed)
                {
                    Disposed = true;
                    GC.SuppressFinalize(this);

                    _mutex?.Close();
                    _mutex?.Dispose();
                    _mutex = null;
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Releases all resources used by the current instance.
        /// </summary>
        /// <remarks>
        /// <para>Dispose(bool disposing) executes in two distinct scenarios.</para>
        /// <para>If the method has been called directly or indirectly by a user's code managed and unmanaged resources can be disposed.</para>
        /// <para>If the method has been called by the runtime from inside the finalizer you should not reference other objects. Only unmanaged resources can be disposed.</para>
        /// </remarks>
        /// <param name="disposing">Specifies if the method has been called by a user's code (true) or by the runtime from inside the finalizer (false).</param>
        private void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                    // Dispose managed resources.
                    // ...

                    mutex?.Close();
                    mutex = null;
                }

                // Call the appropriate methods to clean up unmanaged resources here.
                // ...

                isDisposed = true;
            }
        }
Пример #16
0
  // Methods
  public static LoadBalancer GetLoadBalancer()
  {
    // Support multithreaded applications through
    // "Double checked locking" pattern which avoids 
    // locking every time the method is invoked
    if( balancer == null )
    {
      // Only one thread can obtain a mutex
      Mutex mutex = new Mutex();
      mutex.WaitOne();

      if( balancer == null )
        balancer = new LoadBalancer();

      mutex.Close();
    }
    
    return balancer;
  }
Пример #17
0
        public static bool Create(string procMtxName, string title)
        {
            try
            {
                MutexSecurity security = new MutexSecurity();

                security.AddAccessRule(
                    new MutexAccessRule(
                        new SecurityIdentifier(
                            WellKnownSidType.WorldSid,
                            null
                            ),
                        MutexRights.FullControl,
                        AccessControlType.Allow
                        )
                    );

                bool createdNew;
                ProcMtx = new Mutex(false, @"Global\Global_" + procMtxName, out createdNew, security);

                if (ProcMtx.WaitOne(0))
                {
                    return(true);
                }

                ProcMtx.Close();
                ProcMtx = null;
            }
            catch
            { }

            CloseProcMtx();

            MessageBox.Show(
                "Already started on the other logon session !",
                title + " / Error",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error
                );

            return(false);
        }
Пример #18
0
        public static bool AlreadyRunning(string mutexName)
        {
            long runningId       = 50000;
            bool InstanceRunning = false;

            Process proc = Process.GetCurrentProcess();

            Process[] runningProcesses = Process.GetProcesses();

            foreach (Process p in runningProcesses)
            {
                if (p.Id != proc.Id)
                {
                    bool Created = false;
                    mutex = new Mutex(true, mutexName + p.Id.ToString(), out Created);
                    if (!Created)
                    {
                        InstanceRunning = true;
                        runningId       = p.Id;
                        break;
                    }
                    else
                    {
                        mutex.Close();
                    }
                }
            }
            if (InstanceRunning)
            {
                IntPtr hWnd = Process.GetProcessById((int)runningId).MainWindowHandle;
                if (NativeMethods.IsIconic(hWnd))
                {
                    NativeMethods.ShowWindowAsync(hWnd, 9);
                }
                NativeMethods.SetForegroundWindow(hWnd);
            }
            else
            {
                mutex = new Mutex(true, mutexName + proc.Id.ToString());
            }
            return(InstanceRunning);
        }
Пример #19
0
        public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData)
        {
            if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
            {
                throw new ArgumentOutOfRangeException(nameof(categoryType));
            }
            if (counterData == null)
            {
                throw new ArgumentNullException(nameof(counterData));
            }

            CheckValidCategory(categoryName);
            if (categoryHelp != null)
            {
                // null categoryHelp is a valid option - it gets set to "Help Not Available" later on.
                CheckValidHelp(categoryHelp);
            }
            string machineName = ".";

            Mutex mutex = null;

            try
            {
                SharedUtils.EnterMutex(PerfMutexName, ref mutex);
                if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.Format(SR.PerformanceCategoryExists, categoryName));
                }

                CheckValidCounterLayout(counterData);
                PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData);
                return(new PerformanceCounterCategory(categoryName, machineName));
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
Пример #20
0
        private void RestartAsAdmin()
        {
            var message = "This application must be run as administrator.";

            logger.Log(message, LogState.Error);

            if (MessageBox.Show(message + "\nClick Yes will restart as administrator automatically.", "Sidekick", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Mutex?.Close();
                try
                {
                    using (var p = new Process())
                    {
                        p.StartInfo.FileName        = Application.ExecutablePath;
                        p.StartInfo.UseShellExecute = true;
                        p.StartInfo.Verb            = "runas";
                        p.Start();
                    }
                }
                catch (Win32Exception e)
                {
                    const int ERROR_CANCELLED = 1223; //The operation was canceled by the user.

                    if (e.NativeErrorCode == ERROR_CANCELLED)
                    {
                        MessageBox.Show("This application must be run as administrator.");
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                finally
                {
                    Environment.Exit(Environment.ExitCode);
                }
            }
        }
Пример #21
0
        public static void Close()
        {
            if (driver == null)
            {
                return;
            }

            uint refCount = 0;

            driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);

            driver.Close();

            if (refCount <= 1)
            {
                driver.Delete();
            }

            driver = null;

            if (isaBusMutex != null)
            {
                isaBusMutex.Close();
                isaBusMutex = null;
            }

            if (pciBusMutex != null)
            {
                pciBusMutex.Close();
                pciBusMutex = null;
            }

            // try to delete temporary driver file again if failed during open
            if (fileName != null && File.Exists(fileName))
            {
                try {
                    File.Delete(fileName);
                    fileName = null;
                } catch (IOException) { }
                catch (UnauthorizedAccessException) { }
            }
        }
Пример #22
0
        public static void GUIMain(Func <Form> getMainForm)
        {
            Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomainUnhandledException);
            SystemEvents.SessionEnding += new SessionEndingEventHandler(SessionEnding);

            //WriteLog = message => { };

            SelfFile = Assembly.GetEntryAssembly().Location;
            SelfDir  = Path.GetDirectoryName(SelfFile);

            Mutex procMutex = new Mutex(false, APP_IDENT);

            if (procMutex.WaitOne(0))
            {
                if (GlobalProcMtx.Create(APP_IDENT, APP_TITLE))
                {
                    CheckSelfFile();
                    Directory.SetCurrentDirectory(SelfDir);
                    CheckLogonUserAndTmp();

                    WorkingDir.Root = WorkingDir.CreateProcessRoot();

                    ArgsReader = GetArgsReader();

                    // core >

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(getMainForm());

                    // < core

                    WorkingDir.Root.Delete();
                    WorkingDir.Root = null;

                    GlobalProcMtx.Release();
                }
                procMutex.ReleaseMutex();
            }
            procMutex.Close();
        }
Пример #23
0
 private static void Cleanup()
 {
     CommandHandler.CloseShell();
     if (CommandHandler.StreamCodec != null)
     {
         CommandHandler.StreamCodec.Dispose();
     }
     if (Keylogger.Instance != null)
     {
         Keylogger.Instance.Dispose();
     }
     if (_msgLoop != null)
     {
         _msgLoop.ExitThread();
     }
     if (_appMutex != null)
     {
         _appMutex.Close();
     }
 }
        private void CleanUp(bool disposing)
        {
            // Be sure we have not already been disposed!
            if (!this.disposed)
            {
                // If disposing equals true, dispose all
                // managed resources.
                if (disposing)
                {
                    _mutex.ReleaseMutex();
                }

                if (_mutex != null)
                {
                    _mutex.Close();
                }
                // Clean up unmanaged resources here.
                disposed = true;
            }
        }
Пример #25
0
        static void Main(string[] args)
        {
            Mutex        mutex     = null;
            const string mutexName = "RUNMEONLYONCE";

            while (true)
            {
                try
                {
                    mutex = Mutex.OpenExisting(mutexName);
                    mutex.Close();
                    Console.WriteLine("Closed existing Mutex");
                }
                catch (WaitHandleCannotBeOpenedException e)
                {
                    mutex = new Mutex(true, mutexName);
                    Console.WriteLine("Created new Mutex");
                }
            }
        }
Пример #26
0
        private void goruntuAl_Load(object sender, EventArgs e)
        {
            Mutex Mtx = new Mutex(false, "SINGLE_INSTANCE_APP_MUTEX");

            if (Mtx.WaitOne(0, false) == false)
            {
                Mtx.Close();

                Mtx = null;

                Application.Exit();
            }
            //
            this.ShowInTaskbar = false;
            timer1.Start();
            timer2.Start();
            cek();
            Directory.CreateDirectory(@"C:\\" + "Windows2");
            saat = DateTime.Now.ToLongTimeString();
        }
        public void Close()
        {
            if (accessor != null)
            {
                accessor.Dispose();
                accessor = null;
            }

            if (file != null)
            {
                file.Dispose();
                file = null;
            }

            if (mutexShMem != null)
            {
                mutexShMem.Close();
                mutexShMem = null;
            }
        }
Пример #28
0
        private void CreateLock()
        {
            bool created;

            try
            {
                var name = Assembly.GetEntryAssembly().GetName().Name;
                LockObject = new Mutex(true, name, out created);
            }
            catch (Exception)
            {
                created = false;
            }
            if (!created)
            {
                LockObject?.Close();
                LockObject = null;
                Application.Current.Shutdown();
            }
        }
Пример #29
0
        public App()
        {
            DispatcherUnhandledException += (send, e) =>
            {
                LogHelper.LogError("Unhandled exception happen:", e.Exception);
                e.Handled = true;
            };

            CheckSinglonInstance(Environment.GetCommandLineArgs());

            Exit += (sender, e) =>
            {
                if (_mutex == null)
                {
                    return;
                }
                _mutex.Close();
                _mutex = null;
            };
        }
Пример #30
0
        static void Main(string[] args)
        {
            var mut    = new Mutex(false, "MutexForFile");
            var writer = new Process {
                StartInfo = { FileName = "FileWriter.exe" }
            };
            var reader = new Process {
                StartInfo = { FileName = "FileReader.exe" }
            };

            writer.Start();
            reader.Start();
            Console.WriteLine("++++++");
            writer.WaitForExit();
            Console.WriteLine("8749672984757984");
            reader.WaitForExit();
            Console.WriteLine("-----------------");
            mut.Close();
            Console.ReadKey();
        }
Пример #31
0
        static void Main()
        {
            bool  createdNew;
            Mutex mu = new Mutex(false, "ServerApplicationMutex",
                                 out createdNew);

            if (!createdNew)
            {
                MessageBox.Show("Another copy of the Server Application is already running!");
                Application.Exit();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormServer());

            //mu.ReleaseMutex();
            mu.Close();
        }
Пример #32
0
        /// <summary>
        /// Handles event Window Loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Check, if another instance is active already.
                mutex_ = Mutex.OpenExisting(InstanceMutexName);
                MessageBox.Show("Another instance of the application is running already.", Title, MessageBoxButton.OK,
                                MessageBoxImage.Information);
                mutex_.Close();
                mutex_ = null;

                Close();
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                // No another active instance.
                mutex_ = new Mutex(true, InstanceMutexName);
                WindowManager.Instance.WindowConfig.SetWindowPosition(this);
            }
        }
Пример #33
0
    private static void Main(string[] args)
    {
        //uninstall?
        string[] arguments = Environment.GetCommandLineArgs();

        foreach (string argument in arguments)
        {
            if (argument.Split('=')[0].ToLower() == "/u")
            {
                string guid = argument.Split('=')[1];
                string path = Environment.GetFolderPath(Environment.SpecialFolder.System);
                var si = new ProcessStartInfo(path + "/msiexec.exe", "/x " + guid);
                Process.Start(si);
                Application.Exit();
                return;
            }
        }

        try
        {
            Application.EnableVisualStyles();            
            Application.SetCompatibleTextRenderingDefault(false);


            bool firstInstance = true;

            var me = Process.GetCurrentProcess();
            var arrProcesses = Process.GetProcessesByName(me.ProcessName);

            //only want to do this if not passing in a command

            if (arrProcesses.Length > 1)
            {
                firstInstance = false;
            }
            
            string executableName = Application.ExecutablePath;
            var executableFileInfo = new FileInfo(executableName);
            ExecutableDirectory = executableFileInfo.DirectoryName;

            bool ei = (!Directory.Exists(AppDataPath) || !Directory.Exists(AppDataPath + @"XML\") ||
                       !File.Exists(AppDataPath + @"XML\config.xml"));
            if (ei)
                EnsureInstall(true);
            else
            {
                try
                {
                    var o = Registry.CurrentUser.OpenSubKey(@"Software\ispy",true);
                    if (o?.GetValue("firstrun") != null)
                    {
                        o.DeleteValue("firstrun");
                        //copy over updated static files on first run of new install
                        EnsureInstall(false);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogExceptionToFile(ex, "startup");
                }
            }

            bool silentstartup = false;

            string command = "";
            if (args.Length > 0)
            {
                if (args[0].ToLower().Trim() == " - reset" && !ei)
                {
                    if (firstInstance)
                    {
                        if (
                            MessageBox.Show("Reset iSpy? This will overwrite all your settings.", "Confirm",
                                            MessageBoxButtons.OKCancel) == DialogResult.OK)
                            EnsureInstall(true);
                    }
                    else
                    {
                        MessageBox.Show("Please exit iSpy before resetting it.");
                    }
                }
                if (args[0].ToLower().Trim() == "-silent" || args[0].ToLower().Trim('\\') == "s")
                {
                    if (firstInstance)
                    {
                        silentstartup = true;
                    }
                }
                else
                {
                    command = args.Aggregate(command, (current, s) => current + (s + " "));
                }
            }

            if (!firstInstance)
            {
                if (!string.IsNullOrEmpty(command))
                {
                    File.WriteAllText(AppDataPath + "external_command.txt", command);
                    Thread.Sleep(1000);
                }
                else
                {
                    //show form
                    File.WriteAllText(AppDataPath + "external_command.txt", "showform");
                    Thread.Sleep(1000);
                }
                
                Application.Exit();
                return;
            }

            if (IntPtr.Size == 8)
                Platform = "x64";

            File.WriteAllText(AppDataPath + "external_command.txt", "");

            // in case our https certificate ever expires or there is some other issue
            ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.DefaultConnectionLimit = 1000;

            FfmpegMutex = new Mutex();
            
            Application.ThreadException += ApplicationThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
            
            var ffmpegSetup = new Init();
            ffmpegSetup.Initialise();

            _previousExecutionState = NativeCalls.SetThreadExecutionState(NativeCalls.EsContinuous | NativeCalls.EsSystemRequired);
            
            AppIdle = new WinFormsAppIdleHandler {Enabled = false};
            var mf = new MainForm(silentstartup, command);
            Application.Run(mf);
            FfmpegMutex.Close();

            GC.KeepAlive(FfmpegMutex);
            AppIdle.Enabled = false;
            ffmpegSetup.DeInitialise();
            

            if (_previousExecutionState != 0)
            {
                NativeCalls.SetThreadExecutionState(_previousExecutionState);
            }
            
        }
        catch (Exception ex)
        {
            try
            {
                Logger.LogExceptionToFile(ex);
            } catch
            {
                
            }
            while (ex.InnerException != null)
            {
                try
                {
                    Logger.LogExceptionToFile(ex);
                }
                catch
                {

                }
            }
        }
    }
Пример #34
0
        static void ThreadFunc()
        {
            bool bCreated = false;
            var user = "******";
            var rule = new MutexAccessRule(user, MutexRights.FullControl, AccessControlType.Allow );
            var mSecurity = new MutexSecurity();
            mSecurity.AddAccessRule(rule);
            
            Mutex m = new Mutex(true, Program.mutex_name, out bCreated, mSecurity);
            if (!bCreated)
            {
                Console.WriteLine("Waiting... {0}", Thread.CurrentThread.ManagedThreadId);
                m.WaitOne();
                Console.WriteLine("Acquired Mutex! {0}", Thread.CurrentThread.ManagedThreadId);
            }

            System.Threading.Thread.Sleep(5 * 1000);

            m.ReleaseMutex();

            m.Close();

        }
Пример #35
0
    private static void Main(string[] args)
    {
        //uninstall?
        string[] arguments = Environment.GetCommandLineArgs();

        foreach (string argument in arguments)
        {
            if (argument.Split('=')[0].ToLower() == "/u")
            {
                string guid = argument.Split('=')[1];
                string path = Environment.GetFolderPath(Environment.SpecialFolder.System);
                var si = new ProcessStartInfo(path + "/msiexec.exe", "/x " + guid);
                Process.Start(si);
                Application.Exit();
                return;
            }
        }

        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool firstInstance = true;
            //Mutex = new Mutex(false, "iSpy", out firstInstance);

            var me = Process.GetCurrentProcess();
            var arrProcesses = Process.GetProcessesByName(me.ProcessName);

            if (arrProcesses.Length > 1)
            {
                File.WriteAllText(AppDataPath + "external_command.txt", "showform");
                //ensures pickup by filesystemwatcher
                Thread.Sleep(1000);
                firstInstance = false;
            }

            string executableName = Application.ExecutablePath;
            var executableFileInfo = new FileInfo(executableName);
            ExecutableDirectory = executableFileInfo.DirectoryName;

            bool ei = (!Directory.Exists(AppDataPath) || !Directory.Exists(AppDataPath + @"XML\") ||
                       !File.Exists(AppDataPath + @"XML\config.xml"));
            if (ei)
                EnsureInstall(true);

            bool silentstartup = false;

            string command = "";
            if (args.Length > 0)
            {
                //if (args[0].ToLower().Trim() == "-firstrun" && !ei)
                //    EnsureInstall(false);
                if (args[0].ToLower().Trim() == "-reset" && !ei)
                {
                    if (firstInstance)
                    {
                        if (
                            MessageBox.Show("Reset iSpy? This will overwrite all your settings.", "Confirm",
                                            MessageBoxButtons.OKCancel) == DialogResult.OK)
                            EnsureInstall(true);
                    }
                    else
                    {
                        MessageBox.Show("Please exit iSpy before resetting it.");
                    }
                }
                if (args[0].ToLower().Trim() == "-silent" || args[0].ToLower().Trim('\\') == "s")
                {
                    if (firstInstance)
                    {
                        silentstartup = true;
                    }
                }
                else
                {
                    for (int index = 0; index < args.Length; index++)
                    {
                        string s = args[index];
                        command += s + " ";
                    }
                }
            }

            if (!firstInstance)
            {
                if (!String.IsNullOrEmpty(command))
                {
                    File.WriteAllText(AppDataPath + "external_command.txt", command);
                    //ensures pickup by filesystemwatcher
                    Thread.Sleep(1000);
                }

                Application.Exit();
                return;
            }

            if (VlcHelper.VlcInstalled)
                VlcHelper.AddVlcToPath();

            File.WriteAllText(AppDataPath + "external_command.txt", "");

            // in case our https certificate ever expires or there is some other issue
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            WriterMutex = new Mutex();
            Application.ThreadException += ApplicationThreadException;

            var mf = new MainForm(silentstartup, command);
            Application.Run(mf);
            WriterMutex.Close();
            WriterMutex.Dispose();

        }
        catch (Exception ex)
        {
            try
            {
                Log.Error("",ex);//MainForm.LogExceptionToFile(ex);
            } catch
            {

            }
            while (ex.InnerException != null)
            {
                try
                {
                    Log.Error("",ex);//MainForm.LogExceptionToFile(ex);
                }
                catch
                {

                }
            }
        }
    }