示例#1
0
        public static bool SingleInstanceCheck()
        {
            bool isFirstOne = true;

            if (bUseSingleInstance)
            {
                bool isOnlyInstance = false;
                Mutex = new Mutex(true, AppName, out isOnlyInstance);
                if (!isOnlyInstance)
                {
                    isFirstOne = false;
                    string filesToOpen = " ";
                    var    args        = Environment.GetCommandLineArgs();
                    if (args != null && args.Length > 1)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 1; i < args.Length; i++)
                        {
                            sb.AppendLine(args[i]);
                        }
                        filesToOpen = sb.ToString();
                    }

                    var manager = new NamedPipeManager(AppPipeName);

                    // send the message
                    manager.Write(filesToOpen);

                    ExitThisApp();
                }
            }
            return(isFirstOne);
        }
示例#2
0
        public void FirstTimeSetup(Mutex m, Service_JsonParser jsp,
                                   NamedPipeManager npm, List <DatabaseContext_Profile> profiles, ProfilesManager profileManager)
        {
            if (GetCollection <Game>("games").Count() > 0)
            {
                GetCollection <Game>("games").Delete(x => true);
            }

            if (GetCollection <GameApplication>("game_apps").Count() > 0)
            {
                GetCollection <GameApplication>("game_apps").Delete(x => true);
            }
            foreach (var item in profiles)
            {
                item.Dispose();
            }
            profiles.Clear();

            foreach (var item in GetCollection <UserProfile>("profiles").FindAll())
            {
                profileManager.DeleteProfile(item.ProfileId);
            }

            AvailableGamesWindow chooseGames = new AvailableGamesWindow(m, this, jsp, npm, profiles, profileManager);

            chooseGames.Show();
        }
        public void NamedPipeManager()
        {
            string result = string.Empty;

            var manager = new NamedPipeManager("MarkdownMonster_Tests");

            manager.ReceiveString += (s) =>
            {
                Console.WriteLine("Received results: " + s);
                result += s + "\r\n";
            };

            manager.StartServer();

            Thread.Sleep(200);  // allow thread to spin up

            var manager2 = new NamedPipeManager("MarkdownMonster_Tests");

            manager2.Write("Hello World");
            manager2.Write("Goodbye World");

            manager.StopServer();

            Thread.Sleep(200);

            Assert.IsFalse(string.IsNullOrEmpty(result), "Result shouldn't be null");
        }
示例#4
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try {
                // set language
                Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");

                string root = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
                Environment.CurrentDirectory = root;

                pipe = new NamedPipeManager(Name);
                if (!pipe.SingleServer())
                {
                    if (e.Args.Length == 1)
                    {
                        pipe.Write(e.Args[0]);
                    }
                    Environment.Exit(0);
                }

                pipe.ReceiveString += pipe_ReceiveString;
                pipe.StartServer();

                var win = new UserWindow();
                win.Closed += win_Closed;
                win.Show();
            }
            catch (Exception _e) {
                MessageBox.Show(_e.Message);
                Application.Current.Shutdown();
                pipe.StopServer();
            }
        }
示例#5
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (ApplicationSettings.AppSetting.Default.SingleInstanceApplication)
            {
                Mutex = new Mutex(true, CURRENT_NAMED_PIPE, out bool Is);
                if (!Is)
                {
                    NamedPipeManager.Write(CURRENT_NAMED_PIPE, e.Args);
                    Shutdown(0);
                    return;
                }

                NamedPipeManager = new NamedPipeManager(CURRENT_NAMED_PIPE);
                NamedPipeManager.ReceiveString += NamedPipeManager_ReceiveString;
                NamedPipeManager.Start();
            }

            MainWindowVM = new MainWindowVM();
            if (e.Args.Length > 0)
            {
                MainWindowVM.OpenFile(e.Args[0]);
            }

            MainWindow = new MainWindow()
            {
                DataContext = MainWindowVM
            };
            MainWindow.Show();
        }
示例#6
0
 public static void StartServer()
 {
     if (bUseSingleInstance)
     {
         NamedPipeManager PipeManager = new NamedPipeManager(AppPipeName);
         PipeManager.StartServer();
         PipeManager.ReceiveString += HandleNamedPipe_OpenRequest;
     }
 }
 public AvailableGamesWindow(Mutex m, DatabaseContext_Main db, Service_JsonParser jsp,
                             NamedPipeManager npm, List <DatabaseContext_Profile> profiles, ProfilesManager profMng)
     : this(db, ConfigurationPurpose.FirstTime)
 {
     _mutex            = m;
     _jsonParser       = jsp;
     _namedPipeManager = npm;
     _dbProfiles       = profiles;
     _profilesManager  = profMng;
 }
示例#8
0
        public App()
        {
            this.mutex            = SingleInstanceManager.TryAcquireMutex();
            this.namedPipeManager = new NamedPipeManager(Assembly.GetExecutingAssembly().FullName);

            var autoSuspendHelper = new AutoSuspendHelper(this);

            GC.KeepAlive(autoSuspendHelper);

            BlobCache.ApplicationName = Assembly.GetExecutingAssembly().GetName().Name;
        }
示例#9
0
        public App()
        {
            this.mutex            = SingleInstanceManager.TryAcquireMutex();
            this.namedPipeManager = new NamedPipeManager(Assembly.GetExecutingAssembly()?.FullName ?? String.Empty);

            PlatformRegistrationManager.SetRegistrationNamespaces(RegistrationNamespace.Wpf);

            var autoSuspendHelper = new AutoSuspendHelper(this);

            GC.KeepAlive(autoSuspendHelper);

            BlobCache.ApplicationName = Assembly.GetExecutingAssembly().GetName()?.Name ?? String.Empty;
        }
        public void OpenFilesInRunningApplication()
        {
            var manager = new NamedPipeManager("MarkdownMonster");


            StringBuilder sb = new StringBuilder();

            sb.AppendLine("c:\\temp\\test.txt");
            sb.AppendLine("c:\\temp\\davidrosenhaft.prg");

            Console.WriteLine(sb);

            Assert.IsTrue(manager.Write(sb.ToString()));
        }
		private TangerineSingleInstanceKeeper(string[] args)
		{
			bool isOnlyInstance;
			mutex = new Mutex(true, MutexName, out isOnlyInstance);
			if (!isOnlyInstance) {
				if (args.Length > 0) {
					var stream = new MemoryStream();
					TangerineYuzu.Instance.Value.WriteObject(string.Empty, stream, args, Serialization.Format.JSON);
					var serializedArgs = Encoding.UTF8.GetString(stream.ToArray());
					var manager = new NamedPipeManager(PipeServerName);
					manager.Write(serializedArgs);
				}

				System.Environment.Exit(0);
			}

			pipeManager = new NamedPipeManager(PipeServerName);
			pipeManager.StartServer();
			pipeManager.ReceiveString += OnAnotherInstanceArgsRecieved;
		}
示例#12
0
        public void CustomInitialize(frmChummerMain mainControl)
        {
            Log.Info("CustomInitialize for Plugin ChummerHub.Client entered.");
            MainForm = mainControl;
            if (String.IsNullOrEmpty(ChummerHub.Client.Properties.Settings.Default.TempDownloadPath))
            {
                ChummerHub.Client.Properties.Settings.Default.TempDownloadPath = Path.GetTempPath();
            }

            //check global mutex
            BlnHasDuplicate = false;
            try
            {
                BlnHasDuplicate = !Program.GlobalChummerMutex.WaitOne(0, false);
            }
            catch (AbandonedMutexException ex)
            {
                Log.Error(ex);
                Utils.BreakIfDebug();
                BlnHasDuplicate = true;
            }
            if (PipeManager == null)
            {
                PipeManager = new NamedPipeManager("Chummer");
                Log.Info("blnHasDuplicate = " + BlnHasDuplicate.ToString());
                // If there is more than 1 instance running, do not let the application start a receiving server.
                if (BlnHasDuplicate)
                {
                    Log.Info("More than one instance, not starting NamedPipe-Server...");
                    throw new ApplicationException("More than one instance is running.");
                }
                else
                {
                    Log.Info("Only one instance, starting NamedPipe-Server...");
                    PipeManager.StartServer();
                    PipeManager.ReceiveString += HandleNamedPipe_OpenRequest;
                }
            }
        }
        public MainWindow(Mutex mutex, DatabaseContext_Main db, Service_JsonParser jsonParser,
                          NamedPipeManager npm, List <DatabaseContext_Profile> profiles, ProfilesManager profMngr, Nexus.NexusUrl modUri = null)
        {
            InitializeComponent();

            _mutex            = mutex;
            _jsonParser       = jsonParser;
            _db               = db;
            _dbProfiles       = profiles;
            _currProfileDb    = _dbProfiles.FirstOrDefault(x => _currGame.Id == x.GameId);
            _namedPipeManager = npm;
            _profilesManager  = profMngr;
            _mulConverter     = new MultiplicationMathConverter();
            _addConverter     = new AdditionMathConverter();

            _namedPipeManager.ChangeMessageReceivedHandler(HandlePipeMessage);

            mainGrid.Dispatcher.BeginInvoke((Action)(() =>
            {
                InitGamePicker();
                _accountHandler = new AccountHandler(WhenLogsIn);
                _accountHandler.Init();
                _modManager = new ModManager(_currProfileDb, ModList_View, Downloads_View, _accountHandler);
                profilePicker.SelectionChanged += profilePicker_SelectionChanged;

                if (modUri != null)
                {
                    _modManager.CreateMod(_currGame, modUri).GetAwaiter();
                }
                _db.UpdateCurrentGame(_currGame, SetGame);
            }));

            if (!_namedPipeManager.IsRunning)
            {
                Task.Run(async() => await _namedPipeManager.Listen_NamedPipe(Dispatcher));
            }
        }
示例#14
0
        public MainWindow(
            MainWindowVM viewModel,
            IDialogService dialogService,
            IRuntimeDataService runtimeDataService)
        {
            _dialogService      = dialogService;
            _runtimeDataService = runtimeDataService;

            InitializeComponent();

            WindowChrome windowChrome = new WindowChrome()
            {
                CaptionHeight         = 55,
                CornerRadius          = new CornerRadius(0),
                GlassFrameThickness   = new Thickness(0),
                NonClientFrameEdges   = NonClientFrameEdges.None,
                ResizeBorderThickness = new Thickness(6),
                UseAeroCaptionButtons = false
            };

            WindowChrome.SetWindowChrome(this, windowChrome);

            _namedPipeManager            = new NamedPipeManager("TwitchLeecher");
            _namedPipeManager.OnMessage += OnPipeMessage;
            _namedPipeManager.StartServer();

            // Hold reference to FontAwesome library
            ImageAwesome.CreateImageSource(FontAwesomeIcon.Times, Brushes.Black);

            SizeChanged += (s, e) =>
            {
                if (WindowState == WindowState.Normal)
                {
                    WidthNormal  = Width;
                    HeightNormal = Height;
                }
            };

            LocationChanged += (s, e) =>
            {
                if (WindowState == WindowState.Normal)
                {
                    TopNormal  = Top;
                    LeftNormal = Left;
                }
            };

            Loaded += (s, e) =>
            {
                HwndSource.FromHwnd(new WindowInteropHelper(this).Handle).AddHook(new HwndSourceHook(WindowProc));

                DataContext = viewModel;

                if (viewModel != null)
                {
                    viewModel.Loaded();
                }

                LoadWindowState();
            };

            Activated += (s, e) =>
            {
                if (viewModel != null && !_shown)
                {
                    _shown = true;
                    viewModel.Shown();
                }
            };

            Closed += (s, e) =>
            {
                SaveWindowState();

                _namedPipeManager.StopServer();
            };
        }
        void App_Startup(object sender, StartupEventArgs e)
        {
            NexusUrl modArg        = null;
            bool     isMainProcess = false;

            _dbProfiles = new List <DatabaseContext_Profile>();

            _mutex = new Mutex(false, "Global\\" + appGuid);
            try
            {
                isMainProcess = _mutex.WaitOne(0, false);
            }
            catch (Exception)
            {
                isMainProcess = false;
            }


            // Application is running
            // Process command line args
            bool startMinimized = false;

            for (int i = 0; i < e.Args.Length; ++i)
            {
                if (e.Args[i] == "/StartMinimized")
                {
                    startMinimized = true;
                }
                else
                {
                    try
                    {
                        modArg = new NexusUrl(new Uri(e.Args[i]));
                    }
                    catch (Exception)
                    {
                        Current.Shutdown();
                    }
                }
            }
            if (!isMainProcess)
            {
                _mutex.ReleaseMutex();
                _mutex.Close();
                if (modArg != null)
                {
                    ProcessStartInfo info = new ProcessStartInfo(Defined.NAMED_PIPE_CLIENT_EXECUTABLE)
                    {
                        Arguments      = modArg.ToString(),
                        CreateNoWindow = true
                    };
                    Process.Start(info);
                    Current.Shutdown();
                }
            }
            else
            {
                _namedPipeManager   = new NamedPipeManager();
                _jsonParser         = new Service_JsonParser();
                RequiredDirectories = new string[] { Defined.Settings.ApplicationDataPath };
                foreach (var item in RequiredDirectories)
                {
                    if (!Directory.Exists(item))
                    {
                        Directory.CreateDirectory(item);
                    }
                }

                _db = new DatabaseContext_Main();// Strong Type Class
                foreach (var game in _db.GetCollection <Game>("games").FindAll())
                {
                    if (!Directory.Exists(game.ModsDirectory))
                    {
                        Directory.CreateDirectory(game.ModsDirectory);
                    }
                    if (!Directory.Exists(game.DownloadsDirectory))
                    {
                        Directory.CreateDirectory(game.DownloadsDirectory);
                    }
                    if (!Directory.Exists(game.ProfilesDirectory))
                    {
                        Directory.CreateDirectory(game.ProfilesDirectory);
                    }
                }
                _profilesManager = new ProfilesManager(_db);

                foreach (var item in _db.GetCollection <Classes.DatabaseClasses.UserProfile>("profiles").FindAll())
                {
                    _dbProfiles.Add(new DatabaseContext_Profile(item.ProfileDirectory, item.GameId));
                }

                if (Defined.Settings.State == StatesOfConfiguration.FirstTime || _db.GetCollection <Game>("games").FindAll().Count() < 1)
                {
                    _db.FirstTimeSetup(_mutex, _jsonParser, _namedPipeManager, _dbProfiles, _profilesManager);
                    foreach (var item in _dbProfiles)
                    {
                        item.FirstTimeSetup();
                    }
                    return;
                }
                else if (Defined.Settings.State == StatesOfConfiguration.Ready)
                {
                    // Create main application window, starting minimized if specified
                    MainWindow mainWindow = new MainWindow(_mutex, _db, _jsonParser,
                                                           _namedPipeManager, _dbProfiles, _profilesManager, modArg);
                    if (startMinimized)
                    {
                        mainWindow.WindowState = WindowState.Minimized;
                    }
                    mainWindow.Show();
                    mainWindow.InitBindings();
                }
            }
        }