private async void BackbendWindow_OnLoaded(object sender, RoutedEventArgs e) { await NavigateToMessage($"Starting {Constants.BackbendAppId}…"); var errorsAndInfos = new ErrorsAndInfos(); var dvinApp = await vContainer.Resolve <IDvinRepository>().LoadAsync(Constants.BackbendAppId, errorsAndInfos); if (errorsAndInfos.AnyErrors()) { await NavigateToMessage(errorsAndInfos.ErrorsToString()); return; } if (dvinApp == null) { await NavigateToMessage($"{Constants.BackbendAppId} app not found"); return; } Wait.Until(() => dvinApp.IsPortListenedTo(), TimeSpan.FromSeconds(5)); if (!dvinApp.IsPortListenedTo() && !await StartAppAndReturnSuccess(dvinApp)) { return; } Cursor = Cursors.Wait; Width = 660; Height = 660; vNavigated = false; HtmlOutput.Navigate("http://localhost:" + dvinApp.Port); }
/// <summary> /// Show all highscores on enable /// </summary> void OnEnable() { for (int i = 0; i < highScores.Length; i++) { HighScoreData hsd = GameManager.instance.gsData.hsds[i]; if (hsd != null && hsd.areaName != null) { highScores[i].Init(hsd); } else { highScores[i].Init(); } } for (int i = 0; i < achievements.Length; i++) { achievements[i].SetSprite(GameManager.instance.achievementSprites[i]); achievements[i].SetTooltip(i); achievements[i].SetColour(GameManager.instance.gsDataCurrent.achievementsUnlocked[i]); } monstersAmount.SetText(GameManager.instance.gsData.mostMonsters.ToString()); WAXAmount.SetText(GameManager.instance.gsData.mostWAX.ToString()); eventsAmount.SetText(GameManager.instance.gsData.mostEvents.ToString()); if (GameManager.instance.gsData.fastestTime == -1) { timeAmount.SetText("--"); } else { timeAmount.SetText(TimeSpan.FromSeconds(GameManager.instance.gsData.fastestTime).ToString(@"hh\:mm\:ss\.ff")); } }
private async Task NavigateToMessage(string message) { vNavigated = false; var markup = "<html><head></head><body><p>" + message + "</p></body></html>"; HtmlOutput.NavigateToString(markup); await Task.Run(() => Wait.Until(() => vNavigated, TimeSpan.FromSeconds(5))); }
public async Task <ResponseMessage> Handle(DefaultRequest request, CancellationToken cancellationToken) { await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); return(new ResponseMessage { Response = Rules.FirstOrDefault(x => x.IsValid(request.Request))?.toString() }); }
public static void AssertLoadAasx(Application application, Window mainWindow, string path) { if (!File.Exists(path)) { throw new InvalidOperationException($"The AASX file to be loaded does not exist: {path}"); } var fileMenuItem = mainWindow .FindFirstDescendant( cf => cf.ByClassName("MenuItem").And(cf.ByName("File"))) .AsMenuItem(); fileMenuItem.Click(); var openMenuItem = fileMenuItem .FindFirstChild(cf => cf.ByName("Open ..")) .AsMenuItem(); if (openMenuItem == null) { throw new AssertionException( "The open menu item is null. You need to thoroughly inspect what happened -- " + "this is quite strange."); } openMenuItem.Click(); Retry.WhileEmpty( () => mainWindow.ModalWindows, throwOnTimeout: true, timeout: TimeSpan.FromSeconds(10), timeoutMessage: "Could not find the modal windows of the main window"); Assert.AreEqual(1, mainWindow.ModalWindows.Length); var modal = mainWindow.ModalWindows[0]; var pathCombo = modal.FindFirstChild(cf => cf.ByAutomationId("1148")).AsComboBox(); pathCombo.EditableText = path; var openButton = modal.FindFirstChild(cf => cf.ByAutomationId("1")).AsButton(); openButton.Click(); Assert.IsEmpty(modal.ModalWindows, $"Unexpected modal window (probably an error) while opening the AASX: {path}"); Retry.WhileTrue(() => mainWindow.ModalWindows.Length > 0, throwOnTimeout: true, timeout: TimeSpan.FromSeconds(10)); if (application.HasExited) { throw new AssertionException( "The application unexpectedly exited. " + $"Check manually why the file could not be opened: {path}"); } }
/// <summary> /// Returns the estimated time it takes to enter dehydrated state /// </summary> public TimeSpan GetTimeTillDehydration() { // Convert the dehydration percentage to real numbers float beginDehydrationValue = ThirstSettings.BeginDehydrationPercentage / 100.0f * ThirstSettings.MaxValue; // Calculate the estimated time float increaseCount = Mathf.Ceil(beginDehydrationValue / ThirstSettings.IncreaseAmount); // How many times thirst will be increased float totalSeconds = ThirstSettings.IncreaseInterval * increaseCount; // The estimated time in seconds return(TimeSpan.FromSeconds(Mathf.Ceil(totalSeconds))); }
public BufferManager( IFileManager fileManager, ILogManager logManager, IBufferPoolStrategy poolStrategy, TimeSpan?maxWaitingTime = null, TimeSpan?tickWaitingTime = null) { _fileManager = fileManager; _logManager = logManager; _poolStrategy = poolStrategy; _maxWaitingTime = maxWaitingTime?.Ticks ?? TimeSpan.FromSeconds(5).Ticks; _tickWaitingTime = (int)(tickWaitingTime?.TotalMilliseconds ?? 200); }
public IEnumerator UpdateTimer() { while (timerGoing) { elapsedTime += Time.deltaTime; timeCounter = TimeSpan.FromSeconds(elapsedTime); timeDisplay.text = timeCounter.ToString(@"hh\:mm\:ss\.ff"); if (timeCounter.TotalDays >= 1) { timeDisplay.text = "Too Long"; } yield return(null); } }
/// <summary> /// Retry until the label element with number of errors is found and then check that there are no errors. /// /// If the search times out, an exception will be thrown. /// </summary> /// <param name="application">AASX Package Explorer application under test</param> /// <param name="mainWindow">Main window of <paramref name="application"/></param> /// <remarks>Both <paramref name="application"/> and <paramref name="mainWindow"/> should be obtained /// with <see cref="RunWithMainWindow"/></remarks> public static void AssertNoErrors(Application application, Window mainWindow) { const string automationId = "LabelNumberErrors"; var numberErrors = Retry.Find( () => (application.HasExited) ? null : mainWindow.FindFirstChild(cf => cf.ByAutomationId(automationId)), new RetrySettings { ThrowOnTimeout = true, Timeout = TimeSpan.FromSeconds(5) }); Assert.IsFalse(application.HasExited, "Application unexpectedly exited while searching for number of errors label"); Assert.IsNotNull(numberErrors, $"Element {automationId} could not be found."); Assert.AreEqual("Text", numberErrors.ClassName, $"Expected {automationId} to be a label"); Assert.AreEqual("No errors", numberErrors.AsLabel().Text, "Expected no errors on startup"); }
private async Task <bool> StartAppAndReturnSuccess(IDvinApp dvinApp) { var fileSystemService = new FileSystemService(); var errorsAndInfos = new ErrorsAndInfos(); if (!dvinApp.HasAppBeenPublishedAfterLatestSourceChanges(fileSystemService)) { dvinApp.Publish(fileSystemService, true, errorsAndInfos); if (errorsAndInfos.AnyErrors()) { await NavigateToMessage(string.Join("<br>", errorsAndInfos.Errors)); return(false); } } if (!dvinApp.HasAppBeenPublishedAfterLatestSourceChanges(fileSystemService)) { await NavigateToMessage($"{Constants.BackbendAppId} has not been published since the latest source code changes"); return(false); } vProcess = dvinApp.Start(fileSystemService, errorsAndInfos); Wait.Until(() => dvinApp.IsPortListenedTo(), TimeSpan.FromSeconds(30)); if (errorsAndInfos.AnyErrors()) { await NavigateToMessage(string.Join("<br>", errorsAndInfos.Errors)); return(false); } if (dvinApp.IsPortListenedTo()) { return(true); } await NavigateToMessage($"{Constants.BackbendAppId} started but not listening"); return(false); }
public IEnumerator UpdateTimerAroma() { while (timerGoing) { elapsedTime += Time.deltaTime; timeCounter = TimeSpan.FromSeconds(elapsedTime); timeDisplay.text = timeCounter.ToString(@"hh\:mm\:ss\.ff"); if (timeCounter.TotalMinutes >= 6 && swappedColours == false) { timeDisplay.color = warningColour; swappedColours = true; } else if (timeCounter.TotalMinutes >= 7) { StartCoroutine(EventManager.instance.DisplayGameOver(false)); } yield return(null); } }
private bool isWin; /// <value> True if this game ended in victory </value> /// <summary> /// Initializes all properties so the gameOverMenu can show the correct info /// </summary> /// <param name="isWin"> true if game was won (player reached last subArea), false otherwise </param> /// <param name="midPoints"> List of subArea indexes that were visited </param> /// <param name="subAreaProg"> Current subArea's progress</param> public void Init(bool isWin, List <int> midPoints, string areaName, int subAreaIndex, int subAreaProg, string timeString) { gameObject.SetActive(true); this.isWin = isWin; if (isWin == true) { gameOverTitle.SetKey("game_completed_title"); gameOverDes.SetKey("game_completed_des"); scoreTitle.SetKey("final_score_title"); } else { gameOverTitle.SetKey("game_over_title"); gameOverDes.SetKey("game_over_" + areaName + subAreaIndex); scoreTitle.SetKey("score_title"); } /* * First icon will be the start, last icon will be the end (so only midpoints need to be positioned and have their sprites changed). * Note that for now, the start and end icons are hardcoded via the scene (TODO: Change that) */ float midPointDist = (int)(frontFill.rectTransform.sizeDelta.x / (midPoints.Count + 1)); for (int i = 0; i < midPoints.Count; i++) { pbis[i + 1].SetPosition((int)midPointDist * (i + 1), 0); pbis[i + 1].SetSprite(Resources.Load <Sprite>("Sprites/Menu/" + GameManager.instance.areaName + "Icons/" + midPoints[i])); if (midPoints[i] != -1) // leave progressBarICons as ? if they were not reached { fillAmount += midPointDist / frontFill.rectTransform.sizeDelta.x; } } midPointBarSeg = 1f / (midPoints.Count + 1); fillAmount += (subAreaProg / 100f) * (1f / (midPoints.Count + 1)); monstersAmount.SetText(GameManager.instance.monstersKilled.ToString()); WAXAmount.SetText(GameManager.instance.WAXobtained.ToString()); eventsAmount.SetText(GameManager.instance.totalEvents.ToString()); timeAmount.SetText(timeString); scoreAmount.SetText(CalculateScore().ToString()); if (GameManager.instance.gsDataCurrent.achievementsUnlocked[(int)achievementConstants.ABSOLUTEMASTERY] == false && isWin == true && GameManager.instance.gsData.difficultyModifier == 1f) { string[] partyComp = PartyManager.instance.GetPartyCompositionSorted(); for (int i = 0; i < GameManager.instance.gsDataCurrent.partyCombos.GetLength(0); i++) { bool match = true; for (int j = 0; j < partyComp.Length; j++) { if (GameManager.instance.gsDataCurrent.partyCombos[i, j] != partyComp[j]) { match = false; break; } } if (match == true) { GameManager.instance.gsDataCurrent.partyCombos[i, 0] = null; // setting first entry in a combo to null means its been completed break; } } for (int i = 0; i < GameManager.instance.gsDataCurrent.partyCombos.GetLength(0); i++) { if (GameManager.instance.gsDataCurrent.partyCombos[i, 0] != null) { break; } else if (i == GameManager.instance.gsDataCurrent.partyCombos.GetLength(0) - 1) { GameManager.instance.gsDataCurrent.achievementsUnlocked[(int)achievementConstants.ABSOLUTEMASTERY] = true; EventManager.instance.SetAchievementNotification((int)achievementConstants.ABSOLUTEMASTERY, true); } } } if (GameManager.instance.gsDataCurrent.achievementsUnlocked[(int)achievementConstants.NOTIME] == false && isWin == true && GameManager.instance.gsData.difficultyModifier == 1f) { if (TimeSpan.FromSeconds(GameManager.instance.timeTaken).TotalSeconds < 720) { GameManager.instance.gsDataCurrent.achievementsUnlocked[(int)achievementConstants.NOTIME] = true; EventManager.instance.SetAchievementNotification((int)achievementConstants.NOTIME, true); } } GameManager.instance.AddHighScoreData(CalculateScore(), subAreaIndex); }
public void MessageIsLockedWithCorrectTimeout() { Patiently.VerifyExpectation(() => MessageLock.Received().TryAquireLock(Arg.Any <string>(), TimeSpan.FromSeconds(_expectedtimeout))); }
void Timer(float seconds, System.Action action) { Observable.Timer(TimeSpan.FromSeconds(seconds)) .Subscribe(_ => action()); }
/// <summary> /// Finds the main AASX Package Explorer window and executes the code dependent on it. /// </summary> /// <remarks>This method is necessary since splash screen confuses FlaUI and prevents us from /// easily determining the main window.</remarks> /// <param name="implementation">Code to be executed</param> /// <param name="run">Run options. If null, a new run with default values is used</param> public static void RunWithMainWindow(Implementation implementation, Run?run = null) { string environmentVariable = "AASX_PACKAGE_EXPLORER_RELEASE_DIR"; string releaseDir = System.Environment.GetEnvironmentVariable(environmentVariable); if (releaseDir == null) { throw new InvalidOperationException( $"Expected the environment variable to be set: {environmentVariable}; " + "otherwise we can not find binaries to be tested through functional tests."); } string pathToExe = Path.Combine(releaseDir, "AasxPackageExplorer.exe"); if (!File.Exists(pathToExe)) { throw new FileNotFoundException( "The executable of the AASX Package Explorer " + $"could not be found in the release directory: {pathToExe}; did you compile it properly before?"); } var resolvedRun = run ?? new Run(); // See https://stackoverflow.com/questions/5510343/escape-command-line-arguments-in-c-sharp string joinedArgs = string.Join( " ", resolvedRun.Args .Select(arg => Regex.Replace(arg, @"(\\*)" + "\"", @"$1$1\" + "\""))); var psi = new ProcessStartInfo { FileName = pathToExe, Arguments = joinedArgs, RedirectStandardError = true, WorkingDirectory = releaseDir, UseShellExecute = false }; bool gotStderr = false; var process = new Process { StartInfo = psi }; try { process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { gotStderr = true; TestContext.Error.WriteLine(e.Data); } }; process.Start(); process.BeginErrorReadLine(); } catch (Exception) { TestContext.Error.WriteLine( $"Failed to launch the process: FileName: {psi.FileName}, " + $"Arguments: {psi.Arguments}, Working directory: {psi.WorkingDirectory}"); throw; } var app = new Application(process, false); try { using var automation = new UIA3Automation(); var mainWindow = Retry.Find(() => // ReSharper disable once AccessToDisposedClosure app.GetAllTopLevelWindows(automation) .FirstOrDefault( (w) => w.AutomationId == "mainWindow"), new RetrySettings { ThrowOnTimeout = true, Timeout = TimeSpan.FromSeconds(5), TimeoutMessage = "Could not find the main window" }).AsWindow(); implementation(app, automation, mainWindow); } finally { if (!resolvedRun.DontKill) { app.Kill(); } } if (gotStderr) { throw new AssertionException( "Unexpected writes to standard error. Please see the test context for more detail."); } }