public ProgramApplicationContext()
        {
            this.notifyIcon = new System.Windows.Forms.NotifyIcon();
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

            this.notifyIcon.ContextMenuStrip = this.contextMenuStrip1;
            this.notifyIcon.Icon = Properties.Resources.notifyIcon;
            this.notifyIcon.Text = "Mass Effect 2 Performance Adjuster";
            this.notifyIcon.Visible = true;

            //
            // contextMenuStrip1
            //
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.exitToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.Size = new System.Drawing.Size(153, 48);
            //
            // exitToolStripMenuItem
            //
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.exitToolStripMenuItem.Text = "E&xit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);

            monitor = new ProcessMonitor(MASS_EFFECT_2);
            monitor.StartMonitor();
        }
示例#2
0
 public Home()
 {
     InitializeComponent();
     rumbleMonitor = new ProcessMonitor();
     rumbleMonitor.ProcessFound += RumbleMonitor_ProcessFound;
     rumbleMonitor.ProcessExited += RumbleMonitor_ProcessExited;
     directoryTb.TextWrapping = TextWrapping.NoWrap;
     directoryTb.Text = appSettings.Default.reslocation;
 }
 public KafkaTestCluster(string dockerHost, int brokerCount = 1, int portBase = 45678, int dockerPort = 2375)
 {
     this.dockerHost = dockerHost;
     this.portBase = portBase;
     this.dockerPort = dockerPort;
     DestroyContainers(brokerCount);
     this.zookeeperProcess = StartZookeeper();
     this.kafkaProcesses = StartKafkaBrokers(brokerCount);
 }
示例#4
0
        public override void Play()
        {
            OnStarting(this, new GameControllerEventArgs(this, 0));
            var startViaLauncher         = true;
            GameConfiguration gameConfig = null;

            if (library.SettingsViewModel.Settings.StartGamesWithoutLauncher)
            {
                try
                {
                    gameConfig = Twitch.GetGameConfiguration(Game.InstallDirectory);
                    if (Twitch.GetGameRequiresClient(gameConfig))
                    {
                        startViaLauncher = true;
                    }
                    else
                    {
                        startViaLauncher = false;
                    }
                }
                catch (Exception e) when(!Debugger.IsAttached)
                {
                    logger.Error(e, "Failed to get local game configuration.");
                }
            }

            if (startViaLauncher)
            {
                ProcessStarter.StartUrl($"twitch://fuel-launch/{Game.GameId}");
            }
            else
            {
                var exePath = Path.Combine(Game.InstallDirectory, gameConfig.Main.Command);
                var workDir = Game.InstallDirectory;
                if (!gameConfig.Main.WorkingSubdirOverride.IsNullOrEmpty())
                {
                    workDir = Path.Combine(Game.InstallDirectory, gameConfig.Main.WorkingSubdirOverride);
                }

                string args = null;
                if (gameConfig.Main.Args.HasNonEmptyItems())
                {
                    args = string.Join(" ", gameConfig.Main.Args);
                }

                ProcessStarter.StartProcess(exePath, args, workDir);
            }

            if (Directory.Exists(Game.InstallDirectory))
            {
                stopWatch              = Stopwatch.StartNew();
                procMon                = new ProcessMonitor();
                procMon.TreeStarted   += ProcMon_TreeStarted;
                procMon.TreeDestroyed += Monitor_TreeDestroyed;
                procMon.WatchDirectoryProcesses(Game.InstallDirectory, false);
            }
            else
            {
                OnStopped(this, new GameControllerEventArgs(this, 0));
            }
        }
示例#5
0
        public static bool ImportDeck(GameType gameType, string deck)
        {
            var    collection = GetCollection(gameType);
            var    lines      = deck.Split('\n').Select(line => line.Trim().Replace("'", "'").Replace('`', '\''));
            string deckName   = null;
            var    cardIds    = new List <string>();
            var    colors     = new HashSet <string>();

            foreach (string line in lines)
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }
                if (line.StartsWith("#"))
                {
                    deckName = line.Trim('#').Trim();
                    continue;
                }
                int firstSpace = line.IndexOf(' ');
                int paren1     = line.IndexOf('(');
                int hash       = line.IndexOf('#');
                int paren2     = line.IndexOf(')');
                if (firstSpace < 0 || (paren1 >= 0 && (hash < 0 || paren2 < 0)))
                {
                    throw new Exception($"Invalid line format: {line}");
                }

                int    count = int.Parse(line.Substring(0, firstSpace));
                string cardName = line.Substring(firstSpace, (paren1 < 0 ? line.Length : paren1) - firstSpace).Trim();
                int?   cardSet = null, cardNumber = null;
                if (hash > 0 && paren2 > 0)
                {
                    if (!int.TryParse(line.Substring(paren1 + 4, hash - paren1 - 5).Trim(), out int parsedCardSet))
                    {
                        throw new Exception($"Invalid line format: {line}");
                    }
                    cardSet = parsedCardSet;
                    if (!int.TryParse(line.Substring(hash + 1, paren2 - hash - 1).Trim(), out int parsedCardNumber))
                    {
                        throw new Exception($"Invalid line format: {line}");
                    }
                    cardNumber = parsedCardNumber;
                }

                int nameAttributeId      = gameType == GameType.Eternal ? (int)Eternal.Attribute.Name : (int)TheElderScrollsLegends.Attribute.Name;
                int isPremiumAttributeId = gameType == GameType.Eternal ? (int)Eternal.Attribute.IsPremium : (int)TheElderScrollsLegends.Attribute.IsPremium;
                int rarityAttributeId    = gameType == GameType.Eternal ? (int)Eternal.Attribute.Rarity : (int)TheElderScrollsLegends.Attribute.HydraRarity;
                int cardTypeAttributeId  = gameType == GameType.Eternal ? (int)Eternal.Attribute.CardType : (int)TheElderScrollsLegends.Attribute.HydraCardType;

                bool CheckCardNumber(IReadOnlyDictionary <int, object> attrs) => cardNumber != null && cardNumber == GetCardNumber(gameType, attrs) &&
                attrs.TryGetValue(gameType == GameType.Eternal ? (int)Eternal.Attribute.SetNumber : (int)TheElderScrollsLegends.Attribute.SetNumber, out var cardSetValue) &&
                cardSet == int.Parse(cardSetValue.ToString());

                bool CheckCardType(IReadOnlyDictionary <int, object> attrs) =>
                (attrs.TryGetValue(rarityAttributeId, out var rarityValue) && (string)rarityValue != "Special" ||
                 attrs.TryGetValue(cardTypeAttributeId, out var cardTypeValue) && (string)cardTypeValue == "Power") &&
                (gameType != GameType.TheElderScrollsLegends || !(bool)attrs[(int)TheElderScrollsLegends.Attribute.HydraHiddenFromDeckbuilder]);

                var    matchingNames      = allArchetypes[gameType].Where(a => CheckCardNumber(a.Value) || a.Value.ContainsKey(nameAttributeId) && a.Value[nameAttributeId].ToString() == cardName).ToList();
                string baseArchetypeId    = matchingNames.Where(a => CheckCardType(a.Value) && !(a.Value.ContainsKey(isPremiumAttributeId) && (bool)a.Value[isPremiumAttributeId])).Select(entry => entry.Key).FirstOrDefault();
                string premiumArchetypeId = matchingNames.Where(a => CheckCardType(a.Value) && a.Value.ContainsKey(isPremiumAttributeId) && (bool)a.Value[isPremiumAttributeId]).Select(entry => entry.Key).FirstOrDefault();
                if (baseArchetypeId == null)
                {
                    throw new Exception($"Unknown card name: {cardName}");
                }

                if (gameType == GameType.TheElderScrollsLegends && allArchetypes[gameType][baseArchetypeId].ContainsKey((int)TheElderScrollsLegends.Attribute.HydraColorList))
                {
                    foreach (string color in (JArray)allArchetypes[gameType][baseArchetypeId][(int)TheElderScrollsLegends.Attribute.HydraColorList])
                    {
                        colors.Add(color);
                    }
                }
                if (premiumArchetypeId != null && collection.ContainsKey(premiumArchetypeId))
                {
                    for (var i = 0; i < collection[premiumArchetypeId] && count > 0; i++, count--)
                    {
                        cardIds.Add(premiumArchetypeId);
                    }
                }
                if (collection.ContainsKey(baseArchetypeId))
                {
                    for (var i = 0; i < collection[baseArchetypeId] && count > 0; i++, count--)
                    {
                        cardIds.Add(baseArchetypeId);
                    }
                }
            }
            colors.Remove("Neutral");
            string cardsList = string.Join(",", cardIds);
            string message   = deckName != null ? $"{deckName}|{cardsList}" : cardsList;

            return(ProcessMonitor.SendCommand(gameType, CommandType.ImportDeck, message, 1000) == "Done");
        }
示例#6
0
 private void GameExitCallback(ProcessMonitor monitor)
 {
     monitor.Stop();
     Show();
 }
        public void Start(GameAction playAction, bool asyncExec = false)
        {
            if (playAction == null)
            {
                throw new ArgumentNullException("Cannot start game without play action.");
            }

            if (playAction.Type == GameActionType.Emulator)
            {
                throw new Exception("Cannot start emulator using this configuration.");
            }

            SourceGameAction = playAction;
            var gameClone = Game.GetClone();
            var action    = playAction.GetClone();

            if (gameClone.Roms.HasItems())
            {
                var romPath = gameClone.Roms[0].Path;
                SelectedRomPath = romPath;
                var newPath = CheckPath(romPath, "ROM", FileSystemItem.File);
                if (newPath != romPath)
                {
                    gameClone.Roms = new ObservableCollection <GameRom> {
                        new GameRom("LookupAlternativeFilePath", newPath)
                    };
                }
            }

            action            = action.ExpandVariables(gameClone);
            action.Path       = CheckPath(action.Path, nameof(action.Path), FileSystemItem.File);
            action.WorkingDir = CheckPath(action.WorkingDir, nameof(action.WorkingDir), FileSystemItem.Directory);

            if (playAction.Type == GameActionType.Script)
            {
                if (action.Script.IsNullOrWhiteSpace())
                {
                    throw new ArgumentNullException("Game script is not defined.");
                }

                RunStartScript(
                    $"{Game.Name} play script",
                    action.Script,
                    gameClone.ExpandVariables(gameClone.InstallDirectory, true),
                    new Dictionary <string, object>(),
                    asyncExec);
            }
            else
            {
                Process proc;
                if (action.Type == GameActionType.File)
                {
                    proc = ProcessStarter.StartProcess(action.Path, action.Arguments, action.WorkingDir);
                }
                else if (action.Type == GameActionType.URL)
                {
                    proc = ProcessStarter.StartUrl(action.Path);
                }
                else
                {
                    throw new NotSupportedException();
                }

                procMon                = new ProcessMonitor();
                procMon.TreeStarted   += ProcMon_TreeStarted;
                procMon.TreeDestroyed += Monitor_TreeDestroyed;

                if (action.TrackingMode == TrackingMode.Default)
                {
                    if (action.Type != GameActionType.URL)
                    {
                        stopWatch = Stopwatch.StartNew();

                        // Handle Windows store apps
                        var uwpMatch = Regex.Match(action.Arguments ?? string.Empty, @"shell:AppsFolder\\(.+)!.+");
                        if (action.Path == "explorer.exe" && uwpMatch.Success)
                        {
                            var scanDirectory = gameClone.InstallDirectory;

                            if (!gameClone.GameId.IsNullOrEmpty())
                            {
                                var prg = Programs.GetUWPApps().FirstOrDefault(a => a.AppId == gameClone.GameId);
                                if (prg != null)
                                {
                                    scanDirectory = prg.WorkDir;
                                }
                            }

                            // TODO switch to WatchUwpApp once we are building as 64bit app
                            //procMon.WatchUwpApp(uwpMatch.Groups[1].Value, false);
                            if (Directory.Exists(scanDirectory) && ProcessMonitor.IsWatchableByProcessNames(scanDirectory))
                            {
                                procMon.WatchDirectoryProcesses(scanDirectory, false, true);
                            }
                            else
                            {
                                InvokeOnStopped(new GameStoppedEventArgs());
                            }
                        }
                        else
                        {
                            if (proc != null)
                            {
                                InvokeOnStarted(new GameStartedEventArgs());
                                procMon.WatchProcessTree(proc);
                            }
                            else
                            {
                                InvokeOnStopped(new GameStoppedEventArgs());
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(gameClone.InstallDirectory) && Directory.Exists(gameClone.InstallDirectory))
                        {
                            InvokeOnStarted(new GameStartedEventArgs());
                            stopWatch = Stopwatch.StartNew();
                            procMon.WatchDirectoryProcesses(gameClone.InstallDirectory, false);
                        }
                        else
                        {
                            InvokeOnStopped(new GameStoppedEventArgs());
                        }
                    }
                }
                else if (action.TrackingMode == TrackingMode.Process)
                {
                    if (proc != null)
                    {
                        InvokeOnStarted(new GameStartedEventArgs());
                        stopWatch = Stopwatch.StartNew();
                        procMon.WatchProcessTree(proc);
                    }
                    else
                    {
                        InvokeOnStopped(new GameStoppedEventArgs());
                    }
                }
                else if (action.TrackingMode == TrackingMode.Directory)
                {
                    var watchDir = action.TrackingPath.IsNullOrEmpty() ? gameClone.InstallDirectory : action.TrackingPath;
                    if (!watchDir.IsNullOrEmpty() && Directory.Exists(watchDir))
                    {
                        stopWatch = Stopwatch.StartNew();
                        procMon.WatchDirectoryProcesses(watchDir, false);
                    }
                    else
                    {
                        InvokeOnStopped(new GameStoppedEventArgs());
                    }
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
        }
            /// <summary>
            /// Starts monitoring a process for a project.
            /// </summary>
            /// <param name="projectName">Name of the project.</param>
            /// <param name="taskId">The task id.</param>
            /// <param name="process">The process to monitor.</param>
            public static void MonitorProcessForProject(string projectName, string taskId, Process process)
            {
                var lockTaken = false;
                try
                {
                    Monitor.TryEnter(lockObject, TimeSpan.FromMinutes(1), ref lockTaken);
                    ProcessMonitor monitor;
                    if (!processMonitors.TryGetValue(projectName, out monitor))
                    {
                        monitor = new ProcessMonitor(projectName);
                        processMonitors.Add(projectName, monitor);
                        logger.Debug("Added monitor for '{0}'", projectName);
                    }

                    monitor.Processes.Add(taskId, process);
                    logger.Debug("Added process '{0}' to monitor for '{1}", taskId, projectName);
                }
                finally
                {
                    if (lockTaken)
                    {
                        Monitor.Exit(lockObject);
                    }
                }
            }
示例#9
0
        public MainWindow(
            //OptionsWindow optionsWindow,
            IOptionsMonitor <ConfigModelApp> configApp,
            ICollection <Card> allCards,
            MainWindowVM viewModel,
            ProcessMonitor processMonitor,
            LogFileZipper zipper,
            ServerApiCaller api,
            StartupShortcutManager startupManager,
            LogSplitter logSplitter,
            MtgaResourcesLocator resourcesLocator,
            FileMonitor fileMonitor,
            DraftHelper draftHelper,
            //LogProcessor logProcessor,
            ReaderMtgaOutputLog readerMtgaOutputLog,
            //CacheSingleton<ICollection<Card>> allCards,
            InGameTracker inMatchTracker,
            ExternalProviderTokenManager tokenManager,
            PasswordHasher passwordHasher,
            NotifyIconManager notifyIconManager,
            CacheSingleton <Dictionary <string, DraftRatings> > draftRatings
            )
        {
            this.configApp = configApp.CurrentValue;
            //optionsWindow.Init(this.configApp);
            //optionsWindow.Owner = Window.GetWindow(this);
            //this.optionsWindow = optionsWindow;

            this.reader         = readerMtgaOutputLog;
            this.processMonitor = processMonitor;
            processMonitor.OnProcessMonitorStatusChanged += OnProcessMonitorStatusChanged;
            this.zipper           = zipper;
            this.api              = api;
            this.startupManager   = startupManager;
            this.logSplitter      = logSplitter;
            this.resourcesLocator = resourcesLocator;
            this.fileMonitor      = fileMonitor;
            fileMonitor.OnFileSizeChangedNewText += OnFileSizeChangedNewText;
            this.draftHelper = draftHelper;
            //this.logProcessor = logProcessor;
            this.inGameTracker     = inMatchTracker;
            this.tokenManager      = tokenManager;
            this.passwordHasher    = passwordHasher;
            this.notifyIconManager = notifyIconManager;
            this.draftRatings      = draftRatings;
            this.resourcesLocator.LocateLogFilePath(this.configApp);
            this.resourcesLocator.LocateGameClientFilePath(this.configApp);

            fileMonitor.SetFilePath(this.configApp.LogFilePath);
            //viewModel.ValidateUserId(this.configApp.UserId);
            viewModel.Opacity = this.configApp.Opacity;
            vm          = viewModel;
            DataContext = vm;

            InitializeComponent();

            ucWelcome.Init(tokenManager);
            ucPlaying.Init(vm, this.configApp.WindowSettingsOpponentCards);

            //trayIcon = new System.Windows.Forms.NotifyIcon { Text = "MTGAHelper Tracker" };
            //trayIcon.Icon = new System.Drawing.Icon(Application.GetResourceStream(new Uri("pack://application:,,,/Assets/Images/wcC.ico")).Stream);
            //trayIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(TrayIcon_MouseClick);
            //trayIcon.ContextMenu = new System.Windows.Forms.ContextMenu(new System.Windows.Forms.MenuItem[]
            //{
            //    new System.Windows.Forms.MenuItem("Quit", new EventHandler(TrayIcon_Quit))
            //});

            statusBarTop.Init(this, vm /*, draftHelper, logProcessor, this.configApp.UserId,*/);
            ucReady.Init(this.configApp.GameFilePath);
            ucDraftHelper.Init(allCards, vm.DraftingVM);
            //ucPlaying.Init(vm);

            ucDraftHelper.SetPopupRatingsSource(this.configApp.ShowLimitedRatings, this.configApp.ShowLimitedRatingsSource);

            this.processMonitor.Start(new System.Threading.CancellationToken());
            this.fileMonitor.Start(new System.Threading.CancellationToken());

            var timer = new DispatcherTimer {
                Interval = TimeSpan.FromMilliseconds(200)
            };

            timer.Tick += (object sender, EventArgs e) =>
            {
                vm.SetCardsDraftFromBuffered();
                vm.SetCardsInMatchTrackingFromBuffered();
            };
            timer.Start();

            var timerTokenRefresh = new DispatcherTimer {
                Interval = TimeSpan.FromMinutes(9)
            };

            timerTokenRefresh.Tick += (object sender, EventArgs e) =>
            {
                RefreshAccessToken();
            };
            timerTokenRefresh.Start();
        }
示例#10
0
 /// <summary>
 /// config hangfirez
 /// </summary>
 /// <param name="app"></param>
 /// <param name="env"></param>
 /// <param name="loggerFactory"></param>
 public static void UseHangfireSettings(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
     try
     {
         if (IsEnabled)
         {
             // 设置语言
             var supportedCultures = new[]
             {
                 new CultureInfo("zh-CN"),
                 new CultureInfo("en-US")
             };
             app.UseRequestLocalization(new RequestLocalizationOptions
             {
                 DefaultRequestCulture = new RequestCulture("zh-CN"),
                 // Formatting numbers, dates, etc.
                 SupportedCultures = supportedCultures,
                 // UI strings that we have localized.
                 SupportedUICultures = supportedCultures
             });
             var process = Process.GetCurrentProcess();
             var prcss   = Process.GetProcesses(Environment.MachineName).OrderByDescending(p => p.PrivateMemorySize64).Take(5);
             List <ProcessMonitor> processMonitors = new List <ProcessMonitor>();
             processMonitors.Add(new ProcessMonitor(TimeSpan.FromSeconds(1), Process.GetCurrentProcess()));
             prcss.ToList().ForEach(s =>
             {
                 var moni = new ProcessMonitor(TimeSpan.FromSeconds(5), s);
                 processMonitors.Add(moni);
             });
             app.UseHangfireServer(new BackgroundJobServerOptions()
             {
                 ServerTimeout           = TimeSpan.FromMinutes(4),
                 SchedulePollingInterval = TimeSpan.FromSeconds(1),     // 秒级任务需要配置短点,一般任务可以配置默认时间,默认15秒
                 ShutdownTimeout         = TimeSpan.FromMinutes(30),    // 超时时间
                 Queues      = Queues,                                  // 队列
                 WorkerCount = Math.Max(Environment.ProcessorCount, 40) // 工作线程数,当前允许的最大线程,默认20
             },
                                   additionalProcesses: processMonitors.ToArray());
             app.UseHangfireDashboard("/job", new DashboardOptions
             {
                 AppPath = BackLink,                     // 返回时跳转的地址
                 DisplayStorageConnectionString = false, // 是否显示数据库连接信息
                 IsReadOnlyFunc = Context =>
                 {
                     var isreadonly = IsReadOnly;
                     return(isreadonly);
                 },
                 Authorization = new[]
                 {
                     new Id4AuthAuthorizationFilter()
                 }
                 //Authorization = new[] { new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
                 //{
                 //    RequireSsl = false,// 是否启用ssl验证,即https
                 //    SslRedirect = false,
                 //    LoginCaseSensitive = true,
                 //    Users = new []
                 //    {
                 //        new BasicAuthAuthorizationUser
                 //        {
                 //            Login =Account,// 登录账号
                 //            PasswordClear =  Password// 登录密码
                 //        }
                 //    }
                 //})
                 //}
             });
         }
     }
     catch (Exception ex)
     {
         loggerFactory.CreateLogger("HangfireStartUpError").Log(LogLevel.Error, ex.ToString());
     }
 }
示例#11
0
        public override void Play()
        {
            if (Game.PlayAction == null)
            {
                throw new Exception("Cannot start game without play action.");
            }

            var playAction = Game.PlayAction.ExpandVariables(Game);

            Dispose();
            OnStarting(this, new GameControllerEventArgs(this, 0));
            var emulators = database.Emulators.ToList();
            var profile   = GameActionActivator.GetGameActionEmulatorConfig(playAction, emulators)?.ExpandVariables(Game);
            var proc      = GameActionActivator.ActivateAction(playAction, profile);

            OnStarted(this, new GameControllerEventArgs(this, 0));

            if (playAction.Type != GameActionType.URL)
            {
                stopWatch              = Stopwatch.StartNew();
                procMon                = new ProcessMonitor();
                procMon.TreeDestroyed += Monitor_TreeDestroyed;

                // Handle Windows store apps
                if (playAction.Path == "explorer.exe" &&
                    playAction.Arguments.StartsWith("shell:") &&
                    !string.IsNullOrEmpty(Game.InstallDirectory))
                {
                    if (Directory.Exists(Game.InstallDirectory))
                    {
                        procMon.WatchDirectoryProcesses(Game.InstallDirectory, false);
                    }
                    else
                    {
                        OnStopped(this, new GameControllerEventArgs(this, 0));
                    }
                }
                else
                {
                    if (proc != null)
                    {
                        procMon.WatchProcessTree(proc);
                    }
                    else
                    {
                        OnStopped(this, new GameControllerEventArgs(this, 0));
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(Game.InstallDirectory) && Directory.Exists(Game.InstallDirectory))
                {
                    stopWatch              = Stopwatch.StartNew();
                    procMon                = new ProcessMonitor();
                    procMon.TreeDestroyed += Monitor_TreeDestroyed;
                    procMon.WatchDirectoryProcesses(Game.InstallDirectory, false);
                }
                else
                {
                    OnStopped(this, new GameControllerEventArgs(this, 0));
                }
            }
        }
        private void StopAndWaitForContainer(string containerName, ProcessMonitor process)
        {
            if (process.HasExited)
            {
                return;
            }

            var stopCommand = RunDocker("stop", containerName);
            stopCommand.WaitForExit();
            Console.WriteLine("stop {0} = {1},{2}", containerName, stopCommand.Stdout, stopCommand.Stderr);
            var exited = process.WaitForExit(2000);
            if (exited)
            {
                return;
            }

            RunDocker("kill", containerName);
            process.WaitForExit();
        }
        public void ShouldReturnAMonitorForTheProject()
        {
            ProcessMonitor monitor = project1.ProcessMonitor;

            Assert.AreEqual(ProcessMonitor.GetProcessMonitorByProject(project1.Name), monitor);
        }
示例#14
0
        private static void MonitorProcess(string filename, VisibleWindowHandler visibleWindowHandler, ProcessExitedHandler processExitHandler)
        {
            //Get the active window since the window activation will be lost by lauching the display properties
            IntPtr           activehWnd = IntPtr.Zero;
            ManualResetEvent waitEvent  = new ManualResetEvent(false);

            ProcessMonitor processMonitor     = new ProcessMonitor();
            Process        themeChangeProcess = new Process();

            themeChangeProcess.StartInfo.FileName = filename;

            try
            {
                //Initialize the wait event
                waitEvent.Reset();
                activehWnd = User32.GetForegroundWindow();

                //This field is set when the correct process is started and checked when any process exits
                int processId = 0;
                processMonitor.VisibleWindowFound += new VisibleWindowHandler(delegate(IntPtr topLevelhWnd, IntPtr hWnd, Process process, string title)
                {
                    if (process.ProcessName.ToLowerInvariant().Equals(ThemeProcessName))
                    {
                        processId = process.Id;
                        User32.SetForegroundWindow(topLevelhWnd);  //In case the dialog was opened previously
                        Thread.Sleep(2000);

                        if (visibleWindowHandler != null)
                        {
                            visibleWindowHandler(topLevelhWnd, hWnd, process, title);
                        }
                    }
                });

                processMonitor.ProcessExited += new ProcessExitedHandler(delegate(Process process)
                {
                    if (process.Id == processId)
                    {
                        if (processExitHandler != null)
                        {
                            processExitHandler(process);
                        }

                        Thread.Sleep(1000);     //For good measure
                        waitEvent.Set();
                    }
                });

                themeChangeProcess.Start();

                //Start monitoring processes
                processMonitor.AddProcess(ThemeProcessName);
                processMonitor.Start();

                waitEvent.WaitOne(60000, false);
            }
            finally
            {
                if (processMonitor != null)
                {
                    processMonitor.Stop();
                }

                //Restore the active window
                if (activehWnd != IntPtr.Zero)
                {
                    User32.SetForegroundWindow(activehWnd);
                }
            }
        }
示例#15
0
        public override void Play()
        {
            if (Game.PlayAction == null)
            {
                throw new Exception("Cannot start game without play action.");
            }

            var playAction = Game.PlayAction.ExpandVariables(Game);

            Dispose();
            OnStarting(this, new GameControllerEventArgs(this, 0));
            var proc = GameActionActivator.ActivateAction(playAction);

            if (playAction.Type != GameActionType.URL && playAction.Type != GameActionType.CMD)
            {
                stopWatch              = Stopwatch.StartNew();
                procMon                = new ProcessMonitor();
                procMon.TreeDestroyed += Monitor_TreeDestroyed;

                // Handle Windows store apps
                var uwpMatch = Regex.Match(playAction.Arguments ?? string.Empty, @"shell:AppsFolder\\(.+)!.+");
                if (playAction.Path == "explorer.exe" && uwpMatch.Success)
                {
                    var scanDirectory = Game.InstallDirectory;
                    procMon.TreeStarted += ProcMon_TreeStarted;

                    if (!Game.GameId.IsNullOrEmpty())
                    {
                        var prg = Programs.GetUWPApps().FirstOrDefault(a => a.AppId == Game.GameId);
                        if (prg != null)
                        {
                            scanDirectory = prg.WorkDir;
                        }
                    }

                    // TODO switch to WatchUwpApp once we are building as 64bit app
                    //procMon.WatchUwpApp(uwpMatch.Groups[1].Value, false);
                    if (Directory.Exists(scanDirectory) && ProcessMonitor.IsWatchableByProcessNames(scanDirectory))
                    {
                        procMon.WatchDirectoryProcesses(scanDirectory, false, true);
                    }
                    else
                    {
                        OnStopped(this, new GameControllerEventArgs(this, 0));
                    }
                }
                else
                {
                    if (proc != null)
                    {
                        OnStarted(this, new GameControllerEventArgs(this, 0));
                        procMon.WatchProcessTree(proc);
                    }
                    else
                    {
                        OnStopped(this, new GameControllerEventArgs(this, 0));
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(Game.InstallDirectory) && Directory.Exists(Game.InstallDirectory))
                {
                    OnStarted(this, new GameControllerEventArgs(this, 0));
                    stopWatch              = Stopwatch.StartNew();
                    procMon                = new ProcessMonitor();
                    procMon.TreeDestroyed += Monitor_TreeDestroyed;
                    procMon.WatchDirectoryProcesses(Game.InstallDirectory, false);
                }
                else
                {
                    OnStopped(this, new GameControllerEventArgs(this, 0));
                }
            }
        }
        public MainWindowVM(StatusBlinker statusBlinker, InMatchTrackerStateVM inMatchState, ConfigModel config, DraftingVM draftingVM,
                            IMapper mapper,
                            ICacheLoader <Dictionary <int, Set> > cacheSets,
                            ProcessMonitor processMonitor,
                            ServerApiCaller api,
                            StartupShortcutManager startupManager,
                            MtgaResourcesLocator resourcesLocator,
                            FileMonitor fileMonitor,
                            DraftCardsPicker draftHelper,
                            ReaderMtgaOutputLog readerMtgaOutputLog,
                            InGameTracker2 inMatchTracker,
                            ExternalProviderTokenManager tokenManager,
                            PasswordHasher passwordHasher,
                            CacheSingleton <Dictionary <string, DraftRatings> > draftRatings,
                            DraftHelperRunner draftHelperRunner,
                            //IEmailProvider emailProvider,
                            ICollection <Card> allCards,
                            CardThumbnailDownloader cardThumbnailDownloader,
                            ServerApiCaller serverApiCaller
                            )
        {
            // Set the status blinker reference
            StatusBlinker = statusBlinker;
            // Set the network status emission handler
            StatusBlinker.EmitStatus += status => { NetworkStatus = status; };

            Sets                               = cacheSets.LoadData().Values.ToArray();
            InMatchState                       = inMatchState;
            Config                             = config;
            DraftingVM                         = draftingVM;
            Mapper                             = mapper;
            ProcessMonitor                     = processMonitor;
            Api                                = api;
            StartupManager                     = startupManager;
            ResourcesLocator                   = resourcesLocator;
            FileMonitor                        = fileMonitor;
            DraftHelper                        = draftHelper;
            ReaderMtgaOutputLog                = readerMtgaOutputLog;
            InMatchTracker                     = inMatchTracker;
            InMatchState.GameEnded            += OnGameEnded;
            InMatchState.OpponentCardsUpdated += OnOpponentCardsUpdated;

            TokenManager      = tokenManager;
            PasswordHasher    = passwordHasher;
            DraftRatings      = draftRatings;
            DraftHelperRunner = draftHelperRunner;
            //this.emailProvider = emailProvider;
            AllCards = allCards;
            CardThumbnailDownloader = cardThumbnailDownloader;
            this.serverApiCaller    = serverApiCaller;

            // Set the library order from the config
            OrderLibraryCardsBy = config.OrderLibraryCardsBy == "Converted Mana Cost"
                ? CardsListOrder.ManaCost
                : CardsListOrder.DrawChance;

            // Create the opponent window view model
            OpponentWindowVM = new OpponentWindowVM("Opponent Cards", this, serverApiCaller);

            // Subscribe to property changes
            PropertyChanged += OnPropertyChanged;

            // Set the animated icon state
            AnimatedIcon = Config?.AnimatedIcon ?? false;

            // Set the initial window settings
            PositionTop   = WindowSettings?.Position.Y ?? 0;
            PositionLeft  = WindowSettings?.Position.X ?? 0;
            WindowOpacity = WindowSettings?.Opacity ?? 0.9;
            WindowTopmost = WindowSettings?.Topmost ?? true;

            // Set the initial window size
            WindowWidth = WindowSettings != null && WindowSettings.Size.X > double.Epsilon
                ? WindowSettings.Size.X
                : 340;
            WindowHeight = WindowSettings != null && WindowSettings.Size.Y > double.Epsilon
                ? WindowSettings.Size.Y
                : 500;
        }
 public static void MonitorProcessForProject(Process process, string projectName)
 {
     Monitor.TryEnter(lockObject, 60000);
     try
     {
         processMonitors[projectName] = new ProcessMonitor(process, projectName);
     }
     finally
     {
         Monitor.Exit(lockObject);
     }
 }
        public void ProcessMonitor_DefaultRefreshIs500()
        {
            var pm = new ProcessMonitor();

            Assert.AreEqual(500, pm.RefreshMilliseconds);
        }