Esempio n. 1
0
        ///<summary>
        /// Returns true if the type match the current type filter and section name.
        ///</summary>
        ///<param name="command">Command to match</param>
        ///<returns>True is match</returns>
        public override bool Match(CommandModel command)
        {
            var blockCommand = command as AddApplicationBlockCommand;
            
            if (blockCommand == null)
            {
                return base.Match(command);
            }

            // If only a type filter is specified
            if (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SectionName))
            {
                return base.Match(command);
            }

            // If only a section filter is specified
            if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SectionName))
            {
                return SectionName.Equals(blockCommand.SectionName);
            }

            // If both a section and type filters are specified
            if (!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SectionName))
            {
                return base.Match(blockCommand) && SectionName.Equals(blockCommand.SectionName); 
            }

            return false;
        }
        public void CommandModelWillParseIntegers()
        {
            CommandModel model = new CommandModel()
                .Option<int>("foo", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, int>>()["foo"] = v)
                .Option<int>("bar", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, int>>()["bar"] = v);

            Command cmd2 = model.Parse(new[] { "--foo", "123", "--bar:456" });
            cmd2.Get<Dictionary<string, int>>()["foo"].ShouldBe(123);
            cmd2.Get<Dictionary<string, int>>()["bar"].ShouldBe(456);
        }
        public void CommandModelWillParseStrings()
        {
            CommandModel model = new CommandModel()
                .Option<string>("foo", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["foo"] = v)
                .Option<string>("bar", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["bar"] = v);

            Command cmd2 = model.Parse("--foo", "123", "--bar:456");
            cmd2.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd2.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");
        }
        public void LongNameIsCaseInsensitive()
        {
            CommandModel model = new CommandModel()
                .Option<string>("foo", "f", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["foo"] = v)
                .Option<string>("bar", "b", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["bar"] = v);

            Command cmd1 = model.Parse("--FoO", "123", "--BaR:456");
            cmd1.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd1.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");
        }
        public void ShortNameWorksAsOption()
        {
            CommandModel model = new CommandModel()
                .Option<string>("foo", "f", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["foo"] = v)
                .Option<string>("bar", "b", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["bar"] = v);

            Command cmd1 = model.Parse("-f", "123", "-b:456");
            cmd1.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd1.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");

            Command cmd2 = model.Parse("/f", "123", "/b:456");
            cmd2.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd2.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");
        }
        private BaseRobotCommand CreatePouringCommand(CommandModel source)
        {
            if ((CommandName)source.CurrentName != CommandName.Pouring)
            {
                throw new ArgumentException(GetMessage("заливки"));
            }

            var pouringCommand = new PouringCellCommand(grid, robot, (ColorCell)source.CurrentOneParameter)
            {
                Id = source.CommandId,
                NextNumberCommand = source.CurrentTwoParameter
            };

            return(pouringCommand);
        }
        /// <summary>
        /// Метод
        /// </summary>
        /// <param name="source"></param>
        private BaseRobotCommand CreateLearnCellCommand(CommandModel source)
        {
            if ((CommandName)source.CurrentName != CommandName.Move)
            {
                throw new ArgumentException(GetMessage("изучения"));
            }

            var learnCellCommand = new LearnCellCommand(_commands, grid, robot,
                                                        source.CurrentOneParameter, source.CurrentTwoParameter)
            {
                Id = source.CommandId
            };

            return(learnCellCommand);
        }
Esempio n. 8
0
 private void Validate(CommandModel command, object[] arguments, IServiceProvider services)
 {
     if (command == null)
     {
         throw new ArgumentNullException(nameof(command));
     }
     if (arguments == null)
     {
         throw new ArgumentNullException(nameof(arguments));
     }
     if (services == null)
     {
         throw new ArgumentNullException(nameof(services));
     }
 }
Esempio n. 9
0
        public ClienteNewControl()
        {
            InitializeComponent();
            ClienteNewViewModel = new ClienteNewControlViewModel(DependencyResolver.Instance.FacadeProvider);
            ClienteNewViewModel.InitializeViewContent();

            //Bind the DataGrid to the customer data
            this.DataContext = ClienteNewViewModel;

            CommandModel addPedidoComand = ClienteNewViewModel.SaveClienteComand;

            ButtonSaveCliente.Command          = addPedidoComand.Command;
            ButtonSaveCliente.CommandParameter = this.DataContext;
            ButtonSaveCliente.CommandBindings.Add(new CommandBinding(addPedidoComand.Command, addPedidoComand.OnExecute, addPedidoComand.OnCanExecute));
        }
Esempio n. 10
0
        private static CommandModel AddCommand(ModelBuilder modelBuilder, string howTo, string line, CategoryModel category)
        {
            var command = new CommandModel
            {
                // This feels so wrong--but according to the Microsoft docs this is how you do code first seeding
                Id         = IdentityValues.CommandId++,
                HowTo      = howTo,
                Line       = line,
                CategoryId = category.Id
            };

            modelBuilder.Entity <CommandModel>().HasData(command);

            return(command);
        }
        private BaseRobotCommand CreateRotationCommand(CommandModel source)
        {
            if ((CommandName)source.CurrentName != CommandName.Rotation)
            {
                throw new ArgumentException(GetMessage("поворота"));
            }

            var rotationCommand = new RotationRobotCommand(robot, (RouteMove)source.CurrentOneParameter)
            {
                Id = source.CommandId,
                NextNumberCommand = source.CurrentTwoParameter
            };

            return(rotationCommand);
        }
Esempio n. 12
0
        /// <inheritdoc />
        protected override IParsingResult DoApply(ICommandParserOptions options, CommandModel model, string[] args, ref int argIndex)
        {
            try
            {
                this.TargetProperty.SetValue(model, this._converter.TryConvert(args[argIndex], options.UiCulture));

                argIndex++;

                return(ParsingSuccess.Instance);
            }
            catch (Exception e)
            {
                return(new ParsingFailure(e.Message));
            }
        }
Esempio n. 13
0
        public void TestInsertCommand()
        {
            var connectionString = DbHelper.CreateStringConnectionFromPath(AssemblyDirectory + emptyDbPath);

            using (var sqliteDbConnector = new SqliteDbConnector(connectionString))
            {
                var cmd = new CommandModel {
                    Command = "NameInserted", CommandName = "CmdInserted"
                };
                sqliteDbConnector.InsertOrUpdateCommand(cmd);
                var resultCmd = sqliteDbConnector.GetCommands()[0];
                Assert.AreEqual(cmd.CommandName, resultCmd.CommandName);
                Assert.AreEqual(cmd.Command, resultCmd.Command);
            }
        }
Esempio n. 14
0
        public void should_publish_executed_event_on_success()
        {
            GivenCommandQueue();
            var commandA     = new CommandA();
            var commandModel = new CommandModel
            {
                Body = commandA
            };

            Subject.Handle(new ApplicationStartedEvent());

            QueueAndWaitForExecution(commandModel, true);

            VerifyEventPublished <CommandExecutedEvent>();
        }
 public DataTable FindTable(CommandModel args)
 {
     try
     {
         //  if (args != null)
         {
             return(this.wtserv.FindTable(args.username, args.password, args.tablename));
         }
     }
     catch (Exception ex)
     {
         program.errorreport(ex);
         return(null);
     }
 }
Esempio n. 16
0
        public void should_execute_on_executor()
        {
            GivenCommandQueue();
            var commandA     = new CommandA();
            var commandModel = new CommandModel
            {
                Body = commandA
            };

            Subject.Handle(new ApplicationStartedEvent());

            QueueAndWaitForExecution(commandModel);

            _executorA.Verify(c => c.Execute(commandA), Times.Once());
        }
    public static void RegisterDependencies(this ITypeRegistrar registrar, CommandModel model)
    {
        var stack = new Stack <CommandInfo>();

        model.Commands.ForEach(c => stack.Push(c));
        if (model.DefaultCommand != null)
        {
            stack.Push(model.DefaultCommand);
        }

        while (stack.Count > 0)
        {
            var command = stack.Pop();

            if (command.SettingsType == null)
            {
                // TODO: Error message
                throw new InvalidOperationException("Command setting type cannot be null.");
            }

            if (command.CommandType != null)
            {
                registrar?.Register(command.CommandType, command.CommandType);
            }

            foreach (var parameter in command.Parameters)
            {
                var pairDeconstructor = parameter?.PairDeconstructor?.Type;
                if (pairDeconstructor != null)
                {
                    registrar?.Register(pairDeconstructor, pairDeconstructor);
                }

                var typeConverterTypeName = parameter?.Converter?.ConverterTypeName;
                if (!string.IsNullOrWhiteSpace(typeConverterTypeName))
                {
                    var typeConverterType = Type.GetType(typeConverterTypeName);
                    Debug.Assert(typeConverterType != null, "Could not create type");
                    registrar?.Register(typeConverterType, typeConverterType);
                }
            }

            foreach (var child in command.Children)
            {
                stack.Push(child);
            }
        }
    }
Esempio n. 18
0
        public static bool TryAuthorizationUser(JObject authData, out CommandModel result)
        {
            try
            {
                string email    = authData["Email"].ToString();
                string password = authData["Password"].ToString();

                using (var dbContext = new MessangerModel())
                {
                    if (string.IsNullOrEmpty(email))
                    {
                        result = CommandHelper.GetCommandResultData(CommandTypes.Authorization, StatusCodes.BadRequest, new JObject {
                            { "Message", "Email could not be empty!" }
                        });

                        return(false);
                    }

                    var user = dbContext.Users.FirstOrDefault(u => u.Email == email && u.Password == password);

                    if (user == null)
                    {
                        result = CommandHelper.GetCommandResultData(CommandTypes.Authorization, StatusCodes.BadRequest, new JObject {
                            { "Message", "There is no user with such email or password" }
                        });

                        return(false);
                    }

                    // generate and send back user auth token
                    var plainTextBytes = Encoding.UTF8.GetBytes($"{user.Email}:{user.Password}");
                    var token          = Convert.ToBase64String(plainTextBytes);

                    result = CommandHelper.GetCommandResultData(CommandTypes.Authorization, StatusCodes.OK, new JObject {
                        { "Message", "OK" }, { "Token", token }
                    });

                    return(true);
                }
            }
            catch (Exception ex)
            {
                result = CommandHelper.GetCommandResultData(CommandTypes.Authorization, StatusCodes.BadRequest, new JObject {
                    { "Message", ex.Message }
                });
                return(false);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Searches the command sent from the client and executes it
        /// </summary>
        /// <param name="comman"></param>
        /// <returns></returns>
        public string ExecuteCommand(String comman)
        {
            try
            {
                string ap = "";
                if (comman != null)
                {
                    CommandModel cms = JsonConvert.DeserializeObject <CommandModel>(comman);
                    foreach (ICommand cmd in commands)
                    {
                        /* args[0] root
                         *  args[1] record tag
                         * args[2] username
                         * args[3] password
                         * args[4] db name
                         * args[5] tablename
                         */
                        string[] args = new string[10];
                        args[0] = cms.root;
                        args[1] = cms.recordtag;
                        args[2] = cms.username;
                        args[3] = cms.password;
                        args[4] = cms.dbname;
                        args[5] = cms.tablename;
                        args[6] = cms.data;
                        args[7] = cms.algorith;
                        args[8] = cms.hashalg;
                        args[9] = cms.passphrase;
                        //  if( comman.StartsWith(cms.commandname))
                        {
                            // string arg = comman.Substring(comman.IndexOf(cmd.Name()) + 1);
                            //  string [] args= arg.Split('&');
                            ap = cmd.Execute(args);
                        }
                    }
                }
                return(ap);
            }
            catch (Exception ex)
            {
                program.errorreport(ex);
                CommandModel cmd = new CommandModel();
                cmd.friendlyerrormsg = ex.Message;
                cmd.exception        = ex.ToString();

                return(JsonConvert.SerializeObject(cmd));
            }
        }
Esempio n. 20
0
        protected override void ButtonOk_Click(object sender, EventArgs e)
        {
            Log.Debug(TAG, "ButtonOk_Click");
            string errMsg = ReadView(0);

            if (!string.IsNullOrWhiteSpace(errMsg))
            {
                Log.Error(TAG, $"ButtonOk_Click - {errMsg}");
                CardSubtitle.Text = errMsg;
                CardSubtitle.SetTextColor(Android.Graphics.Color.Red);
                Toast.MakeText(this, errMsg, ToastLength.Short).Show();
                return;
            }

            CommandModel command = ReadFormToObject(new CommandModel()
            {
                ScriptId = ScriptId
            });

            lock (DatabaseContext.DbLocker)
            {
                using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                {
                    if (db.Commands.Any(x => x.ScriptId == ScriptId))
                    {
                        command.Ordering = db.Commands.Where(x => x.ScriptId == ScriptId).Max(x => x.Ordering) + 1;
                    }
                    else
                    {
                        command.Ordering = 1;
                    }
                }
            }

            lock (DatabaseContext.DbLocker)
            {
                using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                {
                    db.Commands.Add(command);
                    db.SaveChanges();
                }
            }

            Intent intent = new Intent(this, typeof(CommandsListActivity));

            intent.PutExtra(nameof(ScriptModel.Id), ScriptId);
            StartActivity(intent);
        }
Esempio n. 21
0
        /// <summary>
        ///		Procesa una exportación de una consulta a CSV
        /// </summary>
        internal bool Execute(SentenceExportCsv sentence)
        {
            bool   exported = false;
            string fileName = Processor.Manager.Step.Project.GetFullFileName(sentence.FileName);

            // Exporta los datos
            using (BlockLogModel block = Processor.Manager.Logger.Default.CreateBlock(LogModel.LogType.Info, $"Start exporting to '{fileName}'"))
            {
                if (string.IsNullOrWhiteSpace(sentence.Command.Sql))
                {
                    block.Error("There is not command at export sentence");
                }
                else
                {
                    ProviderModel provider = Processor.GetProvider(sentence.Source);

                    if (provider == null)
                    {
                        block.Error($"Can't find the provider. Key: '{sentence.Source}'");
                    }
                    else
                    {
                        CommandModel command = Processor.ConvertProviderCommand(sentence.Command, out string error);

                        if (!string.IsNullOrWhiteSpace(error))
                        {
                            block.Error($"Error when convert export command. {error}");
                        }
                        else
                        {
                            try
                            {
                                // Exporta los datos
                                Export(fileName, provider, command, sentence, block);
                                // Indica que se ha exportado correctamente
                                exported = true;
                            }
                            catch (Exception exception)
                            {
                                block.Error($"Error when export to '{fileName}'", exception);
                            }
                        }
                    }
                }
            }
            // Devuelve el valor que indica si se ha exportado correctamente
            return(exported);
        }
Esempio n. 22
0
        public void CommandModelWillParseStrings()
        {
            var model = new CommandModel()
                        .Option <string>("foo", (cmd, v) => cmd.Get <Dictionary <string, string> >()["foo"] = v)
                        .Option <string>("bar", (cmd, v) => cmd.Get <Dictionary <string, string> >()["bar"] = v);

            var cmd1 = model.Parse("/foo", "123", "/bar:456");

            cmd1.Get <Dictionary <string, string> >()["foo"].ShouldBe("123");
            cmd1.Get <Dictionary <string, string> >()["bar"].ShouldBe("456");

            var cmd2 = model.Parse("--foo", "123", "--bar:456");

            cmd2.Get <Dictionary <string, string> >()["foo"].ShouldBe("123");
            cmd2.Get <Dictionary <string, string> >()["bar"].ShouldBe("456");
        }
Esempio n. 23
0
 public CtViewModel()
 {
     CtFileSettings    = new CtFile();
     GenerateCtWorking = new LineCtWorkingDay
     {
         StartTime   = "09:00",
         EndTime     = "18:00",
         StartDinner = "13:00",
         EndDinner   = "14:00"
     };
     CtFileSettings.PropertyChanged += UpdateContent;
     MainWindow.GlobalParameters.PropertyChanged += UpdateGlobalParameters;
     AddItem        = new CommandModel(AddItemCtWorkingDay);
     RemoveItem     = new CommandModel(RemoveItemCtWorkingDay);
     GenerateCtFile = new CommandModel(GenerateCt);
 }
Esempio n. 24
0
        /// <summary>
        ///		Obtiene la tabla de datos
        /// </summary>
        private IEnumerable <DataTable> GetDataTable(ProviderModel provider, CommandModel command)
        {
            using (BlockLogModel block = Manager.Logger.Default.CreateBlock(LogModel.LogType.Info, "Read datatable"))
            {
                int pageIndex = 0;

                // Carga los datos
                foreach (DataTable table in provider.LoadData(command))
                {
                    // Log
                    AddDebug($"Reading page {++pageIndex}", command);
                    // Devuelve la tabla
                    yield return(table);
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Send command to server and get response
        /// </summary>
        /// <param name="commandType">Command type</param>
        /// <param name="metaData">Command metadata</param>
        public async Task SendCommandAsync(CommandTypes commandType, JObject commandData)
        {
            CommandModel command = new CommandModel
            {
                Data        = commandData.ToString(),
                CommandType = commandType
            };

            Packet commandPacket = new Packet
            {
                ActionState = ActionStates.Command,
                Command     = command
            };

            await SendPacketAsync(commandPacket);
        }
Esempio n. 26
0
 public async Task <string> Send_GetMachineOnline()
 {
     return(await Task.Factory.StartNew(() =>
     {
         CommandModel cmd = new CommandModel();
         using (SCMSEntities db = new SCMSEntities())
         {
             var machines = db.Proc_Machines().ToList();
             cmd.Command = CommandMethod.GET.ToString();
             cmd.Model = ModelMethod.MachineOnlineModel.ToString();
             cmd.Data = JsonConvert.SerializeObject(machines);
             cmd.DataLength = machines.Count;
             return JsonConvert.SerializeObject(cmd);
         }
     }));
 }
Esempio n. 27
0
        public void CommandModelWillParseIntegers()
        {
            var model = new CommandModel()
                        .Option <int>("foo", (cmd, v) => cmd.Get <Dictionary <string, int> >()["foo"] = v)
                        .Option <int>("bar", (cmd, v) => cmd.Get <Dictionary <string, int> >()["bar"] = v);

            var cmd1 = model.Parse(new[] { "/foo", "123", "/bar:456" });

            cmd1.Get <Dictionary <string, int> >()["foo"].ShouldBe(123);
            cmd1.Get <Dictionary <string, int> >()["bar"].ShouldBe(456);

            var cmd2 = model.Parse(new[] { "--foo", "123", "--bar:456" });

            cmd2.Get <Dictionary <string, int> >()["foo"].ShouldBe(123);
            cmd2.Get <Dictionary <string, int> >()["bar"].ShouldBe(456);
        }
Esempio n. 28
0
        private void CommandWindow(CommandModel cmd)
        {
            int window;

            if (!Int32.TryParse(cmd.Parameter, out window))
            {
                return;
            }
            ChatView chat = f_ChatViewManager.GetChat(window - 1);

            if (chat == null)
            {
                return;
            }
            f_ChatViewManager.CurrentChat = chat;
        }
Esempio n. 29
0
 private void ReceiveMessageHandler(object sender, ReceiveEventArgs e)
 {
     if (e.ReceiveContent != null)
     {
         List <string>  strList    = new List <string>();
         CommandModel   receiveCmd = PublicMethod.JsonDeSerialize <CommandModel>(e.ReceiveContent.Message);
         ReflectionType typeObject = new ReflectionType(this);
         BaseCmd        baseCmd    = typeObject.GetCmd(receiveCmd, e.ReceiveContent);
         strList = baseCmd.Do();
         foreach (string strContent in strList)
         {
             Connector.Send(strContent);
         }
         baseCmd.Dispose();
     }
 }
Esempio n. 30
0
        public static CommandModel ConvertCommandToModel(this string commandOutput)
        {
            if (commandOutput == null)
            {
                throw new ArgumentNullException(nameof(commandOutput));
            }
            var command = new CommandModel {
                date        = DateTime.Now,
                output      = commandOutput,
                outputTable = TextToList(commandOutput),
                error       = commandOutput,
                errorTable  = TextToList(commandOutput)
            };

            return(command);
        }
        /// <inheritdoc />
        protected override void DoApplySwitch(CommandModel model, string[] switchArguments, IValueParsingOptions pOptions)
        {
            if (pOptions == null)
            {
                throw new ArgumentNullException(nameof(pOptions));
            }
            if (switchArguments.Length == 0)
            {
                throw new ArgumentException("Value cannot be an empty collection.", nameof(switchArguments));
            }
            string enumText = switchArguments[0];

            object enumValue = Enum.Parse(this._enumType, enumText, true); // might fail, TODO: Try finding something better than exception during parsing user input...

            this.TargetProperty.SetValue(model, enumValue);
        }
Esempio n. 32
0
        /// <inheritdoc />
        protected override void DoApplySwitch(CommandModel model, string[] switchArguments, IValueParsingOptions pOptions)
        {
            if (pOptions == null)
            {
                throw new ArgumentNullException(nameof(pOptions));
            }
            if (switchArguments.Length == 0)
            {
                throw new ArgumentException("Value cannot be an empty collection.", nameof(switchArguments));
            }
            string valueText = switchArguments[0];

            object value = this._converter.TryConvert(valueText, pOptions.UiCulture);

            this.TargetProperty.SetValue(model, value);
        }
Esempio n. 33
0
 public void AddCommandToPipeLine(CommandModel command)
 {
     try
     {
         if (commandList != null && command != null)
         {
             command.Id   = GetUiqueId();
             command.Time = DateTime.UtcNow.TimeOfDay;
             commandList.Add(command);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Esempio n. 34
0
        public void ShortNameWorksAsOption()
        {
            CommandModel model = new CommandModel()
                                 .Option <string>("foo", "f", string.Empty, (cmd, v) => cmd.Get <Dictionary <string, string> >()["foo"] = v)
                                 .Option <string>("bar", "b", string.Empty, (cmd, v) => cmd.Get <Dictionary <string, string> >()["bar"] = v);

            Command cmd1 = model.Parse("-f", "123", "-b:456");

            cmd1.Get <Dictionary <string, string> >()["foo"].ShouldBe("123");
            cmd1.Get <Dictionary <string, string> >()["bar"].ShouldBe("456");

            Command cmd2 = model.Parse("/f", "123", "/b:456");

            cmd2.Get <Dictionary <string, string> >()["foo"].ShouldBe("123");
            cmd2.Get <Dictionary <string, string> >()["bar"].ShouldBe("456");
        }
Esempio n. 35
0
        public void should_use_completion_message()
        {
            GivenCommandQueue();
            var commandA     = new CommandA();
            var commandModel = new CommandModel
            {
                Body = commandA
            };

            Subject.Handle(new ApplicationStartedEvent());

            QueueAndWaitForExecution(commandModel);

            Mocker.GetMock <IManageCommandQueue>()
            .Verify(s => s.Complete(It.Is <CommandModel>(c => c == commandModel), commandA.CompletionMessage), Times.Once());
        }
        public void ShortNameIsCaseSensitive()
        {
            CommandModel model = new CommandModel()
                .Option<string>("foo", "f", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["foo"] = v)
                .Option<string>("bar", "F", string.Empty, (cmd, v) => cmd.Get<Dictionary<string, string>>()["bar"] = v);

            Command cmd1 = model.Parse("-f", "123", "-F", "456");
            cmd1.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd1.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");

            Command cmd2 = model.Parse("-f:123", "-F:456");
            cmd2.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd2.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");

            Command cmd3 = model.Parse("/f", "123", "/F", "456");
            cmd3.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd3.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");

            Command cmd4 = model.Parse("/f:123", "/F:456");
            cmd4.Get<Dictionary<string, string>>()["foo"].ShouldBe("123");
            cmd4.Get<Dictionary<string, string>>()["bar"].ShouldBe("456");
        }
Esempio n. 37
0
        /// <summary>
        /// Checks a AddApplicationBlockCommand.
        /// </summary>
        /// <param name="command">The command instance.</param>
        /// <returns>True if the command should be included.</returns>
        public bool Check(CommandModel command)
        {
            var match = MatchKind.Allow;

            foreach (var filter in this.CommandMatchFilters.Where(filter => filter.Match(command)))
            {
                match = filter.MatchKind;
            }

            return match == MatchKind.Allow;
        }
Esempio n. 38
0
        public static CommandModel CreateCommandModel()
        {
            var model = new CommandModel();
            model.Command("install")
                .Parameter<string>((m, v) => m.Parameters.Add(v))
                .Execute(RunInstall);

            model.Command("uninstall")
                .Parameter<string>((m, v) => m.Parameters.Add(v))
                .Execute(RunUninstall);

            model.Command("{run server}", EndingWithExe, (m, v) => m.Set(v))
                .Option<StartOptions, int>("port", (m, v) => m.Port = v)
                .Option<StartOptions, string>("path", (m, v) => m.Settings["directory"] = v)
                .Option<StartOptions, string>("vpath", (m, v) => { })
                .Execute<StartOptions, int>(RunWebApplication);

            return model;
        }
Esempio n. 39
0
 ///<summary>
 /// Returns true if the command instance type match the current type filter.
 ///</summary>
 ///<param name="command">Command to match</param>
 ///<returns>True is match</returns>
 public virtual bool Match(CommandModel command)
 {
     return Match(command.GetType());
 }
Esempio n. 40
0
        public CommandModel CreateCommandModel()
        {
            var model = new CommandModel();

            // run this alternate command for any help-like parameter
            model.Command("{show help}", IsHelpOption, (m, v) => { }).Execute(ShowHelp);

            // otherwise use these switches
            model.Option<StartOptions, string>(
                "server", "s", Resources.ProgramOutput_ServerOption,
                (options, value) => options.ServerFactory = value);

            model.Option<StartOptions, string>(
                "url", "u", Resources.ProgramOutput_UriOption,
                (options, value) => options.Urls.Add(value));

            model.Option<StartOptions, int>(
                "port", "p", Resources.ProgramOutput_PortOption,
                (options, value) => options.Port = value);

            model.Option<StartOptions, string>(
                "directory", "d", Resources.ProgramOutput_DirectoryOption,
                (options, value) => options.Settings["directory"] = value);

            model.Option<StartOptions, string>(
                "traceoutput", "o", Resources.ProgramOutput_OutputOption,
                (options, value) => options.Settings["traceoutput"] = value);

            model.Option<StartOptions, string>(
                "settings", Resources.ProgramOutput_SettingsOption,
                LoadSettings);

            model.Option<StartOptions, string>(
                "boot", "b", Resources.ProgramOutput_BootOption,
                (options, value) => options.Settings["boot"] = value);

            model.Option<StartOptions, int>(
                "devMode", "dev", Resources.ProgramOutput_DevModeOption,
                (options, value) => options.Settings["devMode"] = value.ToString());

            /* Disabled until we need to consume it anywhere.
            model.Option<StartOptions, string>(
                "verbosity", "v", "Set output verbosity level.",
                (options, value) => options.Settings["traceverbosity"] = value);
            */
            // and take the name of the application startup

            model.Parameter<string>((cmd, value) =>
            {
                var options = cmd.Get<StartOptions>();
                if (options.AppStartup == null)
                {
                    options.AppStartup = value;
                }
                else
                {
                    options.AppStartup += " " + value;
                }
            });

            // to call this action

            model.Execute<StartOptions>(RunServer);

            return model;
        }