string ISyncWork.Run(IWorkContext context)
 {
    var command = new CommandParser(context.Command).Parse();
    var route = new CommandRouteInterpretter(command).GetRoute();
    context.CommandInterpretter.AddSyncRoute(route);
    return "";
 }
示例#2
0
        static void Main(string[] args)
        {
            var commandParser = new CommandParser();

            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
示例#3
0
        public override void Create(CommandParser Parser)
        {
            Core.StandardMessage("version", "Build: RMUD Hadad <s0>");
            Core.StandardMessage("commit", "Commit: <s0>");
            Core.StandardMessage("no commit", "Commit version not found.");

            Parser.AddCommand(
                Or(
                    KeyWord("VERSION"),
                    KeyWord("VER")))
                .Manual("Displays the server version currently running.")
                .ProceduralRule((match, actor) =>
                {
                    var buildVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

                    MudObject.SendMessage(actor, "@version", buildVersion);

                    if (System.IO.File.Exists("version.txt"))
                        MudObject.SendMessage(actor, "@commit", System.IO.File.ReadAllText("version.txt"));
                    else
                        MudObject.SendMessage(actor, "@no commit");

                    foreach (var module in Core.IntegratedModules)
                        MudObject.SendMessage(actor, module.Info.Description);

                    return PerformResult.Continue;
                });
        }
 public void TestParseMultiply()
 {
     var commandParser = new CommandParser();
     string testInput = "2*8";
     var result = commandParser.Parse(testInput);
     Assert.AreEqual(16, result);
 }
 public void TestParseSubtract()
 {
     var commandParser = new CommandParser();
     string testInput = "2-6";
     var result = commandParser.Parse(testInput);
     Assert.AreEqual(-4, result);
 }
 public void TestParseDivde()
 {
     var commandParser = new CommandParser();
     string testInput = "8/2";
     var result = commandParser.Parse(testInput);
     Assert.AreEqual(4, result);
 }
 public void TestParseMod()
 {
     var commandParser = new CommandParser();
     string testInput = "8%3";
     var result = commandParser.Parse(testInput);
     Assert.AreEqual(2, result);
 }
 public void TestParseAdd()
 {
     var commandParser = new CommandParser();
     string testInput = "2+6";
     var result = commandParser.Parse(testInput);
     Assert.AreEqual(8, result);
 }
示例#9
0
        ///<summary>
        ///This gets the users message and passes it on to everyone currently
        ///playing.
        ///</summary>
        ///<param name="p">The player who invoked the command.</param>
        ///<param name="cp">The options the player sent along.</param>
        public override void doCommand(Player p, CommandParser cp)
        {
            string you = "You chat: {x{o{y\'{x{o{b" + cp.Arguments + "{x{o{y\'{x\n\r";
            string everyone = "\n\r" + p.Name + " chats: {o{y\'{x{o{b" + cp.Arguments + "{x{o{y\'{x\n\r";

            Mud.mudSuroden.writeAll(p, everyone, you);
        }
示例#10
0
		public override void Create(CommandParser Parser)
		{
			Parser.AddCommand(
				new KeyWord("LOOK", false),
				new LookProcessor(),
				"Look around at your suroundings.");
		}
 string ISyncWork.Run(IWorkContext context)
 {
    var command = new CommandParser(context.Command).Parse();
    var route = new CommandRouteInterpretter(command).GetRoute();
    CommandInterpretter.WorkCreator<ISyncWork>.Create(route, new CommandDef()).Run(context);
    return null;
 }
示例#12
0
 private void HandleAddBlackListCmd(CommandParser.Command param)
 {
     ulong gUID = 0uL;
     ulong.TryParse(param.GetParam(1), out gUID);
     MC2S_AddBlackList mC2S_AddBlackList = new MC2S_AddBlackList();
     mC2S_AddBlackList.GUID = gUID;
     Globals.Instance.CliSession.Send(315, mC2S_AddBlackList);
 }
示例#13
0
        public void Parse_EmptyCommand_ShouldHaveNoTokens()
        {
            CommandParser parser = new CommandParser();

            var tokens = parser.Parse(string.Empty).Tokens.ToArray();

            Assert.IsTrue(tokens.Length == 0);
        }
示例#14
0
        public static void Main()
        {
            var reader = new ConsoleReader();
            var writer = new ConsoleWriter();
            var commandParser = new CommandParser();

            Engine.Start(reader, writer, commandParser);
        }
        public void cmdParser_HandlesNegativeNumbers()
        {
            FakeDeveloperConsole console = new FakeDeveloperConsole();
            CommandParser parser = new CommandParser("-12", console);

            CommandToken token = parser.Tokens[0];
            Assert.AreEqual(CommandTokenKind.Number, token.Kind);
        }
        public void cmdParser_HandlesCodeBlock()
        {
            FakeDeveloperConsole console = new FakeDeveloperConsole();
            CommandParser parser = new CommandParser("{Test()}", console);

            CommandToken token = parser.Tokens[0];
            Assert.AreEqual(CommandTokenKind.CodeBlock, token.Kind);
        }
示例#17
0
        public void Parse_NullCommand_ShouldHaveNoTokens()
        {
            CommandParser parser = new CommandParser();

            var tokens = parser.Parse(null).Tokens.ToArray();

            Assert.IsTrue(tokens.Length == 0);
        }
示例#18
0
        public override CommandParser CreateCustomOpts(CommandParser cli)
        {
            cli.Argument("p", "password",
                         "Password will be passed via environment variable PGPASSWORD; this could be security issue on some systems",
                         "database-password",
                         CommandArgumentFlags.TakesParameter, (p, v) => Options.Add("password", v));

            return cli;
        }
示例#19
0
        public void Parse_OneWordCommand_ShouldHaveOneToken()
        {
            CommandParser parser = new CommandParser();

            var tokens = parser.Parse("test").Tokens.ToArray();

            Assert.IsTrue(tokens.Length == 1);
            Assert.AreEqual("test", tokens[0]);
        }
示例#20
0
		public override void Create(CommandParser Parser)
		{
			Parser.AddCommand(
				new Sequence(
					new KeyWord("GO", true),
					new Cardinal("DIRECTION")),
				new GoProcessor(),
				"Move between rooms.");
		}
示例#21
0
		public override void Create(CommandParser Parser)
		{
			Parser.AddCommand(
				new Or(
					new KeyWord("HELP", false),
					new KeyWord("?", false)),
				new HelpProcessor(),
				"Display a list of all defined commands.");
		}
        public void cmdParser_HandlesDecimalNumbers()
        {
            FakeDeveloperConsole console = new FakeDeveloperConsole();
            CommandParser parser = new CommandParser("12.5", console);

            CommandToken token = parser.Tokens[0];
            Assert.AreEqual(CommandTokenKind.Number, token.Kind);
            Assert.AreEqual("12.5", token.String);
        }
        public void cmdParser_HandlesNegativePrefixedWordAsWord()
        {
            FakeDeveloperConsole console = new FakeDeveloperConsole();
            CommandParser parser = new CommandParser("-hello", console);

            CommandToken token = parser.Tokens[0];
            Assert.AreEqual(CommandTokenKind.Word, token.Kind);
            Assert.AreEqual("-hello", token.String);
        }
示例#24
0
		public override void Create(CommandParser Parser)
		{
			Parser.AddCommand(
				new Sequence(
					new KeyWord("DROP", false),
					new ObjectMatcher("TARGET", new InScopeObjectSource())),
				new DropProcessor(),
				"Drop something");
		}
		public override void Create(CommandParser Parser)
		{
			Parser.AddCommand(
				new Or(
					new KeyWord("i", false),
					new KeyWord("inv", false),
					new KeyWord("inventory", false)),
				new InventoryProcessor(),
				"See what you are carrying.");
		}
示例#26
0
 public void Initialize()
 {
     _Clock = new Mock<IClock>();
     _Console = new Mock<Console> ();
     _MessagePrinter = new MessagePrinter(_Console.Object, _Clock.Object);
     _UserRepository = new UserRepository();
     _MessageRepository = new MessageRepository(_Clock.Object);
     _SubscriptionRepository = new SubscriptionRepository();
     _CommandParser = new CommandParser(GetAllCommands(), _UserRepository, _MessageRepository, _SubscriptionRepository, _MessagePrinter);
 }
示例#27
0
文件: Window.cs 项目: cpdean/di
 public Window(Main _controller, Model.Buffer _model)
 {
     Controller = _controller;
     Model = new Bind<Model.Buffer>(_model);
     CurrentMode = new BindList<WindowMode>();
     CurrentMode.Event.Changed += (list) => { CurrentKeyMap = list.FoldLeft(EmptyKeyMap, (a, b) => a + b.KeyMap); };
     CurrentMode.Add(Controller.WindowModes[0]);
     CurrentMode.Add(Controller.WindowModes[2]);
     CurrentMode.Add(Controller.WindowModes[3]);
     Parser = new CommandParser();
 }
        public void cmdParser_HandlesCSCommand()
        {
            FakeDeveloperConsole console = new FakeDeveloperConsole();
            CommandParser parser = new CommandParser("cs {PED.Velocity = new Vector3( 0, 0 ,1000 ); }", console);

            Assert.AreEqual(CommandTokenKind.Word, parser.Tokens[0].Kind);
            Assert.AreEqual("cs", parser.Tokens[0].String);

            Assert.AreEqual(CommandTokenKind.CodeBlock, parser.Tokens[1].Kind);
            Assert.AreEqual("PED.Velocity = new Vector3( 0, 0 ,1000 ); ", parser.Tokens[1].String);
        }
示例#29
0
        /// <summary>
        /// Initialize interpreter.
        /// </summary>
        /// <param name="factories">The factories.</param>
        /// <param name="input">The input.</param>
        /// <param name="output">The output.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public BaseInterpreter(IEnumerable<ICommandFactory<ConsoleContext<Dungeon>>> factories, TextReader input, TextWriter output, KeyboardStream inputStream)
        {
            if (factories == null || input == null || output == null || inputStream == null)
                throw new ArgumentNullException();

            Input = input;
            Output = output;
            this.inputStream = inputStream;

            parser = new CommandParser<ConsoleContext<Dungeon>>(factories);
        }
        public static void Main()
        {
            var consoleOperator = new ConsoleOperator();
            var httpRequester = new Requester();
            var commandParser = new CommandParser();

            var commandExecutor = new CommandExecutor(httpRequester, consoleOperator);
            var gameEngine = new GameEngine(commandParser, commandExecutor, consoleOperator);

            gameEngine.Run();
        }
        private void btnCreateSite_Click(object sender, RoutedEventArgs e)
        {
            ErrorMessage.Visibility = Visibility.Hidden;
            try
            {
                if (String.IsNullOrEmpty(this.txtSiteName.Text))
                {
                    throw new Exception("Site Name must Not be empty");
                }

                if (String.IsNullOrEmpty(this.txtWebLocation.Text))
                {
                    throw new Exception("Location must Not be empty");
                }

                if (String.IsNullOrEmpty(this.txtPort.Text) ||
                    ((Int32.Parse(this.txtPort.Text) > 65535)))
                {
                    throw new Exception("Port number is not valid it should be in range 0-65535");
                }

                List <string> commandStringList = new List <string>();

                CommandParser cmdParser = new CommandParser(Environment.CurrentDirectory + "\\commands.json");

                Dictionary <string, string[]> CommandsForExecution = new Dictionary <string, string[]>();
                CommandsForExecution.Add("NPMInit", new string[] { });
                CommandsForExecution.Add("NPMInstallPackage", new string[] { "--save express" });
                CommandsForExecution.Add("CmdCreateDirectory", new string[] { "public" });

                foreach (var pair in CommandsForExecution)
                {
                    var com = cmdParser.GetCommand(pair.Key).Generate(pair.Value);
                    commandStringList.Add(com);
                }

                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(this.txtWebLocation.Text, this.txtSiteName.Text));
                CommandLineManager mgr = new CommandLineManager(System.IO.Path.Combine(this.txtWebLocation.Text, this.txtSiteName.Text));
                mgr.Commands = commandStringList;
                mgr.Run();

                //Create QuickStart Scripts
                var moduleDir = System.IO.Path.Combine(this.txtWebLocation.Text,
                                                       this.txtSiteName.Text,
                                                       "nsm-server-config");
                Directory.CreateDirectory(moduleDir);

                var packConfigContent = @"{
                    ""name"":""nsm-server-config"",
                    ""description"":""Server Configuration NSM"",
                    ""version"":""1.0.0"",
                    ""main"":""index.js""
                 }";

                System.IO.File.WriteAllText(System.IO.Path.Combine(moduleDir, "index.js"),
                                            String.Format("module.exports.portNumber = {0}", this.txtPort.Text));

                System.IO.File.WriteAllText(System.IO.Path.Combine(moduleDir, "package.json"), packConfigContent);


                if (this.cmbWebServer.Text.ToLower() == "express")
                {
                    File.Copy(System.IO.Path.Combine(Environment.CurrentDirectory, "QuickStartScripts\\Express.js"),
                              System.IO.Path.Combine(this.txtWebLocation.Text,
                                                     this.txtSiteName.Text,
                                                     "server.js"));
                }

                App.siteManager.CreateSite(new Site
                {
                    SiteId       = Guid.NewGuid().ToString(),
                    SiteName     = this.txtSiteName.Text,
                    SiteLocation = txtWebLocation.Text,
                    SitePort     = Int32.Parse(txtPort.Text),
                    Extensions   = new List <string>()
                });

                App.siteManager.Save();

                ((MainWindow)System.Windows.Application.Current.MainWindow).NavigationFrame.Navigate(new Home());

                OnSitesUpdated(new EventArgs());
            }
            catch (Exception ex)
            {
                ErrorMessage.Visibility = Visibility.Visible;
                ErrorMessage.Content    = ex.Message;
            }
        }
示例#32
0
        void ValidateUpdateQuery(string updateQuery, bool testing = false)
        {
            if (string.IsNullOrEmpty(updateQuery))
            {
                return;
            }

            DataSource ds = new DataSource(DataSourceId, string.Empty);

            updateQuery = new CommandParser(ds).Parse(updateQuery);
            //DoNotClose = false;
            IdpeKey        connectionStringKey    = cmbConnectionString.SelectedItem as IdpeKey;
            DatabaseTypes  databaseType           = connectionStringKey.GetDatabaseType();
            string         actualConnectionString = connectionStringKey.Value;
            IDbConnection  conn        = null;
            IDbTransaction transaction = null;
            IDbCommand     command     = null;

            try
            {
                IDal myDal = new DataAccessLayer(databaseType).Instance;
                conn = myDal.CreateConnection(actualConnectionString);
                conn.Open();
                transaction         = myDal.CreateTransaction(conn);
                command             = myDal.CreateCommand();
                command.Connection  = conn;
                command.Transaction = transaction;
                command.CommandText = updateQuery;

                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                command.ExecuteNonQuery();
                transaction.Rollback();
                if (testing)
                {
                    MessageBox.Show("Successful!", "Test SQL Update Query", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }
                //DoNotClose = true;
                MessageBox.Show("Invalid update query! " + ex.Message,
                                "Invalid Update or Recovery Query", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
                if (transaction != null)
                {
                    transaction.Dispose();
                }
                if (command != null)
                {
                    command.Dispose();
                }
            }
        }
示例#33
0
 public void TestParse__Special__Chained()
 {
     Assert.Equal(Command.Special, CommandParser.Parse("*@PART", out string newName));
     Assert.Equal("@PART", newName);
 }
示例#34
0
        public void HandleManualChange(ushort x, ushort y, ushort z, bool placing,
                                       BlockID block, bool checkPlaceDist)
        {
            BlockID old = level.GetBlock(x, y, z);

            if (old == Block.Invalid)
            {
                return;
            }

            if (jailed || frozen || possessed)
            {
                RevertBlock(x, y, z); return;
            }
            if (!agreed)
            {
                Message(mustAgreeMsg);
                RevertBlock(x, y, z); return;
            }

            if (level.IsMuseum && Blockchange == null)
            {
                return;
            }
            bool deletingBlock = !painting && !placing;

            if (Unverified)
            {
                Authenticator.Current.RequiresVerification(this, "modify blocks");
                RevertBlock(x, y, z); return;
            }

            if (LSGame.Instance.Running && LSGame.Instance.Map == level && LSGame.Instance.IsPlayerDead(this))
            {
                Message("You are out of the round, and cannot build.");
                RevertBlock(x, y, z); return;
            }

            if (ClickToMark && DoBlockchangeCallback(x, y, z, block))
            {
                return;
            }

            bool cancel = false;

            OnBlockChangingEvent.Call(this, x, y, z, block, placing, ref cancel);
            if (cancel)
            {
                return;
            }

            if (old >= Block.Air_Flood && old <= Block.Door_Air_air)
            {
                Message("Block is active, you cannot disturb it.");
                RevertBlock(x, y, z); return;
            }

            if (!deletingBlock)
            {
                PhysicsArgs args = level.foundInfo(x, y, z);
                if (args.HasWait)
                {
                    return;
                }
            }

            if (Rank == LevelPermission.Banned)
            {
                return;
            }
            if (checkPlaceDist)
            {
                int dx = Pos.BlockX - x, dy = Pos.BlockY - y, dz = Pos.BlockZ - z;
                int diff = (int)Math.Sqrt(dx * dx + dy * dy + dz * dz);

                if (diff > ReachDistance + 4)
                {
                    Logger.Log(LogType.Warning, "{0} attempted to build with a {1} distance offset", name, diff);
                    Message("You can't build that far away.");
                    RevertBlock(x, y, z); return;
                }
            }

            if (!CheckManualChange(old, deletingBlock))
            {
                RevertBlock(x, y, z); return;
            }

            BlockID raw = placing ? block : Block.Air;

            block = BlockBindings[block];
            if (ModeBlock != Block.Invalid)
            {
                block = ModeBlock;
            }

            BlockID      newB = deletingBlock ? Block.Air : block;
            ChangeResult result;

            if (old == newB)
            {
                // Ignores updating blocks that are the same and revert block back only to the player
                result = ChangeResult.Unchanged;
            }
            else if (deletingBlock)
            {
                result = DeleteBlock(old, x, y, z);
            }
            else if (!CommandParser.IsBlockAllowed(this, "place", block))
            {
                // Not allowed to place new block
                result = ChangeResult.Unchanged;
            }
            else
            {
                result = PlaceBlock(old, x, y, z, block);
            }

            if (result != ChangeResult.Modified)
            {
                // Client always assumes that the place/delete succeeds
                // So if actually didn't, need to revert to the actual block
                if (!Block.VisuallyEquals(raw, old))
                {
                    RevertBlock(x, y, z);
                }
            }
            OnBlockChangedEvent.Call(this, x, y, z, result);
        }
示例#35
0
        protected override void HandleSet(Player p, RoundsGame game, string[] args)
        {
            ZSConfig    cfg  = ZSGame.Config;
            string      prop = args[1];
            LevelConfig lCfg = p.level.Config;

            if (prop.CaselessEq("map"))
            {
                p.Message("Pillaring allowed: &b" + lCfg.Pillaring);
                p.Message("Build type: &b" + lCfg.BuildType);
                p.Message("Round time: &b{0}" + lCfg.RoundTime.Shorten(true, true));
                return;
            }
            if (args.Length < 3)
            {
                Help(p, "set"); return;
            }

            if (prop.CaselessEq("hitbox"))
            {
                if (!CommandParser.GetReal(p, args[2], "Hitbox detection", ref cfg.HitboxDist, 0, 4))
                {
                    return;
                }
                p.Message("Set hitbox detection to &a" + cfg.HitboxDist + " %Sblocks apart");

                cfg.Save(); return;
            }
            else if (prop.CaselessEq("maxmove"))
            {
                if (!CommandParser.GetReal(p, args[2], "Max move distance", ref cfg.MaxMoveDist, 0, 4))
                {
                    return;
                }
                p.Message("Set max move distance to &a" + cfg.MaxMoveDist + " %Sblocks apart");

                cfg.Save(); return;
            }
            else if (prop.CaselessEq("pillaring"))
            {
                if (!CommandParser.GetBool(p, args[2], ref lCfg.Pillaring))
                {
                    return;
                }

                p.Message("Set pillaring allowed to &b" + lCfg.Pillaring);
                game.UpdateAllStatus2();
            }
            else if (prop.CaselessEq("build"))
            {
                if (!CommandParser.GetEnum(p, args[2], "Build type", ref lCfg.BuildType))
                {
                    return;
                }
                p.level.UpdateBlockPermissions();

                p.Message("Set build type to &b" + lCfg.BuildType);
                game.UpdateAllStatus2();
            }
            else if (prop.CaselessEq("roundtime"))
            {
                if (!ParseTimespan(p, "round time", args, ref lCfg.RoundTime))
                {
                    return;
                }
            }
            else
            {
                Help(p, "set"); return;
            }
            p.level.SaveSettings();
        }
示例#36
0
        public void Parse_GivenValidCommand_CapturesSegment()
        {
            var actual = new CommandParser().Parse("pop static 2");

            Assert.Equal("static", actual.Segment);
        }
示例#37
0
        public void Parse_GivenValidCommand_CapturesKeyword()
        {
            var actual = new CommandParser().Parse("pop static 2");

            Assert.Equal("pop", actual.Keyword);
        }
示例#38
0
 /// <summary>
 /// Initializes a new instance of this class.
 /// </summary>
 /// <param name="commandParser">The parser for the command the option belongs to.</param>
 /// <param name="optionParser">The parser for the option.</param>
 /// <exception cref="ArgumentNullException"><paramref name="commandParser" /> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="optionParser" /> is null.</exception>
 public DecimalOptionSetup(CommandParser <TCommandOptions> commandParser, DecimalOptionParser optionParser) : base(commandParser, optionParser)
 {
 }
 /// <summary>
 /// Initializes a new instance of this class.
 /// </summary>
 /// <param name="commandParser">The parser for the command the option belongs to.</param>
 /// <param name="optionParser">The parser for the option.</param>
 /// <exception cref="ArgumentNullException"><paramref name="commandParser" /> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="optionParser" /> is null.</exception>
 protected SingleValueOptionSetup(CommandParser <TCommandOptions> commandParser, TOptionParser optionParser) : base(commandParser, optionParser)
 {
 }
示例#40
0
 public BotHandler(ITelegramBotClient botClient, ExecutorsFactory factory, UserMessageParser parser, IUserCommandTypeService typeService, IUserCommandStateService stateService, CommandParser commandParser)
 {
     this.botClient           = botClient;
     this.executorsFactory    = factory;
     this.parser              = parser;
     this.commandTypeService  = typeService;
     this.commandStateService = stateService;
     this.commandParser       = commandParser;
 }
示例#41
0
        public override void Use(Player p, string message)
        {
            if (message.Length == 0)
            {
                Player.Message(p, "Map authors: " + p.level.Config.Authors);
                Player.Message(p, "Pillaring allowed: " + p.level.Config.Pillaring);
                Player.Message(p, "Build type: " + p.level.Config.BuildType);
                Player.Message(p, "Min round time: " + p.level.Config.MinRoundTime + " minutes");
                Player.Message(p, "Max round time: " + p.level.Config.MaxRoundTime + " minutes");
                Player.Message(p, "Drawing commands allowed: " + p.level.Config.DrawingAllowed);
                return;
            }

            string[] args = message.SplitSpaces(2);
            if (args.Length == 1)
            {
                Player.Message(p, "You need to provide a value."); return;
            }

            if (args[0].CaselessEq("author") || args[0].CaselessEq("authors"))
            {
                p.level.Config.Authors = args[1].Replace(" ", "%S, ");
                Player.Message(p, "Sets the authors of the map to: " + args[1]);
            }
            else if (args[0].CaselessEq("pillar") || args[0].CaselessEq("pillaring"))
            {
                bool value = false;
                if (!CommandParser.GetBool(p, args[1], ref value))
                {
                    return;
                }

                p.level.Config.Pillaring = value;
                Player.Message(p, "Set pillaring allowed to: " + value);
                HUD.UpdateAllSecondary(Server.zombie);
            }
            else if (args[0].CaselessEq("build") || args[0].CaselessEq("buildtype"))
            {
                BuildType value = BuildType.Normal;
                if (!CommandParser.GetEnum(p, args[1], "Build type", ref value))
                {
                    return;
                }

                p.level.Config.BuildType = value;
                p.level.UpdateBlockPermissions();
                Player.Message(p, "Set build type to: " + value);
                HUD.UpdateAllSecondary(Server.zombie);
            }
            else if (args[0].CaselessEq("minroundtime") || args[0].CaselessEq("minround"))
            {
                byte time = GetRoundTime(p, args[1]);
                if (time == 0)
                {
                    return;
                }

                if (time > p.level.Config.MaxRoundTime)
                {
                    Player.Message(p, "Min round time must be less than or equal to max round time"); return;
                }
                p.level.Config.MinRoundTime = time;
                Player.Message(p, "Set min round time to: " + time + " minutes");
            }
            else if (args[0].CaselessEq("maxroundtime") || args[0].CaselessEq("maxround"))
            {
                byte time = GetRoundTime(p, args[1]);
                if (time == 0)
                {
                    return;
                }

                if (time < p.level.Config.MinRoundTime)
                {
                    Player.Message(p, "Max round time must be greater than or equal to min round time"); return;
                }
                p.level.Config.MaxRoundTime = time;
                Player.Message(p, "Set max round time to: " + time + " minutes");
            }
            else if (args[0].CaselessEq("roundtime") || args[0].CaselessEq("round"))
            {
                byte time = GetRoundTime(p, args[1]);
                if (time == 0)
                {
                    return;
                }

                p.level.Config.MinRoundTime = time;
                p.level.Config.MaxRoundTime = time;
                Player.Message(p, "Set round time to: " + time + " minutes");
            }
            else if (args[0].CaselessEq("drawingallowed") || args[0].CaselessEq("drawingenabled"))
            {
                bool value = false;
                if (!CommandParser.GetBool(p, args[1], ref value))
                {
                    return;
                }

                p.level.Config.DrawingAllowed = value;
                Player.Message(p, "Set drawing commands allowed to: " + value);
            }
            else
            {
                Player.Message(p, "Unrecognised property \"" + args[0] + "\"."); return;
            }
            Level.SaveSettings(p.level);
        }
示例#42
0
 void Start()
 {
     st = new ServerThread(ip, port);
     st.Start();
     parser = this.GetComponent <CommandParser> ();
 }
 /// <summary>
 /// Initializes a new instance of this class.
 /// </summary>
 /// <param name="parser">The parser the command belongs to.</param>
 /// <param name="commandParser">The command parser for the command.</param>
 /// <exception cref="ArgumentException"><paramref name="parser" /> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="commandParser" /> is null.</exception>
 internal NamedCommandSetup(Parser parser, CommandParser <TCommandOptions> commandParser) : base(parser, commandParser)
 {
 }
 /// <summary>
 /// Initializes a new instance of this class.
 /// </summary>
 /// <param name="commandParser">The parser for the command the option belongs to.</param>
 /// <param name="optionParser">The parser for the option.</param>
 /// <exception cref="ArgumentNullException"><paramref name="commandParser" /> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="optionParser" /> is null.</exception>
 public TimeSpanListOptionSetup(CommandParser <TCommandOptions> commandParser, TimeSpanListOptionParser optionParser) : base(commandParser, optionParser)
 {
 }
示例#45
0
 public void TestParse__Create()
 {
     Assert.Equal(Command.Create, CommandParser.Parse("&PART", out string newName));
     Assert.Equal("PART", newName);
 }
        /// <summary>
        /// Init observatory activity. OBSOLETE
        /// </summary>
        public void StartUpObservatory_old()
        {
            //1. Switch on power
            if (ConfigManagement.getBool("scenarioMainParams", "POWER_ON") ?? false)
            {
                Logging.AddLog("StartUp run: Switching power on", LogLevel.Debug);
                CommandParser.ParseSingleCommand2("POWER_MOUNT_ON");
                CommandParser.ParseSingleCommand2("POWER_CAMERA_ON");
                CommandParser.ParseSingleCommand2("POWER_FOCUSER_ON");
            }

            //2.1 Run PHD2
            if (ConfigManagement.getBool("scenarioMainParams", "PHD2_RUN") ?? false)
            {
                Logging.AddLog("StartUp run: Start PHD2", LogLevel.Debug);
                CommandParser.ParseSingleCommand2("PHD2_RUN");
            }

            Thread.Sleep(ConfigManagement.getInt("scenarioMainParams", "PHD_CONNECT_PAUSE") ?? 300);

            //2.2 PHD2 Connect equipment
            if (ConfigManagement.getBool("scenarioMainParams", "PHD2_CONNECT") ?? false)
            {
                Logging.AddLog("StartUp run: connect equipment in PHD2", LogLevel.Debug);
                CommandParser.ParseSingleCommand2("PHD2_CONNECT");
            }

            //2.3 Rub broker app
            if (ConfigManagement.getBool("scenarioMainParams", "PHDBROKER_RUN") ?? false)
            {
                Logging.AddLog("StartUp run: run PHD Broker", LogLevel.Debug);
                CommandParser.ParseSingleCommand2("PHDBROKER_RUN");
            }

            //3. Run MaximDL
            if (ConfigManagement.getBool("scenarioMainParams", "MAXIM_RUN") ?? false)
            {
                Logging.AddLog("StartUp run: Start Maxim DL", LogLevel.Debug);
                CommandParser.ParseSingleCommand2("MAXIM_RUN");
            }


            //3.1. CameraConnect
            if (ConfigManagement.getBool("scenarioMainParams", "MAXIM_CAMERA_CONNECT") ?? false)
            {
                Logging.AddLog("StartUp run: Maxim Camera connect", LogLevel.Debug);
                CommandParser.ParseSingleCommand2("MAXIM_CAMERA_CONNECT");
                //ParentMainForm.AppendLogText("Camera connected");
            }

            //3.2. Set camera cooler
            if (ConfigManagement.getBool("scenarioMainParams", "MAXIM_CAMERA_SETCOOLING") ?? false)
            {
                CommandParser.ParseSingleCommand2("MAXIM_CAMERA_SETCOOLING");
            }

            //3.3. Connect telescope to Maxim
            if (ConfigManagement.getBool("scenarioMainParams", "MAXIM_TELESCOPE_CONNECT") ?? false)
            {
                CommandParser.ParseSingleCommand2("MAXIM_TELESCOPE_CONNECT");
            }

            //4. Run FocusMax
            if (ConfigManagement.getBool("scenarioMainParams", "FOCUSMAX_RUN") ?? false)
            {
                Logging.AddLog("StartUp run: Start Focus Max", LogLevel.Debug);
                CommandParser.ParseSingleCommand2("FOCUSMAX_RUN");
                //ParentMainForm.AppendLogText("FocusMax started");
            }

            //5. Connect focuser in Maxim to FocusMax
            if (ConfigManagement.getBool("scenarioMainParams", "MAXIM_FOCUSER_CONNECT") ?? false)
            {
                CommandParser.ParseSingleCommand2("MAXIM_FOCUSER_CONNECT");
            }

            //Thread.Sleep(2000);

            //6. Run Cartes du Ciel
            if (ConfigManagement.getBool("scenarioMainParams", "CdC_RUN") ?? false)
            {
                CommandParser.ParseSingleCommand2("CdC_RUN");
            }

            //8. Start CCDAP
            if (ConfigManagement.getBool("scenarioMainParams", "CCDAP_RUN") ?? false)
            {
                CommandParser.ParseSingleCommand2("CCDAP_RUN");
            }
            //8. Start CCDC
            if (ConfigManagement.getBool("scenarioMainParams", "CCDC_RUN") ?? false)
            {
                CommandParser.ParseSingleCommand2("CCDC_RUN");
            }

            //7. Connect telescope in Program
            if (ConfigManagement.getBool("scenarioMainParams", "OBS_TELESCOPE_CONNECT") ?? false)
            {
                CommandParser.ParseSingleCommand2("OBS_TELESCOPE_CONNECT");
            }

            Thread.Sleep(ConfigManagement.getInt("scenarioMainParams", "CDC_CONNECT_PAUSE") ?? 0);

            //6.1. Connect telescope in Cartes du Ciel (to give time for CdC to run)
            if (ConfigManagement.getBool("scenarioMainParams", "CdC_TELESCOPE_CONNECT") ?? false)
            {
                CommandParser.ParseSingleCommand2("CdC_TELESCOPE_CONNECT");
            }
        }
示例#47
0
 public void TestParse__Rename()
 {
     Assert.Equal(Command.Rename, CommandParser.Parse("|PART", out string newName));
     Assert.Equal("PART", newName);;
 }
示例#48
0
        protected override DrawOp GetDrawOp(DrawArgs dArgs)
        {
            DrawOp op = null;

            switch (dArgs.Mode)
            {
            case DrawMode.cone:   op = new ConeDrawOp(); break;

            case DrawMode.hcone:  op = new AdvHollowConeDrawOp(); break;

            case DrawMode.icone:  op = new ConeDrawOp(true); break;

            case DrawMode.hicone: op = new AdvHollowConeDrawOp(true); break;

            case DrawMode.pyramid:   op = new AdvPyramidDrawOp(); break;

            case DrawMode.hpyramid:  op = new AdvHollowPyramidDrawOp(); break;

            case DrawMode.ipyramid:  op = new AdvPyramidDrawOp(true); break;

            case DrawMode.hipyramid: op = new AdvHollowPyramidDrawOp(true); break;

            case DrawMode.sphere:  op = new AdvSphereDrawOp(); break;

            case DrawMode.hsphere: op = new AdvHollowSphereDrawOp(); break;

            case DrawMode.volcano: op = new AdvVolcanoDrawOp(); break;

            case DrawMode.hollow:  op = new CylinderDrawOp(); break;
            }
            if (op == null)
            {
                Help(dArgs.Player); return(null);
            }

            AdvDrawMeta meta    = new AdvDrawMeta();
            bool        success = false;

            string[] args = dArgs.Message.SplitSpaces();
            Player   p    = dArgs.Player;

            if (UsesHeight(dArgs))
            {
                if (args.Length < 3)
                {
                    p.Message("You need to provide the radius and the height for the {0}.", args[0]);
                }
                else
                {
                    success = CommandParser.GetInt(p, args[1], "radius", ref meta.radius, 0, 2000) &&
                              CommandParser.GetInt(p, args[2], "height", ref meta.height, 0, 2000);
                }
            }
            else
            {
                if (args.Length < 2)
                {
                    p.Message("You need to provide the radius for the {0}.", args[0]);
                }
                else
                {
                    success = CommandParser.GetInt(p, args[1], "radius", ref meta.radius, 0, 2000);
                }
            }

            if (!success)
            {
                return(null);
            }
            dArgs.Meta = meta;
            return(op);
        }
示例#49
0
 public void TestParse__Edit()
 {
     Assert.Equal(Command.Edit, CommandParser.Parse("@PART", out string newName));
     Assert.Equal("PART", newName);
 }
示例#50
0
 /// <summary>
 /// Initializes a new instance of this class.
 /// </summary>
 /// <param name="commandParser">The parser for the command the option belongs to.</param>
 /// <param name="optionParser">The parser for the option.</param>
 /// <exception cref="ArgumentNullException"><paramref name="commandParser" /> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="optionParser" /> is null.</exception>
 public DateTimeOptionSetup(CommandParser <TCommandOptions> commandParser, DateTimeOptionParser optionParser) : base(commandParser, optionParser)
 {
 }
 public void Initialize()
 {
     commandParser = new CommandParser();
 }
示例#52
0
        public override void Use(Player p, string message, CommandData data)
        {
            if (!Directory.Exists("extra/images/"))
            {
                Directory.CreateDirectory("extra/images/");
            }
            if (message.Length == 0)
            {
                Help(p); return;
            }
            string[] parts = message.SplitSpaces(5);

            DrawArgs dArgs = new DrawArgs();

            dArgs.Pal = ImagePalette.Find("color");
            if (dArgs.Pal == null)
            {
                dArgs.Pal = ImagePalette.Palettes[0];
            }

            if (parts.Length > 1)
            {
                dArgs.Pal = ImagePalette.Find(parts[1]);
                if (dArgs.Pal == null)
                {
                    p.Message("Palette {0} not found.", parts[1]); return;
                }

                if (dArgs.Pal.Entries == null || dArgs.Pal.Entries.Length == 0)
                {
                    p.Message("Palette {0} does not have any entries", dArgs.Pal.Name);
                    p.Message("Use %T/Palette %Sto add entries to it"); return;
                }
            }

            if (parts.Length > 2)
            {
                string mode = parts[2];
                if (mode.CaselessEq("horizontal"))
                {
                    dArgs.Layer = true;
                }
                if (mode.CaselessEq("vertical2layer"))
                {
                    dArgs.Dual = true;
                }
            }

            if (parts.Length > 4)
            {
                if (!CommandParser.GetInt(p, parts[3], "Width", ref dArgs.Width, 1, 1024))
                {
                    return;
                }
                if (!CommandParser.GetInt(p, parts[4], "Height", ref dArgs.Height, 1, 1024))
                {
                    return;
                }
            }

            if (parts[0].IndexOf('.') != -1)
            {
                dArgs.Data = HttpUtil.DownloadImage(parts[0], p);
                if (dArgs.Data == null)
                {
                    return;
                }
            }
            else
            {
                string path = "extra/images/" + parts[0] + ".bmp";
                if (!File.Exists(path))
                {
                    p.Message("{0} does not exist", path); return;
                }
                dArgs.Data = File.ReadAllBytes(path);
            }

            p.Message("Place or break two blocks to determine direction.");
            p.MakeSelection(2, "Selecting direction for %SImagePrint", dArgs, DoImage);
        }
 /// <summary>
 /// Initializes a new instance of this class.
 /// </summary>
 /// <param name="commandParser">The parser for the command the option belongs to.</param>
 /// <param name="optionParser">The parser for the option.</param>
 /// <exception cref="ArgumentNullException"><paramref name="commandParser" /> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="optionParser" /> is null.</exception>
 public BooleanOptionSetup(CommandParser <TCommandOptions> commandParser, BooleanOptionParser optionParser) : base(commandParser, optionParser)
 {
 }
示例#54
0
        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();

            ILocalConfigManager configManager = new LocalConfigManager();

            configManager.AdjustPortValues();

            ICommunicationManager communicationManager = new CommunicationManager(configManager);

            ICommandParser commandParser = new CommandParser(configManager);

            communicationManager.OnMessage    += msg => Console.WriteLine($"Msg from app: {msg}");
            communicationManager.OnAppStarted += msg => _appLoaded = true;
            communicationManager.Start();

            ConsoleProcess consoleProcess = new ConsoleProcess(commandParser.ParseCommand(), bool.Parse(configManager.GetConfig(LocalConfigKeys.ShowCmd)));

            consoleProcess.ExecuteCommand();

            long connectionTimeout     = long.Parse(configManager.GetConfig(LocalConfigKeys.AppStartTimeout));
            long connectionElapsedTime = 0L;

            while (!_appLoaded)
            {
                connectionElapsedTime += 1;
                Thread.Sleep(1);

                if (connectionElapsedTime > connectionTimeout)
                {
                    MessageBox.Show("App was not started", "Error");
                    consoleProcess.Kill();
                    return;
                }
            }

            InitCef();
            //TODO: add utility class for this.
            BrowserForm form = new BrowserForm(commandParser.ParseBaseUrl())
            {
                Width       = int.Parse(configManager.GetConfig(LocalConfigKeys.WindowWidth)),
                Height      = int.Parse(configManager.GetConfig(LocalConfigKeys.WindowHeight)),
                WindowState = bool.Parse(configManager.GetConfig(LocalConfigKeys.WindowMaximizedState)) ? FormWindowState.Maximized : FormWindowState.Normal
            };

            form.SizeChanged += (sender, eventArgs) =>
            {
                configManager.SetConfig(LocalConfigKeys.WindowWidth, form.Width.ToString());
                configManager.SetConfig(LocalConfigKeys.WindowHeight, form.Height.ToString());
            };

            form.FormClosing += (sender, eventArgs) =>
            {
                configManager.SetConfig(LocalConfigKeys.WindowMaximizedState, (form.WindowState == FormWindowState.Maximized).ToString());
                configManager.Save();
                communicationManager.SendStopMessage();
                consoleProcess.Kill();
                Environment.Exit(0);
            };

            Application.Run(form);
        }
示例#55
0
        void EditPreset(Player p, string[] args, LevelPreset preset)
        {
            if (preset == null)
            {
                p.Message("%WThat preset level doesn't exist"); return;
            }

            if (args[3] == "name" || args[3] == "title")
            {
                preset.name = args[4];
                p.Message("&aSuccessfully changed preset name to &f" + preset.name);
            }
            else if (args[3] == "x" || args[3] == "y" || args[3] == "z")
            {
                string[] dims = new string[] { preset.x, preset.y, preset.z };
                if (args[3] == "x")
                {
                    dims[0] = args[4];
                }
                if (args[3] == "y")
                {
                    dims[1] = args[4];
                }
                if (args[3] == "z")
                {
                    dims[2] = args[4];
                }

                ushort x = 0, y = 0, z = 0;
                if (!CmdNewLvl.GetDimensions(p, dims, 0, ref x, ref y, ref z))
                {
                    return;
                }
                preset.x = dims[0]; preset.y = dims[1]; preset.z = dims[2];

                p.Message("&aSuccessfully changed preset {0} size to &f{1}", args[3], args[4]);
            }
            else if (args[3] == "type" || args[3] == "theme")
            {
                if (MapGen.Find(args[4]) == null)
                {
                    MapGen.PrintThemes(p); return;
                }

                preset.type = args[4];
                p.Message("&aSuccessfully changed preset type to &f" + preset.type);
            }
            else if (args[3] == "price")
            {
                int newPrice = 0;
                if (!CommandParser.GetInt(p, args[4], "Price", ref newPrice, 0))
                {
                    return;
                }

                preset.price = newPrice;
                p.Message("&aSuccessfully changed preset price to &f" + preset.price + " &3" + ServerConfig.Currency);
            }
            else
            {
                p.Message("Supported properties to edit: name, title, x, y, z, type, price");
            }
        }
示例#56
0
 private void AddUpcomingIMCommands(CommandParser showUpcomingParser)
 {
     showUpcomingParser.AddCommand("recordings", "r", delegate(IMBotConversation conversation, IList <string> arguments) { return(DoShowUpcomingCommand(conversation, ScheduleType.Recording)); });
     showUpcomingParser.AddCommand("alerts", "a", delegate(IMBotConversation conversation, IList <string> arguments) { return(DoShowUpcomingCommand(conversation, ScheduleType.Alert)); });
     showUpcomingParser.AddCommand("suggestions", "s", delegate(IMBotConversation conversation, IList <string> arguments) { return(DoShowUpcomingCommand(conversation, ScheduleType.Suggestion)); });
 }
示例#57
0
        static void Main(string[] args)
        {
            string strInput         = "";
            string strParentDir     = "";
            string strTestTableName = "jive";

            int intWindowWidth = 160;

            try
            {
                Console.SetWindowSize(intWindowWidth, 50);
            }
            catch (Exception)
            {
                Console.WriteLine("Screen doesn't support chosen console window dimensions.");
            }

            DatabaseContext dbTemp = null;

            Console.SetIn(new StreamReader(Console.OpenStandardInput(4096)));
            Console.WriteLine(@"SqlDb# ISQL client. 
SqlDb# version: " + MainClass.version + @"

Type one or more statements terminated by semi-colons and then a period on a line by itself to execute.
Type only a period on a line by itself to quit.

You may set a start-up database by including the full path on a single line in a file called 
SqlDbSharp.config, placed in this folder:

     " + Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"
");

            string strConfigFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SqlDbSharp.config");

            if (File.Exists(strConfigFile))
            {
                strParentDir = File.ReadAllText(strConfigFile);
                strParentDir = strParentDir.TrimEnd(System.Environment.NewLine.ToCharArray());
            }
            else
            {
                // set up debug db
                Console.WriteLine("Starting at testing dir: MooresDbPlay");
                strParentDir = Utils.cstrHomeDir + System.IO.Path.DirectorySeparatorChar + "MooresDbPlay";
            }

            dbTemp = new DatabaseContext(strParentDir);
            Console.WriteLine("Current home dir: " + strParentDir + "\n\n");
            // eo setup debug db

            string strCmd = "";

            while (!strCmd.Trim().Equals("."))
            {
                strInput = "";
                strCmd   = "";

                try
                {
                    // Put the command together.
                    Console.Write("SqlDbSharp> ");
                    while (!strInput.Equals("."))
                    {
                        strInput = Console.ReadLine();

                        if (strInput.Contains("--"))
                        {
                            strInput = strInput.Substring(0, strInput.IndexOf("--"));
                        }
                        strCmd += strInput + " ";
                    }

                    if (!strCmd.Trim().Equals("."))
                    {
                        Queue <string> qCmds = strCmd.Trim(' ').Trim('.').SplitSeeingSingleQuotesAndBackticks(";", true);

                        foreach (string strSingleCommand in qCmds)
                        {
                            strCmd = strSingleCommand.Substring(0, strSingleCommand.LastIndexOf(";") + 1).Trim();    // kinda kludging to reuse code for now.

                            // I'm going to cheat and set up some test strings,
                            // just to save some typing.
                            // Ob remove when live.
                            switch (strCmd)
                            {
                            case "test usage;":
                                DatabaseContext database = new DatabaseContext(@"C:\temp\DatabaseName");     // or Mac path, etc.
                                CommandParser   parser   = new CommandParser(database);
                                string          sql      = @"CREATE TABLE TestTable (
                                            ID INTEGER (4) AUTOINCREMENT,
                                            CITY CHAR (10));";
                                parser.executeCommand(sql);
                                parser.executeCommand("INSERT INTO TestTable (CITY) VALUES ('New York');");
                                parser.executeCommand("INSERT INTO TestTable (CITY) VALUES ('Boston');");
                                parser.executeCommand("INSERT INTO TestTable (CITY) VALUES ('Fuquay');");
                                sql = "SELECT * FROM TestTable;";
                                DataTable dataTable = (DataTable)parser.executeCommand(sql);
                                Console.WriteLine(InfrastructureUtils.dataTableToString(dataTable));
                                parser.executeCommand("DROP TABLE TestTable;");

                                strCmd = "";
                                goto case "goto kludge";

                            case "test create;":
                                strTestTableName = "jive" + DateTime.Now.Ticks;
                                strCmd           = @"create TABLE " + strTestTableName + @"
                                        (ID INTEGER (4) AUTOINCREMENT,
                                        CITY CHAR (10),
                                        STATE CHAR (2),
                                        LAT_N REAL (5),
                                        LONG_W REAL (5),
                                        TIMESTAMP DATETIME(8));";
                                goto case "goto kludge";

                            case "test create2;":
                                strTestTableName = "rest" + DateTime.Now.Ticks;
                                strCmd           = @"create TABLE " + strTestTableName + @"
                                        (
                                        ID INTEGER (4) AUTOINCREMENT,
                                        CityId INTEGER (4),
                                        Name CHAR (30)
                                        );";
                                goto case "goto kludge";

                            case "test select;":
                                strCmd = @"SELECT ID, CITY, LAT_N FROM "
                                         + strTestTableName + @"
                                        INNER JOIN rest
                                        ON jive.Id = rest.CityId
                                        WHERE city = 'Chucktown' AND LAT_N > 32;";
                                goto case "goto kludge";

                            case "test insert;":
                                strCmd = @"INSERT INTO " + strTestTableName + @" (CITY, STATE, LAT_N, LONG_W, TIMESTAMP)
                                        VALUES ('Chucktown', 'SC', 32.776, 79.931, '12/12/2001');";
                                goto case "goto kludge";

                            case "insert2;":
                                strCmd = @"INSERT INTO " + strTestTableName + @" (CITY, LAT_N, LONG_W, TIMESTAMP) VALUES ('Chucktown', 32.776, 79.931, '11/11/2011');";
                                goto case "goto kludge";

                            case "test drop;":
                                strCmd = @"DROP TABLE " + strTestTableName + @";";
                                goto case "goto kludge";

                            case "test update;":
                                strCmd = @"UPDATE jive SET city = 'Gotham', LAT_N = 45.987 WHERE ID = 4;";
                                goto case "goto kludge";

                            // Okay, Lippert doesn't say to use it quite like this, but he did give me the idea:
                            // http://blogs.msdn.com/b/ericlippert/archive/2009/08/13/four-switch-oddities.aspx
                            case "goto kludge":
                                Console.WriteLine("Test cmd:" + Environment.NewLine + strCmd);
                                break;
                            }

                            // Execute the command.
                            if (strCmd.ToLower().StartsWith("use"))
                            {
                                string strDbPath = strCmd.Split()[1].TrimEnd(';');
                                // Complete kludge.  Use regexp and check for xplat formats.
                                if (strDbPath.StartsWith(@"C:\"))
                                {
                                    strParentDir = strDbPath;
                                }
                                else
                                {
                                    strParentDir = Utils.cstrHomeDir + System.IO.Path.DirectorySeparatorChar + strDbPath;
                                }
                                dbTemp = new DatabaseContext(strParentDir);
                                Console.WriteLine(strParentDir);
                            }
                            else if (strParentDir.Equals(""))
                            {
                                Console.WriteLine("Please select a database before executing a statement.");
                            }
                            else
                            {
                                try
                                {
                                    CommandParser parser    = new CommandParser(dbTemp);
                                    object        objResult = parser.executeCommand(strCmd);

                                    if (objResult is DataTable)
                                    {
                                        Console.WriteLine(InfrastructureUtils.dataTableToString((DataTable)objResult, intWindowWidth - 1));
                                    }
                                    else if (objResult is string)
                                    {
                                        Console.WriteLine(objResult.ToString());
                                    }
                                    else if (strCmd.Trim().ToUpper().StartsWith("INSERT"))
                                    {
                                        Console.WriteLine("Row ID for new row is: " + objResult);
                                    }
                                    else if (strCmd.Trim().ToUpper().StartsWith("SELECT MAX("))
                                    {
                                        Console.WriteLine(objResult.ToString());
                                    }
                                    else
                                    {
                                        Console.WriteLine("Uncaptured return value.");
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Error executing statement.\n\t" + e.Message);
                                }
                            }
                        }   // end of "foreach" command in the split commands queue.
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Something borked: " + ex.ToString());
                    strParentDir = "";
                }
                Console.WriteLine(System.Environment.NewLine + System.Environment.NewLine);
            }
        }
示例#58
0
 public Engine(CommandParser commandParser, StudentSystem studentSystem, Func <string> readInput)
 {
     this.commandParser = commandParser;
     this.studentSystem = studentSystem;
     this.readInput     = readInput;
 }
示例#59
0
 static string ParseModelScale(Player dst, Entity entity, string model, string argName, ref float value)
 {
     string[] bits = model.SplitSpaces();
     CommandParser.GetReal(dst, bits[1], argName, ref value, 0, 3);
     return(entity.Model);
 }
示例#60
0
        public void Parse_GivenValidCommand_CapturesIndex()
        {
            var actual = new CommandParser().Parse("pop static 2");

            Assert.Equal("2", actual.Index);
        }