private static async Task Run() { Api bot = new Api("146368700:AAEPKl3D6RLUNylmTqOUB-9cxKIwZGUyEfM"); int offset = 0; AiCommand aiCommand = new AiCommand(bot); CurrencyCommand currencyCommand = new CurrencyCommand(bot); DefaultCommand defaultCommand = new DefaultCommand(bot); WeatherCommand weatherCommand = new WeatherCommand(bot); TaskAddCommand taskAddCommand=new TaskAddCommand(bot); TaskListCommand taskListCommand = new TaskListCommand(bot); IBotCommand[] commands = {currencyCommand, weatherCommand,taskListCommand,taskAddCommand, aiCommand, defaultCommand}; while (true) { Update[] updates = await bot.GetUpdates(offset); foreach (Update update in updates) { if (update.Message.Type == MessageType.TextMessage) { string inputMessage = update.Message.Text; List<CommandEntity> commandsRecieved = MessageParser.ParseMessage(inputMessage); foreach (CommandEntity commandRecieved in commandsRecieved) { foreach (IBotCommand command in commands) { if (command.IsExecutable(commandRecieved.Name)) { Dictionary<string, object> context = new Dictionary<string, object> { {"commandEntity", commandRecieved}, {"update", update} }; command.Execute(context); break; } } } } offset = update.Id + 1; } await Task.Delay(1000); } }
protected internal MainWindowViewModel(IEncryption encryption) : base(true) { _encryption = encryption ?? throw new ArgumentNullException(nameof(encryption)); EncryptClick = new DefaultCommand { Text = "Encrypt", Command = new RelayCommand(rc => BtnEncryptClick()) }; DecryptClick = new DefaultCommand { Text = "Decrypt", Command = new RelayCommand(rc => BtnDecryptClick()) }; CompareClick = new DefaultCommand { Text = "Compare", Command = new RelayCommand(rc => BtnCompareClick()) }; AboutWindowClick = new DefaultCommand { Text = "About", Command = new RelayCommand(rc => BtnAboutWindowClick()) }; LostFocus = new DefaultCommand { Command = new RelayCommand(rc => ExecuteCustomColorOnLostFocus()) }; }
public void HelpForSubSubCommands() { // Given var logger = new StringBuilderLogger(); var subCommand = new SubCommand() .RegisterSubCommand(new KatasCommand()) ; var root = new DefaultCommand() .RegisterSubCommand(subCommand) .Use(logger) ; // When var result = root.Execute("sub", "katas", "help"); // Then Assert.That(result, Is.EqualTo(0), logger.ErrorBuilder.ToString()); var lines = logger.InfoBuilder.ToString() .Split('\n') .Where(row => !string.IsNullOrWhiteSpace(row)) .Select(row => row.Replace("\r", "")) .ToArray() ; var i = -1; lines[++i].Trim().ShouldBe("This command is intended for demonstration purposes. It provides some katas"); }
public void SubCommandSectionFooter() { // Given var logger = new StringBuilderLogger(); var subCommand = new SubCommand() .RegisterSubCommand(new KatasCommand()) ; var root = new DefaultCommand() .RegisterSubCommand(subCommand) .Use(logger) ; // When var result = root.Execute("sub", "help"); // Then Assert.That(result, Is.EqualTo(0), logger.ErrorBuilder.ToString()); var lines = logger.InfoBuilder.ToString() .Split('\n') .Select(row => row.Replace("\r", "")) .SkipUntil(row => row == "To get help for subcommands") .ToArray() ; var i = -1; lines[++i].Trim().ShouldBe("To get help for subcommands"); lines[++i].Trim().ShouldBe("sub help <subcommand>"); }
internal static void Validate <TRunInfo>(DefaultCommand <TRunInfo> defaultCommand) where TRunInfo : class { int commandLevel = -1; if (defaultCommand.Arguments != null) { CommandRules.Common.ArgumentsCannotBeNull(defaultCommand, commandLevel); foreach (ArgumentBase <TRunInfo> argument in defaultCommand.Arguments) { argument.Validate(commandLevel); } } if (defaultCommand.Options != null) { CommandRules.Common.OptionsCannotBeNull(defaultCommand.Options, commandLevel); CommandRules.Common.OptionKeysMustMatchRegex(defaultCommand.Options, commandLevel); CommandRules.Common.OptionKeysMustBeUnique(defaultCommand.Options, null, commandLevel); foreach (OptionBase <TRunInfo> option in defaultCommand.Options) { option.ValidateOption(commandLevel); } } }
public async Task Command_should_be_produced_by_valid_ingestion_service() { var messagesCollectorMock = new Mock <IAsyncCollector <EventData> >(); var loggerMock = new Mock <ILogger>(); messagesCollectorMock .Setup(x => x.AddAsync(It.IsAny <EventData>(), default)) .Returns( Task.CompletedTask ); var command = new DefaultCommand { Header = new MessageHeader(Guid.NewGuid().ToString(), nameof(DefaultCommand), nameof(Sources.Orchestrator)), }; Producer producer = new Producer(messagesCollectorMock.Object, loggerMock.Object); ProducerResult result = await producer.ProduceCommandWithRetryAsync(command); ICommandContainer commandContainer = DeserializeEventData(result.Message); MessageHeader header = GetCommandHeader(commandContainer); Assert.True(result.Valid); Assert.NotEqual(header.MessageId, command.Header.MessageId); Assert.NotEqual(header.CreationDate, command.Header.CreationDate); Assert.Equal(header.TransactionId, command.Header.TransactionId); Assert.Equal(header.MessageType, command.Header.MessageType); Assert.Equal(header.Source, command.Header.Source); }
internal static string BuildFor <TRunInfo>(DefaultCommand <TRunInfo> command, string programName) where TRunInfo : class { var sb = new StringBuilder(); sb.AppendLine("Default Command"); if (!string.IsNullOrWhiteSpace(command.Description)) { sb.AppendLine(Padding + $"{command.Description}"); } sb.Append(Padding + "Usage: "); var helpTokens = new List <string>(); if (!string.IsNullOrWhiteSpace(programName)) { helpTokens.Add(programName); } helpTokens.AddRange(command.Arguments.Select(a => a.GetHelpToken())); helpTokens.AddRange(command.Options.Select(o => o.GetHelpToken())); var tokens = string.Join(" ", helpTokens); sb.Append(tokens); return(sb.ToString()); }
//if timeout is set and window is not closed after timeout - click default button internal Thread CloseWindowOnTimeout(int timeout) { if (timeout < 100) { return(null); } Thread t = new Thread(() => { if (timeout < 2000) { Thread.Sleep(timeout); } else { int count = timeout / 300; for (int i = 0; i < count; i++) { Thread.Sleep(300); int idx = i; WPF_Helper.ExecuteOnUIThread(() => { UpdateDefaultButtonTimeout(idx * 300, timeout); return(0); }); } } if (IsVisible) { WPF_Helper.ExecuteOnUIThread(() => { DefaultCommand.Execute(this); return(0); }); } }); t.Name = "AutoCloseMessage"; t.Start(); return(t); }
/// <summary> /// Shows the help for this command line utility tool. It prints out the help display, and can be overridden. /// </summary> /// <param name="args"></param> /// <returns></returns> private int ShowHelp() { ConsoleLogger.PrintLine(""); ConsoleLogger.PrintLine("NAME"); ConsoleLogger.PrintLine(_name + " Version " + Version); ConsoleLogger.PrintLine(""); ConsoleLogger.PrintLine("SYNOPSIS"); ConsoleLogger.PrintLine(_synopsis); ConsoleLogger.PrintLine(""); ConsoleLogger.PrintLine("DESCRIPTION"); ConsoleLogger.PrintLine(_description); ConsoleLogger.PrintLine(""); ConsoleLogger.PrintLine("COMMANDS"); if (hasDefaultCommand) { ConsoleLogger.PrintLine(DefaultCommand.ToString()); ConsoleLogger.PrintLine(""); } foreach (ConsoleCommand c in _commands.Values) { ConsoleLogger.PrintLine(c.ToString()); ConsoleLogger.PrintLine(""); } return(0); }
public void AssignmentTest() { ICommand command = new DefaultCommand(); Assert.AreEqual("DefaultCommand", command.FullName); Assert.AreEqual("defcmd", command.ShortName); }
public static async Task <IEvent <TEntity> > Send <TEntity>(this IMediator mediator, string commandName, Action <IDictionaryBuilder <string, object> > dictionaryBuilderAction) where TEntity : class { return(await mediator .Send <IEvent <TEntity> >(DefaultCommand .Create <TEntity>(commandName, dictionaryBuilderAction)).ConfigureAwait(false)); }
public CreateContractViewModel() { bl = BLFacade.Instance; CreateContractCommand = new DefaultCommand(ExecuteCreateContract); CreateContractLineCommand = new DefaultCommand(ExecuteCreateContractLine, CanCreateContractLine); UpdateCustomersCommand = new DefaultCommand(ExecuteUpdateCustomers); }
public StatisticsViewModel() { startDate = DateTime.MinValue; endDate = DateTime.MaxValue; bl = BLFacade.Instance; PopulateDisplayItems(); UpdateCommand = new DefaultCommand(ExcecuteUpdate); }
public async void OnLoadCommand(DefaultCommand command, object parameter) { await this.LoadModelOnNodeAsync(HyperStore, MissionInstance); //UpdatePhasesUI(); //await UpdateMissionInstancesAsync(); await OnToastMessage.InvokeAsync(new ToastMessage($"Load mission", ToastMessageType.Info)); }
public MainWindowViewModel() { CurrentState = "Memory Trainer Version 1.4.1"; ShowHelp = new DefaultCommand(OnShowHelp); OpenCardGame = new DefaultCommand(OnOpenCardGame); OpenResultOverview = new DefaultCommand(OnOpenResultOverview); OpenNumberGame = new DefaultCommand(OnOpenNumberGame); }
void ExecuteMenu(MENU _menu) { menubuilder.addMenu(_menu); DefaultCommand command = new DefaultCommand(menubuilder, _menu); invoker.AddCommand(command); invoker.Execute(); }
private async Task OnLoadAsync( DefaultCommand command, object parameter) { await LoadDataAsync(); // TODO: Temp hack to force UI refresh. Remove once it's not needed RaiseNotify("test"); }
private async Task OnCustomExpand_Aggregate(DefaultCommand command, object parameter) { var itemVm = parameter as PropertyGridItemVm; if (itemVm != null) { await Utility.SetMainDataAdvanced(itemVm.DataProp.Value, true); } }
internal Queue <Stage <TRunInfo> > Create <TRunInfo>( DefaultCommand <TRunInfo> defaultCommand, Action <TRunInfo> postBuildCallback) where TRunInfo : class { Queue <Stage <TRunInfo> > pipeline = BuildCommonPipelineStages(defaultCommand); pipeline.Enqueue(new EndProcessStage <TRunInfo>(postBuildCallback)); return(pipeline); }
public ContractViewModel() { bl = BLFacade.Instance; UpdateContractList(); AddAmountCommand = new DefaultCommand(ExecuteAddAmount, CanAddAmount); SearchCommand = new DefaultCommand(ExecuteSearch, CanSearch); UpdateCommand = new DefaultCommand(ExecuteUpdate); DeactivateCommand = new DefaultCommand(ExecuteDeactivate, CanExecuteSelected); RemoveCommand = new DefaultCommand(ExecuteRemove, CanExecuteSelected); }
public void Authorise() { // Arrange var componentUnderTest = new DefaultCommand(); // Act var actual = componentUnderTest.Authorise(); // Assert actual.ShouldHaveSameValueAs(true); }
public void Result() { // Arrange var componentUnderTest = new DefaultCommand(); // Act componentUnderTest.Result = "result"; // Assert componentUnderTest.Result.ShouldHaveSameValueAs("result"); }
public void Target() { // Arrange var componentUnderTest = new DefaultCommand(); // Act componentUnderTest.Target = "target"; // Assert componentUnderTest.Target.ShouldHaveSameValueAs("target"); }
public void ToStringTest() { // Arrange var componentUnderTest = new DefaultCommand(); var expected = "[OnAuthoriseCalled:False] [OnAfterExecuteCalled:False] [OnAfterExecuteCalledWithException:False] [OnBeforeInitialiseTargetCalled:False] [OnInitialiseTargetCalled:False] [OnExecuteCalled:False]"; // Act var actual = componentUnderTest.ToString(); // Assert actual.ShouldHaveSameValueAs(expected); }
void OnRemovePhase(DefaultCommand command, object parameter) { var phaseModel = this.SelectedPhaseProp.Value; HyperMission mission = this.Mission; if (mission == null || phaseModel == null) { return; } mission.Phases.Remove(phaseModel); }
public void GetCommand_EmptyParameter_ReturnsDefaultCommand() { // Arrange OptionObject2015 optionObject2015 = new OptionObject2015(); IOptionObjectDecorator optionObjectDecorator = new OptionObjectDecorator(optionObject2015); IParameter parameter = new Parameter(""); DefaultCommand expected = new DefaultCommand(optionObjectDecorator, parameter); // Act IRunScriptCommand actual = CommandSelector.GetCommand(optionObject2015, parameter); // Assert Assert.AreEqual(expected.GetType(), actual.GetType()); }
public bool CanExecute(object parameter) { var args = (SearchBoxResultSuggestionChosenEventArgs)parameter; var command = GetCommand(args); if (command == null && DefaultCommand == null) { return(false); } if (command == null) { return(DefaultCommand.CanExecute(args.Tag)); } return(command.Command.CanExecute(command.CommandSelector.SelectTag(args.Tag))); }
// Falls back on a given Default or Help void ExecuteFallback(string[] args, string commandName) { if (DefaultCommand == null) { // If we have no default then invoke Help string message = $"The command '{commandName}' does not exist, and here is no default command"; HelpFacade.Execute(message); } else { // Pass on all arguments to the default Command DefaultCommand.Execute(args); } }
public void InvalidCommandTest() { ICommand command = new DefaultCommand(); var arguments = new List <string>() { "someUnknownCommand", "SomeArgument" }; var commandResult = command.Execute(arguments); Assert.IsNotNull(commandResult); Assert.IsTrue(commandResult.Count() == 1); Assert.AreEqual($"Command {arguments.First()} was not found", commandResult.First()); }
public void Run(TextReader reader = null, bool echoInput = false) { if (reader == null) { // set input limit to 10M var stdin = Console.OpenStandardInput(1024 * 1024 * 10); reader = new StreamReader(stdin); } while (keepRunning) { Console.Write(Welcome + "> "); var rawInput = reader.ReadLine(); if (rawInput == null) { break; } if (echoInput) { Console.WriteLine(rawInput); } var cmdline = rawInput.Split( new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries ); if (cmdline.Length == 0) { continue; } try { var cmd = FindCommand(cmdline[0]); if (cmd != null) { var parameters = new string[cmdline.Length - 1]; Array.Copy(cmdline, 1, parameters, 0, cmdline.Length - 1); cmd.Execute(parameters); } else { DefaultCommand.Execute(cmdline); } } catch (Exception x) { Console.WriteLine("ERROR: Unexpected exception occured\n{0}", x); } } }
public ICommand Build(string command) { string[] commandSplit = command?.Split(' '); ICommand createdCommand; switch (commandSplit[0]) { case "/help": case "/h": createdCommand = new HelpCommand(); break; case "/version": case "/v": createdCommand = new VersionCommand(); break; case "/clear": createdCommand = new ClearCommand(); break; case "/quit": case "/q": createdCommand = new QuitCommand(); break; case "/post": case "/p": createdCommand = new PostCommand(commandSplit); break; case "/retrieve": case "/r": createdCommand = new RetrieveCommand(commandSplit); break; case "/settings": createdCommand = new SettingsCommand(commandSplit); break; default: createdCommand = new DefaultCommand(); break; } return(createdCommand); }
public void Init() { _fakeConsole = Substitute.For<IConsole>(); _defaultCommand = new DefaultCommand(_fakeConsole, "$&$%$"); }
public virtual void ExecuteDefault(DefaultCommand command) { command.Sender = SettingsScreen; SettingsScreen.Default.OnNext(command); }
public virtual void DefaultHandler(DefaultCommand command) { this.Default(command.Sender as SettingsScreenViewModel); }
public ActionMenuService() { _defaultCmd = new DefaultCommand(); }