public async Task ExecuteAsync_MultiPartRouteWithBodyFromFile_VerifyResponse() { string filePath = "someFilePath.txt"; string fileContents = "This is a test response from a PUT: \"Test Put Body From File\""; ArrangeInputs(commandText: $"PUT --file " + filePath, baseAddress: _baseAddress, path: _testPath, urlsWithResponse: _urlsWithResponse, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences, readBodyFromFile: true, fileContents: fileContents); fileSystem.AddFile(filePath, "Test Put Body From File"); PutCommand putCommand = new PutCommand(fileSystem, preferences); await putCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); List <string> result = shellState.Output; Assert.Equal(2, result.Count); Assert.Contains("HTTP/1.1 200 OK", result); Assert.Contains(fileContents, result); }
public CustomerController(PostCommand <Customer> command, GetAllCommand <Customer> getCommand, PutCommand <Customer> putCommand) { this.postCommand = command; this.putCommand = putCommand; this.getAllCommand = getCommand; }
protected void GetInfo(object obj, EventArgs args) { if (_playername == "") { _playername = playerText.Text; _player.AddIdentifier(_playername); playerText.Text = ""; playerText.Hide(); descText.Show(); TextArea.Buffer.Text = "Tell me something about yourself"; } else if (!IsEmpty(descText.Text) && !IsEmpty(_playername)) { _desc = descText.Text; _player.Description = _desc; descText.Text = ""; descText.Hide(); commandText.Show(); TextArea.Buffer.Text = "Enter commands or type quit to exit"; } else { string command = commandText.Text.ToLower(); char delimiterChar = ' '; string[] cmd = command.Split(delimiterChar); LookCommand look = new LookCommand(new string[] { "look" }); MoveCommand move = new MoveCommand(new string[] { "move", "go", "head", "leave" }); PutCommand put = new PutCommand(new string[] { "put", "drop" }); TakeCommand take = new TakeCommand(new string[] { "pickup", "take" }); CommandProcessor cp = new CommandProcessor(new string[] { }, new Command[] { look, move, put, take }); TextArea.Buffer.Text = cp.Execute(_player, cmd); } }
public void Handle_WithPutCommand_CallsPutAPI() { const string testFilePath = "TestFilePath"; const string testSrcFile = "TestSrcFile"; // Arrange var mockClientProtocol = new Mock <IRestClientProtocol>(); var locatedBlock = new LocatedBlock() { Locations = new DataNodeId[] { new DataNodeId { IPAddress = "http://localhost" } } }; mockClientProtocol.Setup(x => x.AddBlock(It.IsAny <string>())).Returns(locatedBlock); var stubDataTransferProtocol = new Mock <IRestDataTransferProtocol>(); var sut = new PutCommandHandler(mockClientProtocol.Object, stubDataTransferProtocol.Object); var stubPutCommand = new PutCommand() { FilePath = testFilePath, SrcFile = testSrcFile }; // Act sut.Handle(stubPutCommand); // Assert mockClientProtocol.Verify(x => x.Create(testSrcFile, testFilePath)); }
public async Task CreateBatchAndUpdateTimeouts(RavenBatch batch) { var insertCommand = new PutCommand { Id = $"{RavenConstants.BatchPrefix}/{batch.Number}", Type = "PUT", ChangeVector = null, Document = batch }; var timeoutUpdateCommands = batch.TimeoutIds.Select(timeoutId => new PatchCommand { Id = timeoutId, Type = "PATCH", ChangeVector = null, Patch = new Patch() { Script = $"this.OwningTimeoutManager = '{RavenConstants.MigrationOngoingPrefix}' + this.OwningTimeoutManager;", Values = new { } } }).ToList(); var commands = new List <object> { insertCommand }; commands.AddRange(timeoutUpdateCommands); await PostToBulkDocs(commands); }
public AccountController(PostCommand <Account> command, GetAllCommand <Account> getAllCommand, GetStringCommand <Account> getStringCommand, DeleteCommand deleteCommand, PutCommand <Account> putCommand) { this.postCommand = command; this.getAllCommand = getAllCommand; this.getStringCommand = getStringCommand; this.deleteCommand = deleteCommand; this.putCommand = putCommand; }
public async Task ExecuteAsync_WithNoBasePath_VerifyError() { ArrangeInputs(commandText: "PUT", baseAddress: null, path: null, urlsWithResponse: null, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences); string expectedErrorMessage = Strings.Error_NoBasePath.SetColor(httpState.ErrorColor); PutCommand putCommand = new PutCommand(fileSystem, preferences); await putCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.Equal(expectedErrorMessage, shellState.ErrorMessage); }
public async Task <IActionResult> Update(int id, [FromBody] PutCommand model) { var produto = await _prodRepository.GetAsync(id); if (produto == null) { ModelState.AddModelError("Id", "Produto não encontrado"); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } produto.Atualizar(model.Nome, model.PrecoUnitario, model.CategoriaId, model.QtdeEmEstoque); _prodRepository.Update(produto); await _uow.CommitAsync(); return(NoContent()); }
public async Task ExecuteAsync_MultiPartRouteWithInlineContent_VerifyResponse() { ArrangeInputs(commandText: "PUT --content \"Test Put Body\"", baseAddress: _baseAddress, path: _testPath, urlsWithResponse: _urlsWithResponse, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences); PutCommand putCommand = new PutCommand(fileSystem, preferences); await putCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); string expectedResponse = "This is a test response from a PUT: \"Test Put Body\""; List <string> result = shellState.Output; Assert.Equal(2, result.Count); Assert.Contains("HTTP/1.1 200 OK", result); Assert.Contains(expectedResponse, result); }
public async Task <IActionResult> Update(int id, [FromBody] PutCommand model) { var categoria = await _catRepository.GetAsync(id); if (categoria == null) { ModelState.AddModelError("Id", "Categoria não encontrada"); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } categoria.Atualizar(model.Nome); _catRepository.Update(categoria); await _uow.CommitAsync(); return(NoContent()); }
internal static Command Parse(string input) { var splittedCmd = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (splittedCmd.Length == 0) { return(new EmptyCommand()); } var cmdArgs = new string[splittedCmd.Length - 1]; Array.Copy(splittedCmd, 1, cmdArgs, 0, cmdArgs.Length); Command cmd = null; switch (splittedCmd[0].ToLower()) { case "dir": cmd = new DirCommand(); break; case "post": cmd = new PostCommand(); break; case "put": cmd = new PutCommand(); break; case "get": cmd = new GetCommand(); break; case "delete": cmd = new DeleteCommand(); break; case "connect": break; case "disconnect": break; case "capturestatson": break; case "capturestatsoff": break; case "help": cmd = new HelpCommand(); break; case "exit": cmd = new ExitCommand(); break; case "ping": cmd = new PingCommand(); break; default: cmd = new UnknownCommand(splittedCmd[0]); break; } cmd.Parse(cmdArgs); return(cmd); }
static void Main(string[] args) { Console.WriteLine("Welcome to Swin-Adventure!"); Console.WriteLine(); Console.WriteLine("This is the first version of the game that is created by me. Enjoy the adventure in the game world!"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("What is your name?"); string name = Console.ReadLine(); Console.WriteLine("How can you describe yourself(for example, a mighty programmer)?"); string description = Console.ReadLine(); Console.WriteLine("Let's begin your adventure today!"); Player newPlayer = new Player(name, description); bool StayingOpen = true; // adding items and bag Item Itm1 = new Item(new string[] { "golden", "ring" }, "ring", "This is a golden ring for you"); Item Itm2 = new Item(new string[] { "yellow", "small", "box" }, "box", "This is a small yellow box for you"); Item Itm3 = new Item(new string[] { "purple", "ball" }, "ball", "That is a small and purple ball"); Item Itm4 = new Item(new string[] { "green", "table" }, "table", "This is a dining table. Be careful with it!"); Item Itm5 = new Item(new string[] { "orange" }, "orange", "This is an orange for you."); Bag Bag1 = new Bag(new string[] { "red", "bag" }, "bag", "This is a large and red bag"); // adding locations Location Loc1 = new Location("coffee house", " where you could go to coffee house each day"); Location Loc2 = new Location("palace", "where the duke worked and lived"); Location Loc3 = new Location("old fort", "where we could see the port"); Location Loc4 = new Location("small house", "where an old family lives"); Location Loc5 = new Location("museum", "which is quite niche"); Location Loc6 = new Location("stable", "where people raise their finest horses"); // adding paths Path path1 = new Path(new string[] { "north" }, "a trail", " which is where people go every day", Loc1, Loc2); Path path2 = new Path(new string[] { "west" }, "main road", " where traders move and go", Loc1, Loc6); Path path3 = new Path(new string[] { "east" }, "river bank", " where the weather is quite sunny.", Loc1, Loc3); Path path4 = new Path(new string[] { "south" }, "small grove", " near a tiny lake", Loc1, Loc4); Path path5 = new Path(new string[] { "northwest" }, "a creek", " where a plan was laid out", Loc1, Loc5); Path path6 = new Path(new string[] { "southwest" }, "big street", "near the center of the city", Loc2, Loc3); Path path7 = new Path(new string[] { "northeast" }, "a corridor", "near a forest", Loc2, Loc4); Path path8 = new Path(new string[] { "southeast" }, "a bridge", "through the great river", Loc2, Loc5); Path path9 = new Path(new string[] { "gate" }, "new gate", "leads to stable", Loc2, Loc6); //add path to locations. Loc1.AddPath(path1); Loc1.AddPath(path2); Loc1.AddPath(path3); Loc1.AddPath(path4); Loc1.AddPath(path5); Loc2.AddPath(path6); Loc2.AddPath(path7); Loc2.AddPath(path8); Loc2.AddPath(path9); Loc1.Inventory.Put(Itm4); newPlayer.Location = Loc1; newPlayer.Inventory.Put(Itm1); newPlayer.Inventory.Put(Itm2); newPlayer.Inventory.Put(Itm5); newPlayer.Inventory.Put(Bag1); Bag1.Inventory.Put(Itm3); //handling Command Processor. CommandProcessor newCommand = new CommandProcessor(); TakeCommand Take = new TakeCommand(); newCommand.AddCommand(Take); LookCommand Look = new LookCommand(); newCommand.AddCommand(Look); MoveCommand Move = new MoveCommand(); newCommand.AddCommand(Move); PutCommand Put = new PutCommand(); newCommand.AddCommand(Put); while (StayingOpen) { Console.WriteLine("Please enter command:"); string _input = Console.ReadLine(); string[] Command = _input.Split();// get help from Charlotte Pierce in HelpDesk. if (Command[0] == "quit") { Console.WriteLine("Bye."); Thread.Sleep(2000); StayingOpen = false; } else { Console.WriteLine(newCommand.Execute(newPlayer, Command)); } } }
public WebDAVListener(HttpListener server, string path) { this.HttpServer = server; OptionsCommand optionsCommand = new OptionsCommand(); optionsCommand.Start(this, path); commands.Add(optionsCommand); PropFindCommand propfindCommand = new PropFindCommand(); propfindCommand.Start(this, path); commands.Add(propfindCommand); LockCommand lockCommand = new LockCommand(); lockCommand.Start(this, path); commands.Add(lockCommand); UnlockCommand unlockCommand = new UnlockCommand(); unlockCommand.Start(this, path); commands.Add(unlockCommand); MkcolCommand mkcolCommand = new MkcolCommand(); mkcolCommand.Start(this, path); commands.Add(mkcolCommand); MoveCommand moveCommand = new MoveCommand(); moveCommand.Start(this, path); commands.Add(moveCommand); GetCommand getCommand = new GetCommand(); getCommand.Start(this, path); commands.Add(getCommand); PutCommand putCommand = new PutCommand(); putCommand.Start(this, path); commands.Add(putCommand); DeleteCommand deleteCommand = new DeleteCommand(); deleteCommand.Start(this, path); commands.Add(deleteCommand); CopyCommand copyCommand = new CopyCommand(); copyCommand.Start(this, path); commands.Add(copyCommand); PropPatchCommand proppatchCommand = new PropPatchCommand(); proppatchCommand.Start(this, path); commands.Add(proppatchCommand); }
public void GenerateCodeForInstruction(CodeLine line) { if (InstructionHelper.IsMoveInstruction(line.instruction)) { var command = new MoveCommand(InstructionHelper.GetInstructionDirection(line.instruction), currentCodeLineNumber + 1); commandToCodeLineMapping.Add(command, line); allCommands.Add(command); } if (InstructionHelper.IsPutInstruction(line.instruction)) { var command = new PutCommand(currentCodeLineNumber + 1); commandToCodeLineMapping.Add(command, line); allCommands.Add(command); } if (InstructionHelper.IsPickInstruction(line.instruction)) { var command = new PickCommand(currentCodeLineNumber + 1); commandToCodeLineMapping.Add(command, line); allCommands.Add(command); } if (InstructionHelper.IsJumpInstruction(line.instruction)) { ICommand command; if (InstructionHelper.IsJumpInstructionLabel(line.instruction)) { command = new JumpCommand(currentCodeLineNumber + 1); allCommands.Add(command); } else { //this is being set in code later - otherwise forward jumps will not work - see RepairJumps for reference. command = new JumpCommand(currentCodeLineNumber + 1); allCommands.Add(command); } commandToCodeLineMapping.Add(command, line); } if (InstructionHelper.IsIfInstruction(line.instruction)) { int trueLineNumber = currentCodeLineNumber + 1; int elseLineNumber = currentCodeLineNumber + line.TotalChildrenCount + 1; var command = new IfCommand(trueLineNumber, elseLineNumber, GetConditions(line), GetLogicalOperators(line)); allCommands.Add(command); commandToCodeLineMapping.Add(command, line); currentCodeLineNumber++; foreach (var child in line.children) { GenerateCodeForInstruction(child); } command.NextCommandId = currentCodeLineNumber; currentCodeLineNumber--; //this may seem wrong but actually it is not } if (InstructionHelper.IsWhileInstruction(line.instruction)) { int trueLineNumber = currentCodeLineNumber + 1; int falseLineNumber = currentCodeLineNumber + line.TotalChildrenCount + 1; var command = new WhileCommand(trueLineNumber, falseLineNumber, GetConditions(line), GetLogicalOperators(line)); allCommands.Add(command); commandToCodeLineMapping.Add(command, line); currentCodeLineNumber++; foreach (var child in line.children) { GenerateCodeForInstruction(child); } var loopJumpCommand = new JumpCommand(trueLineNumber - 1); commandToCodeLineMapping.Add(loopJumpCommand, null); command.NextCommandId = currentCodeLineNumber + 1; allCommands.Add(loopJumpCommand); } if (InstructionHelper.IsRepeatInstruction(line.instruction)) { int trueLineNumber = currentCodeLineNumber + 1; int falseLineNumber = currentCodeLineNumber + line.TotalChildrenCount + 1; var command = new RepeatCommand(trueLineNumber, falseLineNumber, InstructionHelper.GetRepeatTimes(line.instruction)); allCommands.Add(command); commandToCodeLineMapping.Add(command, line); currentCodeLineNumber++; foreach (var child in line.children) { GenerateCodeForInstruction(child); } var loopJumpCommand = new JumpCommand(trueLineNumber - 1); commandToCodeLineMapping.Add(loopJumpCommand, null); command.NextCommandId = currentCodeLineNumber; allCommands.Add(loopJumpCommand); } currentCodeLineNumber++; }
public void Execute(Message msg, IMessageSenderService sender, IBot bot) { if (Main.Api.Users.IsBanned(msg)) { return; } if (!Main.Api.Users.CheckUser(msg)) { var kb2 = new KeyboardBuilder(bot); kb2.AddButton("➕ Зарегистрироваться", "start"); sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build()); return; } var user = Main.Api.Users.GetUser(msg); var command = UsersCommandHelper.GetHelper().Get(user.Id); //TODO: написать с использованием команд-менеджера. var text = string.Empty; if (command == "") { if (msg.ChatId > 2000000000) { return; } sender.Text("❌ Неизвестная команда", msg.ChatId); return; } else if (command == "putrawmoney") { long count; try { count = long.Parse(msg.Text); text = PutCommand.PutMoney(user, count); } catch { text = "❌ Вы ввели неверное число. Попробуйте ещё раз."; } } else if (command == "withdrawmoney") { long count; try { count = long.Parse(msg.Text); text = WithdrawCommand.Withdraw(user, count); } catch { text = "❌ Вы ввели неверное число. Попробуйте ещё раз."; } } else if (command == "exchangedonate") { long count; try { count = long.Parse(msg.Text); text = ExchangeDonateCommand.Exchange(msg, count); }catch { text = "❌ Вы ввели неверное число. Попробуйте ещё раз."; } } else if (command == "creategang") { text = CreateCommand.Create(msg.Text, user.Id); } else if (command == "renamegang") { text = RenameCommand.Rename(user, msg.Text); } else if (command == "opencontribution") { try { var array = msg.Text.Split(" "); var count = long.Parse(array[0]); var days = long.Parse(array[1]); text = OpenContributionCommand.Open(user.Id, count, days); } catch { text = "❌ Вы указали неверные числа"; } } else if (command == "racefriend") { try { var array = msg.Text.Split(" "); var id = long.Parse(array[0]); text = RaceFriendCommand.RunFriendBattle(user.Id, id, sender, bot, msg); }catch { text = "Вы указали неверный id"; } } else if (command == "addfriend") { try { text = AddFriendCommand.AddFriend(user, msg.Text.ToLong(), sender); } catch { text = "❌ Вы указали неверный Id."; } } else if (command == "removefriend") { try { text = RemoveFriendCommand.RemoveFriend(user, msg.Text.ToLong()); } catch { text = "❌ Вы указали невеный Id."; } } else if (command == "sellcar") { try { var array = msg.Text.Split(" "); var idUser = long.Parse(array[0]); var price = long.Parse(array[1]); text = SellCarCommand.Sell(user, idUser, sender, price); }catch { text = "❌ Произошла ошибка."; } } else if (command == "buycarnumber") { try { var region = long.Parse(msg.Text); if (region < 1 || region > 999) { text = "❌ Регион находится за пределом допустимого значения."; } else { text = BuyCarNumberCommand.BuyNumber(user, region); } } catch { text = "❌ Произошла ошибка."; } } else if (command == "sellnumber") { try { var array = msg.Text.Split(" "); var idUser = long.Parse(array[0]); var price = long.Parse(array[1]); text = SellNumberCommand.Sell(user, idUser, sender, price); }catch { text = "❌ Произошла ошибка."; } } else if (command == "buychips") { try { var count = msg.Text.ToLong(); text = BuyChipsCommand.BuyChips(user, count); } catch { text = "❌ Произошла ошибка."; } } else if (command == "exchangechips") { try { var count = msg.Text.ToLong(); text = ExchangeChipsCommand.ExchangeChips(user, count); } catch { text = "❌ Произошла ошибка."; } } else if (command == "vipDonateBuy") { try { var count = msg.Text.ToLong(); text = ExpDonateCommand.BuyExp(count, user); } catch { text = "❌ Произошла ошибка."; } } else if (command == "carDonate") { try { text = CarDonateCommand.CreateCar(msg.Text, user); } catch { text = "❌ Произошла ошибка."; } } else if (command == "expDonate") { try { var array = msg.Text.Split(" "); var power = long.Parse(array[0]); var weight = long.Parse(array[1]); text = AcceptCustomCarCommand.SetParams(power, weight, user, sender); }catch { text = "❌ Произошла ошибка."; } } else if (command == "customNumber") { try { var number = msg.Text.ToLong(); text = BuyOtherItemCommand.CustomNumber(number.ToString(), user); } catch { text = "❌ Произошла ошибка."; } } else if (command == "chatSend") { try { var textMsg = msg.Text; text = ChatCommand.Send(textMsg, user, sender); } catch (Exception e) { text = $"❌ Произошла ошибка. {e}"; } } else if (command == "newChatCreate") { try { var number = msg.Text; text = NewChatCommand.CreateChat(number, user, sender, bot); } catch { text = "❌ Произошла ошибка."; } } var kb = new KeyboardBuilder(bot); kb.AddButton(ButtonsHelper.ToHomeButton()); sender.Text(text, msg.ChatId, kb.Build()); // UsersCommandHelper.GetHelper().Add("", user.Id); }
public Task <string> Handle(PutCommand <T> request, CancellationToken cancellationToken) { var result = repository.Update(request.Obj); return(Task.FromResult(result)); }