public void User_input_should_return_valid_trackId_when_supplied() { var userInput = new List<string>{"5"}; _console.MockUserInput(userInput); var actual = new UserInteraction(_console, _validator).GetTrackId(); const int expected = 5; Assert.That(actual, Is.EqualTo(expected)); }
public void ShouldReturnNullForInvalidCommand() { var mockIoStream = new Mock <IUserIoStream>(); mockIoStream.Setup(m => m.ReadLine()).Returns("Invalid Input"); var sut = new UserInteraction(mockIoStream.Object); var result = sut.WaitForUserAction(); Assert.Null(result); }
private void DeleteStudent(StudentDto studentDto) { var response = _controller.DeleteStudent(studentDto); var lista = (List <string>)response; foreach (var bad in lista) { Console.WriteLine($"{bad}"); } UserInteraction.PressToBackToMenu(); }
public void User_input_should_return_valid_trackId_when_supplied() { var userInput = new List <string> { "5" }; _console.MockUserInput(userInput); var actual = new UserInteraction(_console, _validator).GetTrackId(); const int expected = 5; Assert.That(actual, Is.EqualTo(expected)); }
public void removeHistorico(string distrito, string atracao, string imagem) { Publicacao p = new Publicacao(distrito, atracao, imagem); if (!(UserInteraction.user.Historico.Where(x => string.Equals(x.Distrito, distrito) && string.Equals(x.Atracao, atracao) && string.Equals(x.Imagem, imagem)).ToList().Count > 0)) { return; } UserInteraction.user.Historico.RemoveAll(x => string.Equals(x.Distrito, distrito) && string.Equals(x.Atracao, atracao) && string.Equals(x.Imagem, imagem)); UserInteraction.user.Pontos -= Pontos; UserInteraction.updateUser(); }
public void ShouldIdentifyCommands(string input, Type expectedCommand, bool expectedCorrectArgs) { var mockIoStream = new Mock <IUserIoStream>(); mockIoStream.Setup(m => m.ReadLine()).Returns(input); var sut = new UserInteraction(mockIoStream.Object); var result = sut.WaitForUserAction(); Assert.IsType(expectedCommand, result); Assert.Equal(expectedCorrectArgs, result.HasCorrectArguments); }
async void EditarUtilizadorAsync() { if (Email != "" && UserInteraction.GetUtilizador(Email).Result != null) { await App.Current.MainPage.DisplayAlert("ERRO", "O email indicado já está a ser utilizado", "OK"); return; } if (Nome == "") { Nome = UserInteraction.user.Nome; } if (Email == "") { Email = UserInteraction.user.Email; } if (Cidade == "" || Cidade == null) { Cidade = UserInteraction.user.Cidade; } if (Distrito == "" || Distrito == null) { Distrito = UserInteraction.user.Distrito; } if (Password == "") { Password = UserInteraction.user.Password; } else { byte[] data = Encoding.ASCII.GetBytes(Password); data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data); Password = Encoding.ASCII.GetString(data); } if (Imagem == "") { Imagem = UserInteraction.user.Imagem; } Utilizador u = new Utilizador(Nome, Cidade, Distrito, Email, Password, Imagem, UserInteraction.user.Pontos, UserInteraction.user.Historico); if (!u.Equals(UserInteraction.user)) { u = await UserInteraction.EditaUtilizador(UserInteraction.user.Email, u); await App.Current.MainPage.Navigation.PopAsync(); } else { await App.Current.MainPage.DisplayAlert("Erro", "Não alterou nenhum elemento", "OK"); return; } }
public void ShouldInsertToCollection_WhenStringIsNotNull() { var consoleWriterMock = new Mock <IConsoleWriter>(); var consoleReaderMock = new Mock <IConsoleReader>(); var userInteraction = new UserInteraction(consoleWriterMock.Object, consoleReaderMock.Object); userInteraction.AddAction("action"); Assert.IsTrue(userInteraction.ActionLog.Contains("action")); }
public void GetStudentNote() { var studentNoteDto = GetStudentNotesDto(); var option = UserInteraction.MenuOptionTwo(); switch (option) { case "2": ShowStudentNotes(studentNoteDto); return; } }
public static double NumericValue(this UserInteraction userInteraction) { switch (userInteraction) { case UserInteraction.None: return(0.85); case UserInteraction.Required: return(0.62); default: throw new ArgumentOutOfRangeException(nameof(userInteraction), userInteraction, null); } }
private static PlayerMode SelectMode() { ShowModeMenu(); int choice = UserInteraction.GetNumberFromUser( "Select Mode: ", $"Option not found. Please try again.", 1, 2); if (choice == 1) { return(PlayerMode.SinglePlayer); } return(PlayerMode.TwoPlayers); }
public static string StringValue(this UserInteraction userInteraction) { switch (userInteraction) { case UserInteraction.None: return("N"); case UserInteraction.Required: return("R"); default: throw new ArgumentOutOfRangeException(nameof(userInteraction), userInteraction, null); } }
public void acrescentaHistorico(string distrito, string atracao, string imagem) { Publicacao p = new Publicacao(distrito, atracao, imagem); if (UserInteraction.user.Historico.Where(x => string.Equals(x.Distrito, distrito) && string.Equals(x.Atracao, atracao) && string.Equals(x.Imagem, imagem)).ToList().Count > 0) { return; } UserInteraction.user.Historico.Insert(0, p); UserInteraction.user.Pontos += Pontos; UserInteraction.updateUser(); }
private string BuildNormalizedVector(bool addEmptyValues) { var param = new List <string> { $"AV:{AttackVector.StringValue()}", $"AC:{AttackComplexity.StringValue()}", $"PR:{PrivilegesRequired.StringValue()}", $"UI:{UserInteraction.StringValue()}", $"S:{Scope.StringValue()}", $"C:{ConfidentialityImpact.StringValue()}", $"I:{IntegrityImpact.StringValue()}", $"A:{AvailabilityImpact.StringValue()}" }; void AddConditional(string key, string value) { if (!string.IsNullOrEmpty(value)) { param.Add($"{key}:{value}"); } else if (addEmptyValues) { param.Add($"{key}:X"); } } AddConditional("E", ExploitCodeMaturity?.StringValue()); AddConditional("RL", RemediationLevel?.StringValue()); AddConditional("RC", ReportConfidence?.StringValue()); AddConditional("CR", ConfidentialityRequirement?.StringValue()); AddConditional("IR", IntegrityRequirement?.StringValue()); AddConditional("AR", AvailabilityRequirement?.StringValue()); AddConditional("MAV", ModifiedAttackVector?.StringValue()); AddConditional("MAC", ModifiedAttackComplexity?.StringValue()); AddConditional("MPR", ModifiedPrivilegesRequired?.StringValue()); AddConditional("MUI", ModifiedUserInteraction?.StringValue()); AddConditional("MS", ModifiedScope?.StringValue()); AddConditional("MC", ModifiedConfidentialityImpact?.StringValue()); AddConditional("MI", ModifiedIntegrityImpact?.StringValue()); AddConditional("MA", ModifiedAvailabilityImpact?.StringValue()); StringBuilder sb = new StringBuilder(); sb.Append(VectorPrefix); foreach (var current in param) { sb.Append('/'); sb.Append(current); } return(sb.ToString()); }
public async Task WriteStringPickLocationAsync(string content, string name) { String token = await PickExternalStorageFile_NewFile(name); if (token == null || token.Equals("")) { await UserInteraction.ShowDialogAsync("ERROR", "Konnte den vorgang nicht abschließen"); Debug.WriteLine("maybe add return type to this at some point? (UWPStorageInterface)"); return; } await WriteToStorageFile(await GetStorageFileFromToken(token), content); }
public override void MainLoop() { string[] words = DataAccess.WordFinderWords(_wordsFile); UserInteraction.DisplayWordStats(words); for (int i = 0; words.Length > 1; i++) { string letters = UserInteraction.ReadLetters(i); words = words.Where(word => letters.Contains(word[i])).ToArray(); UserInteraction.DisplayWordStats(words); } }
void Awake() { gridBoxItems = boxItemsGO.GetComponent <GridLayoutGroup> (); user = User.getInstance; userInteraction = manager.GetComponent <UserInteraction> (); messageInteraction = manager.GetComponent <MessageInteraction> (); displayNumber = displayNumberGO.GetComponent <DisplayNumberUser> (); itemMeasured = 0; qntS = ""; }
public void ShouldParseCaseInsensitiveCurrencyArguments() { var mockIoStream = new Mock <IUserIoStream>(); mockIoStream.Setup(m => m.ReadLine()).Returns("Exchange euR/Usd 1"); var sut = new UserInteraction(mockIoStream.Object); var result = sut.WaitForUserAction(); var exchangeCommand = (ExchangeCommand)result; Assert.Equal("EUR", exchangeCommand.CurrencyFrom); Assert.Equal("USD", exchangeCommand.CurrencyTo); }
/// <summary> /// Closes this object. /// </summary> /// <returns>True if the object was closed, otherwise false.</returns> protected internal bool Close(UserInteraction interactive, CloseReason reason) { // easy case - bail if interaction is prohibited and we can't close without interacting if (interactive == UserInteraction.NotAllowed && !CanClose()) { return(false); } // either we can close without interacting, or interaction is allowed, so let's try and close // begin closing - the operation may yet be cancelled _state = DesktopObjectState.Closing; ClosingEventArgs args = new ClosingEventArgs(reason, interactive); OnClosing(args); if (args.Cancel || !PrepareClose(reason)) { _state = DesktopObjectState.Open; return(false); } _view.CloseRequested -= OnViewCloseRequested; _view.VisibleChanged -= OnViewVisibleChanged; _view.ActiveChanged -= OnViewActiveChanged; // notify inactive this.Active = false; try { // close the view _view.Dispose(); } catch (Exception e) { Platform.Log(LogLevel.Error, e); } _view = null; // close was successful _state = DesktopObjectState.Closed; OnClosed(new ClosedEventArgs(reason)); // dispose of this object after firing the Closed event // (reason being that handlers of the Closed event may expect this object to be intact) (this as IDisposable).Dispose(); return(true); }
static void Main(string[] args) { var userInteraction = new UserInteraction(); var calculatorApp = new CalculatorApp(new DefaultExchangeService(), userInteraction); userInteraction.DisplayMessage(CalculatorApp.HELP_MESSAGE); userInteraction.DisplayMessage("Other Commands: HELP, EXIT"); Command lastExecutedCommand = null; while (!(lastExecutedCommand is ExitCommand)) { lastExecutedCommand = calculatorApp.ProcessCommand(); } }
public void Call_ReadLine() { var consoleWriterMock = new Mock <IConsoleWriter>(); var consoleReaderMock = new Mock <IConsoleReader>(); consoleReaderMock.Setup(r => r.ReadLine()); var userInteraction = new UserInteraction(consoleWriterMock.Object, consoleReaderMock.Object); var askUser = userInteraction.AskUser("same", true); consoleReaderMock.Verify(r => r.ReadLine(), Times.Once); }
public void ReturnMessage_WhenIsOnTheSameTheSameLine() { var consoleWriterMock = new Mock <IConsoleWriter>(); consoleWriterMock.Setup(w => w.Write("same")); var consoleReaderMock = new Mock <IConsoleReader>(); var userInteraction = new UserInteraction(consoleWriterMock.Object, consoleReaderMock.Object); var askUser = userInteraction.AskUser("same", true); consoleWriterMock.Verify(w => w.Write("same")); }
private IMoveResult SaveGame(IMoveResult moveResult) { Console.WriteLine("Under what name save the game?"); string file = UserInteraction.ReadNotEmptyStringFromUser(); var saveRepository = SaveRepository.GetDefaultRepository(); bool isEnded = moveResult.IsCheckMate(TeamColor.Black) || moveResult.IsCheckMate(TeamColor.White); var state = new ChessGameState(moveResult, isEnded, new [] { _player }, _computer.MyTeamColor, PlayerMode.SinglePlayer, _difficulty); saveRepository.Save(file + ".bin", state); Console.WriteLine("Game saved."); return(new StoppedMoveResult()); }
private IMoveResult SaveGame(IMoveResult moveResult, int currentPlayer) { Console.WriteLine("Under what name save the game?"); string file = UserInteraction.ReadNotEmptyStringFromUser(); var saveRepository = SaveRepository.GetDefaultRepository(); bool isEnded = moveResult.IsCheckMate(TeamColor.Black) || moveResult.IsCheckMate(TeamColor.White); var state = new ChessGameState(moveResult, isEnded, _players, _players[currentPlayer].TeamColor, PlayerMode.TwoPlayers, 0); saveRepository.Save(file + ".bin", state); Console.WriteLine("Game saved."); return(new StoppedMoveResult()); }
async void EntrarUtilizador() { bool b = await UserInteraction.AutenticaUtilizador(Email, Password); if (b) { App.Current.MainPage = new NavigationPage(new HomePage()); } //if (b) App.Current.MainPage = new DistritosInfView("Braga"); else { await App.Current.MainPage.DisplayAlert("Login", "As credenciais fornecidas não estão corretas", "OK"); } }
static async Task <StorageFolder> GetCustomFolder(String type) { String Token = await ReadFromLocalFolder("Storage." + type + ".token"); if (Token == null || Token.Equals("")) { await UserInteraction.ShowDialogAsync("INFORMATION", "You will now be prompted to chose a Folder in which to save the Comic." + "This App will create a new Folder within the Folder you selected, called \"" + type + "\", which will be used to store the images" + "(in order not to confuse them with your files). The App will remember the location you have picked and will use this location until you change it in the Settings."); Token = await PickExternalStorageFolder(); await WriteToLocalFolder("Storage." + type + ".token", Token); } return(await GetStorageFolderFromToken(Token)); }
public void RegisterNewStudent() { var studentDto = GetStudentDTO(); var option = UserInteraction.MenuOption(); switch (option) { case "2": SaveStudent(studentDto); return; case "3": DeleteStudent(studentDto); return; } }
public int Run() { UserInteraction.Message($"SCALUS is starting up..."); using (GenericHost = CreateHost()) { var serverTask = GenericHost.RunAsync(CancellationTokenSource.Token).ContinueWith(x => { Log.Debug($"Web server stopped: {x.Status}"); return(x); }); OsServices.OpenDefault($"http://localhost:{WebPort}/index.html"); UserInteraction.Message($"SCALUS is running at http://localhost:{WebPort}. Close the browser window to quit."); GenericHost.WaitForShutdown(); } return(0); }
// Use this for initialization void Start() { userInteraction = GameObject.Find("GameController").GetComponent <UserInteraction>(); //cubes = GameObject.FindGameObjectsWithTag("node"); // no longer needed after adding [System.Serializable] to do it manually //spinSpeed = 70.0f; // default spin speed is 70.0 //spinCurrentCubeOn = true; // cubesOrigZ = 3.0f; // cubesOrigY = 1.1f; userInteraction.maxIndex = cubes.Length - 1; // the max index is set to the number of cubes (items) in the array for switching between them // (needed to add -1 because C# Array.Length returns the number of items in the array, but the indexing begins at 0 so the max index OVERFLOWS) cubesOrigState = new GameObject[userInteraction.maxIndex]; cubesOrigState = cubes; }
static void Main(string[] args) { while (true) { // Read in the item catalog for all items and associated promotions in the given file "Catalog.txt" PriceCatalog.ReadPriceCatalog(); // Start the interaction with the user UserInteraction.Start(); // Print the recipt, calculate cost, clear data Checkout.Finish(); // Repeat } }
public void RegisterNewSubject() { var subjectDto = GetSubjectDto(); var option = UserInteraction.MenuOption(); switch (option) { case "2": SaveSubject(subjectDto); return; case "3": DeleteSubject(subjectDto); return; } }
/// <summary> /// This is a bad method that breaks all sorts of rules /// </summary> /// <param name="ui"></param> public void DisplayMaze(UserInteraction ui) { for (int y = 0; y < dungeon.rows; y++) { StringBuilder line = new StringBuilder(); for (int x = 0; x < dungeon.cols; x++) { if (y == row && x == col) { line.Append('P'); } else if (dungeon.RoomVisited(y, x)) { line.Append('O'); } else { line.Append('x'); } } ui.PushStringLine(line.ToString()); } }
public Line(Line prototype): base(prototype) { mAllowMove = prototype.AllowMove; mLineJoin = prototype.LineJoin; mDrawSelected = prototype.DrawSelected; mInteraction = prototype.Interaction; //Set up new origins Start = new Origin(prototype.FirstPoint); End = new Origin(prototype.LastPoint); Start.Marker = prototype.Start.Marker; End.Marker = prototype.End.Marker; mPoints = (ArrayList) prototype.Points.Clone(); //Copy ports Ports = new Elements(typeof(Port),"Port"); foreach (Port port in prototype.Ports.Values) { Port clone = (Port) port.Clone(); Ports.Add(port.Key,clone); clone.SuspendValidation(); clone.Location = port.Location; clone.ResumeValidation(); } if (prototype.Animation != null) mAnimation = (Animation) prototype.Animation.Clone(); DrawPath(); }
public AnalysisService(UserInteraction interaction) { _interaction = interaction; }
public Player CreateCharacter(string Class, UserInteraction ui) { Class = Class.ToLower(); Player newChar; switch(Class) { case "barbarian": newChar = new Barbarian(new int[] { 15, 15, 15, 10, 9, 10 }); newChar.SetArmor(Armors.chainShirt); newChar.SetMainHand(new MasterworkWeapon(Weapons.battleaxe)); newChar.SetName("Bob"); break; case "bard": newChar = new Bard(new int[] { 15, 10, 15, 10, 9, 15 }); newChar.SetArmor(Armors.leatherArmor); newChar.SetMainHand(new MasterworkWeapon(Weapons.rapier)); newChar.SetName("Bill"); break; case "cleric": newChar = new Cleric(new int[] { 15, 10, 15, 15, 9, 10 }); newChar.SetArmor(Armors.breastplate); newChar.SetMainHand(new MasterworkWeapon(Weapons.heavyMace)); newChar.SetOffHand(Armors.heavyWoodenShield); newChar.SetName("Chad"); break; case "druid": newChar = new Druid(new int[] { 15, 10, 15, 15, 9, 10 }); newChar.SetArmor(Armors.hideArmor); newChar.SetMainHand(new MasterworkWeapon(Weapons.club)); newChar.SetOffHand(Armors.heavyWoodenShield); newChar.SetName("Dave"); break; case "fighter": newChar = new Fighter(new int[] { 15, 15, 15, 10, 9, 10 }); newChar.SetArmor(Armors.breastplate); newChar.SetMainHand(new MasterworkWeapon(Weapons.longsword)); newChar.SetOffHand(Armors.heavyWoodenShield); newChar.SetName("Frank"); break; case "monk": newChar = new Monk(new int[] { 15, 10, 15, 10, 15, 9 }); newChar.SetMainHand(new MasterworkWeapon(Weapons.quarterstaff)); newChar.SetName("Molly"); break; case "paladin": newChar = new Paladin(new int[] { 15, 10, 15, 9, 15, 10 }); newChar.SetArmor(Armors.breastplate); newChar.SetMainHand(new MasterworkWeapon(Weapons.longsword)); newChar.SetOffHand(Armors.heavyWoodenShield); newChar.SetName("Phil"); break; case "ranger": newChar = new Ranger(new int[] { 15, 10, 15, 9, 15, 10 }); newChar.SetArmor(Armors.leatherArmor); newChar.SetMainHand(new MasterworkWeapon(Weapons.longbow)); newChar.SetName("Randy"); break; case "rogue": newChar = new Rogue(new int[] { 15, 10, 15, 15, 9, 10 }); newChar.SetArmor(Armors.leatherArmor); newChar.SetMainHand(new MasterworkWeapon(Weapons.rapier)); newChar.SetName("Rudy"); break; case "sorcerer": newChar = new Sorcerer(new int[] { 10, 15, 15, 10, 9, 15 }); newChar.SetMainHand(new MasterworkWeapon(Weapons.lightCrossbow)); newChar.SetName("Steve"); break; case "wizard": newChar = new Wizard(new int[] { 10, 15, 15, 15, 9, 10 }); newChar.SetMainHand(new MasterworkWeapon(Weapons.lightCrossbow)); newChar.SetName("Willis"); break; default: newChar = new Barbarian(new int[] { 10, 10, 10, 10, 10, 10 }); newChar.SetArmor(Armors.chainShirt); newChar.SetMainHand(new MasterworkWeapon(Weapons.battleaxe)); newChar.SetName("Default"); break; } newChar.SetUI(ui); newChar.AddItems(new Item[] { Consumables.minorHealthPotion, Consumables.minorHealthPotion, Consumables.minorManaPotion, Consumables.minorManaPotion, Consumables.minorHarmingPotion, Consumables.minorHarmingPotion }); return newChar; }
public Port(Port prototype): base(prototype) { SuspendEvents = true; Label = null; StencilItem = null; mAlignment = prototype.Alignment; mOffset = prototype.Offset; mAllowMove = prototype.AllowMove; mAllowRotate = prototype.AllowRotate; mDirection = prototype.Direction; mInteraction = prototype.Interaction; Label = null; mPortStyle = prototype.Style; Cursor = prototype.Cursor; mPercent = prototype.Percent; mOrientation = prototype.Orientation; //Needed for action mvoe mParent = prototype.Parent; SuspendEvents = false; }
/// <summary> /// Closes this object. /// </summary> /// <returns>True if the object was closed, otherwise false.</returns> protected internal bool Close(UserInteraction interactive, CloseReason reason) { // easy case - bail if interaction is prohibited and we can't close without interacting if (interactive == UserInteraction.NotAllowed && !CanClose()) return false; // either we can close without interacting, or interaction is allowed, so let's try and close // begin closing - the operation may yet be cancelled _state = DesktopObjectState.Closing; ClosingEventArgs args = new ClosingEventArgs(reason, interactive); OnClosing(args); if (args.Cancel || !PrepareClose(reason)) { _state = DesktopObjectState.Open; return false; } _view.CloseRequested -= OnViewCloseRequested; _view.VisibleChanged -= OnViewVisibleChanged; _view.ActiveChanged -= OnViewActiveChanged; // notify inactive this.Active = false; try { // close the view _view.Dispose(); } catch (Exception e) { Platform.Log(LogLevel.Error, e); } _view = null; // close was successful _state = DesktopObjectState.Closed; OnClosed(new ClosedEventArgs(reason)); // dispose of this object after firing the Closed event // (reason being that handlers of the Closed event may expect this object to be intact) (this as IDisposable).Dispose(); return true; }
/// <summary> /// Tries to close the object, interacting with the user only if specified. /// </summary> /// <param name="interactive">A value specifying whether user interaction is allowed.</param> /// <returns>True if the object is closed, otherwise false.</returns> public bool Close(UserInteraction interactive) { AssertState(new DesktopObjectState[] {DesktopObjectState.Open}); return Close(interactive, CloseReason.Program); }
public AllAnalysis(UserInteraction interaction) { _interaction = interaction; }
public SwatchOutputType(UserInteraction interaction) { _interaction = interaction; _iterations = _interaction.GetNumberOfIterations(); }
public SingleAnalysis(UserInteraction interaction) { _interaction = interaction; }
public Shape(Shape prototype): base(prototype) { mAllowMove = prototype.AllowMove; mAllowScale = prototype.AllowScale; mAllowRotate = prototype.AllowRotate; mDrawSelected = prototype.DrawSelected; mDirection = prototype.Direction; mInteraction = prototype.Interaction; mMaximumSize = prototype.MaximumSize; mMinimumSize = prototype.MinimumSize; mKeepAspect = prototype.KeepAspect; //Copy ports Ports = new Elements(typeof(Port),"Port"); foreach (Port port in prototype.Ports.Values) { Port clone = (Port) port.Clone(); Ports.Add(port.Key,clone); clone.SuspendValidation(); clone.Location = port.Location; clone.ResumeValidation(); } if (prototype.Animation != null) mAnimation = (Animation) prototype.Animation.Clone(); }