示例#1
0
		private void RegisterFireBallCommand()
		{
			var command = new Command(FireBallFromPaddle);
			command.Add(new KeyTrigger(Key.Space));
			command.Add(new MouseButtonTrigger());
			command.Add(new GamePadButtonTrigger(GamePadButton.A));
		}
示例#2
0
		private void RegisterButtonCommands()
		{
			var left = new Command(() => xPosition -= PaddleMovementSpeed * Time.Delta);
			left.Add(new KeyTrigger(Key.CursorLeft, State.Pressed));
			left.Add(new GamePadButtonTrigger(GamePadButton.Left, State.Pressed));
			var right = new Command(() => xPosition += PaddleMovementSpeed * Time.Delta);
			right.Add(new KeyTrigger(Key.CursorRight, State.Pressed));
			right.Add(new GamePadButtonTrigger(GamePadButton.Right, State.Pressed));
		}
示例#3
0
 public void Run(Type resolver)
 {
     Start(resolver, (InputCommands input) =>
     {
         var command = new Command();
         command.Add(new KeyTrigger(Key.Y, State.Releasing));
         command.Run(input);
     });
 }
 protected override void OnGameStart()
 {
     Command registerCom = new Command(RegisterCode);
     registerCom.Add<DefaultData> (new DefaultData(DataType.Int, ClientManager.ClientID));
     for (int i = 0; i < 1; i++)
     {
         CommandManager.SendCommand(registerCom);
     }
 }
 public Command GenerateTransitionCommand () {
     Cover cover = CoverManager.FindCover(CachedTurn.GetBodiesInLine(FixedMath.One * 200),CurrentCover);
     if (cover != null) {
         Command com = new Command(this.Data.ListenInputID,this.Agent.Controller.ControllerID);
         com.Add<DefaultData> (new DefaultData(DataType.UShort,cover.ID));
         return com;
     }
     return null;
 }
 public Command GenerateMoveCommand(Vector2 input)
 {
     Command com = new Command(this.Data.ListenInputID, this.Agent.Controller.ControllerID);
     Vector2d vec = (new Vector2d(input));
     if (vec.FastMagnitude () > FixedMath.One * FixedMath.One) {
         vec.Normalize();
     }
     com.Add<Vector2d>(vec);
     return com;
 }
示例#7
0
 public void AddAndRemoveTrigger(Type resolver)
 {
     Start(resolver, (InputCommands input) =>
     {
         var command = new Command();
         var trigger = new MouseButtonTrigger(MouseButton.Left, State.Releasing);
         command.Add(trigger);
         Assert.AreEqual(1, command.attachedTriggers.Count);
         command.Remove(trigger);
         Assert.AreEqual(0, command.attachedTriggers.Count);
     });
 }
示例#8
0
 public void SimulateKeyPress(Type resolver)
 {
     Start(resolver, (InputCommands input) =>
     {
         var command = new Command();
         input.Add(command);
         command.Add(new KeyTrigger(Key.A, State.Pressed));
         bool triggered = false;
         command.Attach(trigger => triggered = true);
         if (testResolver != null)
         {
             testResolver.SetKeyboardState(Key.A, State.Pressed);
             testResolver.AdvanceTimeAndExecuteRunners(0.1f);
             Assert.IsTrue(triggered);
         }
     });
 }
    // move to build ability?
    public void StartConstruction()
    {
        findingPlacement = false;
        Vector2d buildPoint  = new Vector2d(tempBuilding.transform.position.x, tempBuilding.transform.position.z);
        RTSAgent newBuilding = cachedCommander.CachedController.CreateAgent(tempBuilding.gameObject.name, buildPoint, Vector2d.right) as RTSAgent;

        Destroy(tempBuilding.gameObject);

        newBuilding.SetState(AnimState.Building);
        newBuilding.RestoreMaterials();
        newBuilding.SetPlayingArea(tempCreator.GetPlayerArea());
        newBuilding.GetAbility <Health>().HealthAmount = FixedMath.Create(0);
        newBuilding.SetCommander();

        // send build command
        Command buildCom = new Command(AbilityDataItem.FindInterfacer("Construct").ListenInputID);

        buildCom.Add <DefaultData>(new DefaultData(DataType.UShort, newBuilding.GlobalID));
        UserInputHelper.SendCommand(buildCom);

        newBuilding.GetAbility <Structure>().StartConstruction();
        // check that the Player has the resources available before allowing them to create a new Unit / Building
        cachedCommander.RemoveResource(ResourceType.Gold, newBuilding.cost);
    }
示例#10
0
        public void PropertyInfo_can_be_bound_to_option()
        {
            var command = new Command("the-command");
            var option  = new Option("--fred")
            {
                Argument = new Argument <int>()
            };

            command.Add(option);

            var type         = typeof(ClassWithMultiLetterSetters);
            var binder       = new ModelBinder(type);
            var propertyInfo = type.GetProperties().First();

            binder.BindMemberFromValue(
                propertyInfo,
                option);

            var bindingContext = new BindingContext(command.Parse("the-command --fred 42"));

            var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext);

            instance.IntOption.Should().Be(42);
        }
            public void When_position_is_unspecified_in_array_command_line_and_final_token_is_unmatched_then_it_returns_final_token()
            {
                IReadOnlyCollection <Symbol> symbols = new[]
                {
                    new Option("--option1"),
                    new Option("--option2")
                };
                var command1 = new Command(
                    "the-command",
                    ""
                    );

                foreach (var symbol in symbols)
                {
                    command1.Add(symbol);
                }

                var command = command1;

                string textToMatch = command.Parse("the-command", "opt")
                                     .TextToMatch();

                textToMatch.Should().Be("opt");
            }
示例#12
0
        public Main()
        {
            InitializeComponent();

            m_CommandManager = new CommandManager(StatusBarHintChanged);

            Command cmd = m_CommandManager.Create("IgnoreCase", null, null);

            cmd.Add(IgnoreCaseMenu);
            cmd.Add(IgnoreCaseButton);

            cmd = m_CommandManager.Create("Open", Open, null);
            cmd.Add(OpenMenu);
            cmd.Add(OpenButton);

            cmd = m_CommandManager.Create("Multiline", null, null);
            cmd.Add(MultilineMenu);
            cmd.Add(MultilineButton);
        }
示例#13
0
        public void AddCommand(Command rootCommand)
        {
            var cmd = new Command("Unblock", "Unblocks one person, a group of people or everyone");

            cmd.AddAlias("unblock");
            cmd.AddAlias("un");

            var dryRunOption = new Option <bool>("--dryrun", "Does not actually make the changes");

            cmd.Add(dryRunOption);

            var targetOption = new Option <string>("--target", "If unblocking one person, this is their name");

            targetOption.AddAlias("-t");
            targetOption.Name = "targetUsername";
            cmd.Add(targetOption);

            var allOption = new Option <bool>("--all", "Unblocks everyone you have blocked");

            allOption.Name = "all";
            cmd.Add(allOption);

            var fileOption = new Option <string>("--file", "Unblocks from a file");

            fileOption.AddAlias("-f");
            fileOption.Name = "file";
            cmd.Add(fileOption);

            var logOption = new Option <bool>("--log", "Creates (or appends if the file exists) a log of all the " +
                                              "accounts impacted by the unblocking");

            logOption.Name = "log";
            logOption.AddAlias("-l");
            cmd.Add(logOption);

            var unmuteOption = new Option <bool>("--unmute", "Rather than unblocking, this command will unmute the targets");

            cmd.Add(unmuteOption);

            cmd.Handler = CommandHandler.Create <bool, string, bool, string, bool, bool>(this.Execute);
            rootCommand.Add(cmd);
        }
示例#14
0
        public static Command CreateCommand()
        {
            Command command = new Command("show", "Show information about a DLC");

            command.AddOption(new Option <bool>("--json", "Output in json")
            {
                IsRequired = false,
            });
            command.AddOption(new Option <bool>("--psbt", "Output transactions as PSBT")
            {
                IsRequired = false,
            });
            command.Add(new Argument <string>("name", "The name of the DLC")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            command.Add(new Option <bool>("--offer", "Show the offer message of the DLC")
            {
                IsRequired = false
            });
            command.Add(new Option <bool>("--accept", "Show the accept message of the DLC")
            {
                IsRequired = false
            });
            command.Add(new Option <bool>("--funding", "Show the funding PSBT of the DLC")
            {
                IsRequired = false
            });
            command.Add(new Option <bool>("--refund", "Show the refund transaction of the DLC.")
            {
                IsRequired = false
            });
            command.Add(new Option <bool>("--abort", "Show the abort PSBT of the DLC")
            {
                IsRequired = false
            });
            command.Handler = new ShowDLCCommand();
            return(command);
        }
示例#15
0
        public static RootCommand WireUpSha256Commands(this RootCommand rootCommand)
        {
            var sha256Command     = new Command("sha256", "SHA256");
            var sha256HashCommand = new Command("hash", "Hash");

            sha256HashCommand.AddOption(new Option(new string[] { "--text", "-t" }, "Input Text")
            {
                Argument = new Argument <string>("text")
            });
            sha256HashCommand.AddOption(new Option(new string[] { "--input", "-i" }, "Input file path")
            {
                Argument = new Argument <FileInfo>("input")
            });
            sha256HashCommand.AddOption(new Option(new string[] { "--output", "-o" }, "Output file path")
            {
                Argument = new Argument <FileInfo>("output")
            });
            sha256HashCommand.Handler = CommandHandler.Create <string, FileInfo, FileInfo, IConsole>(async(text, input, output, console) =>
            {
                Stream outputStream = null;
                Stream inputStream  = null;
                try
                {
                    if (output == null)
                    {
                        outputStream = new MemoryStream();
                    }
                    else
                    {
                        outputStream = output.OpenWrite();
                    }

                    if (text != null)
                    {
                        inputStream = new MemoryStream(Encoding.UTF8.GetBytes(text));
                    }
                    if (input != null)
                    {
                        inputStream = input.OpenRead();
                    }

                    using var sha256 = SHA256.Create();
                    var hashBytes    = sha256.ComputeHash(inputStream);
                    if (output == null)
                    {
                        console.Out.WriteLine(hashBytes.ToHexString());
                    }
                    else
                    {
                        await outputStream.WriteAsync(hashBytes);
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                }
                finally
                {
                    if (inputStream != null)
                    {
                        await inputStream.DisposeAsync();
                    }
                    if (outputStream != null)
                    {
                        await outputStream.DisposeAsync();
                    }
                }
            });

            sha256Command.Add(sha256HashCommand);
            rootCommand.AddCommand(sha256Command);

            return(rootCommand);
        }
 public Command GenerateMovementCommand (float input) {
     if (this.IsTransitioning) return null;
     Command com = new Command(this.Data.ListenInputID,this.Agent.Controller.ControllerID);
     com.Add<DefaultData> (new DefaultData(DataType.Long,FixedMath.Create(input)));
     return com;
 }
示例#17
0
        public static RootCommand WireUpHmacMd5Commands(this RootCommand rootCommand)
        {
            var hmacmd5Command     = new Command("hmacmd5", "Hash based Message Authentication Code - MD5");
            var hmacmd5HashCommand = new Command("hash", "Hash");

            hmacmd5HashCommand.AddOption(new Option <string>(new string[] { "--text", "-t" }, "Input Text"));
            hmacmd5HashCommand.AddOption(new Option <FileInfo>(new string[] { "--input", "-i" }, "Input file path"));
            hmacmd5HashCommand.AddOption(new Option <string>(new string[] { "--keytext", "-kt" }, "Key Text"));
            hmacmd5HashCommand.AddOption(new Option <FileInfo>(new string[] { "--keyinput", "-ki" }, "Key file path"));
            hmacmd5HashCommand.AddOption(new Option <FileInfo>(new string[] { "--output", "-o" }, "Output file path"));

            hmacmd5HashCommand.Handler = CommandHandler.Create <string, FileInfo, string, FileInfo, FileInfo, IConsole>(async(text, input, keytext, keyinput, output, console) =>
            {
                Stream outputStream = null;
                Stream inputStream  = null;
                try
                {
                    if (text != null)
                    {
                        inputStream = new MemoryStream(Encoding.UTF8.GetBytes(text));
                    }
                    if (input != null)
                    {
                        inputStream = input.OpenRead();
                    }

                    byte[] key = null;

                    if (keytext != null)
                    {
                        key = Encoding.UTF8.GetBytes(keytext);
                    }

                    if (keyinput != null)
                    {
                        key = await File.ReadAllBytesAsync(keyinput.FullName).ConfigureAwait(false);
                    }

                    using var hmacMd5 = new HMACMD5(key);
                    var hashBytes     = hmacMd5.ComputeHash(inputStream);
                    if (output == null)
                    {
                        console.Out.WriteLine(hashBytes.ToHexString());
                    }
                    else
                    {
                        outputStream = output.OpenWrite();
                        await outputStream.WriteAsync(hashBytes).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                    return(22);
                }
                finally
                {
                    if (inputStream != null)
                    {
                        await inputStream.DisposeAsync().ConfigureAwait(false);
                    }
                    if (outputStream != null)
                    {
                        await outputStream.DisposeAsync().ConfigureAwait(false);
                    }
                }
                return(0);
            });

            hmacmd5Command.Add(hmacmd5HashCommand);
            rootCommand.AddCommand(hmacmd5Command);

            return(rootCommand);
        }
示例#18
0
文件: Program.cs 项目: nicobst/NDLC
        public static RootCommand CreateCommand()
        {
            RootCommand root = new RootCommand();

            root.Description = "A simple tool to manage DLCs.\r\nTHIS IS EXPERIMENTAL, USE AT YOUR OWN RISKS!";
            root.Add(new Option <string>("--network", "The network type (mainnet, testnet or regtest)")
            {
                Argument   = new Argument <string>(),
                IsRequired = false
            });
            root.Add(new Option <string>("--datadir", "The data directory")
            {
                Argument   = new Argument <string>(),
                IsRequired = false
            });

            Command info = new Command("info", "Show informations");

            root.Add(info);
            info.Handler = new ShowInfoCommand();

            Command offer = new Command("offer", "Manage offers");

            root.Add(offer);
            offer.Description = "Manage offers";
            Command createOffer = new Command("create")
            {
                Description = "Create a new offer",
            };

            offer.Add(createOffer);
            createOffer.Description = "Create a new offer";
            createOffer.Add(new Option <string>("--oraclepubkey")
            {
                Argument    = new Argument <string>(),
                Description = "The oracle's public key",
                IsRequired  = true
            });
            createOffer.Add(new Option <string>("--nonce")
            {
                Argument    = new Argument <string>(),
                Description = "The oracle's commitment for this bet",
                IsRequired  = true
            });
            createOffer.Add(new Option <string[]>("--outcome")
            {
                Argument = new Argument <string[]>()
                {
                    Arity = ArgumentArity.OneOrMore
                },
                Description = "The outcomes of the contract (one or multiple)",
                IsRequired  = true
            });
            createOffer.Add(new Option <string>("--maturity")
            {
                Argument    = new Argument <string>(),
                Description = "The timelock of the contract execution transactions (default: 0)",
                IsRequired  = false
            });
            createOffer.Add(new Option <string>("--expiration")
            {
                Argument    = new Argument <string>(),
                Description = "The timelock on the refund transaction",
                IsRequired  = true
            });
            createOffer.Handler = new CreateOfferCommand();


            Command oracle    = new Command("oracle", "Oracle commands");
            Command oracleAdd = new Command("add", "Add a new oracle")
            {
                new Argument <string>("name", "The oracle name"),
                new Argument <string>("pubkey", "The oracle pubkey"),
            };

            oracleAdd.Handler = new AddSetOracleCommand();
            Command oracleSet = new Command("set", "Modify an oracle")
            {
                new Argument <string>("name", "The oracle name"),
                new Argument <string>("pubkey", "The oracle pubkey"),
            };

            oracleSet.Handler = new AddSetOracleCommand()
            {
                Set = true
            };
            Command oracleRemove = new Command("remove", "Remove an oracle")
            {
                new Argument <string>("name", "The oracle name")
            };

            oracleRemove.Handler = new RemoveOracleCommand();
            Command oracleList = new Command("list", "List oracles");

            oracleList.Handler = new ListOracleCommand();
            Command oracleShow = new Command("show", "Show an oracle")
            {
                new Argument <string>("name", "The oracle name")
            };

            oracleShow.Add(new Option <bool>("--show-sensitive", "Show sensitive informations (like private keys)"));
            oracleShow.Handler = new ShowOracleCommand();
            Command oracleCreate = new Command("generate", "Generate a new oracle (the private key will be stored locally)")
            {
                new Argument <string>("name", "The oracle name")
            };

            oracleCreate.Handler = new GenerateOracleCommand();
            root.Add(oracle);
            oracle.Add(oracleAdd);
            oracle.Add(oracleSet);
            oracle.Add(oracleRemove);
            oracle.Add(oracleList);
            oracle.Add(oracleShow);
            oracle.Add(oracleCreate);

            Command evts     = new Command("event", "Manage events");
            Command addEvent = new Command("add", "Add a new event");

            addEvent.Add(new Argument <string>("name", "The event full name, in format 'oraclename/name'")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            addEvent.Add(new Argument <string>("nonce", "The event nonce, as specified by the oracle")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            addEvent.Add(new Argument <string>("outcomes", "The outcomes, as specified by the oracle")
            {
                Arity = ArgumentArity.OneOrMore
            });
            addEvent.Handler = new AddEventCommand();
            Command listEvent = new Command("list", "List events");

            listEvent.Add(new Option <string>("--oracle", "Filter events of this specific oracle")
            {
                Argument = new Argument <string>()
                {
                    Arity = ArgumentArity.ExactlyOne
                },
                IsRequired = false
            });
            listEvent.Handler = new ListEventsCommand();
            Command showEvents = new Command("show", "Show details of an event");

            showEvents.Add(new Argument <string>("name", "The full name of the event"));
            showEvents.Handler = new ShowEventCommand();

            Command generateEvents = new Command("generate", "Generate a new event");

            generateEvents.Add(new Argument <string>("name", "The event full name, in format 'oraclename/name'")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            generateEvents.Add(new Argument <string>("outcomes", "The outcomes, as specified by the oracle")
            {
                Arity = ArgumentArity.OneOrMore
            });
            generateEvents.Handler = new GenerateEventCommand();

            Command attestEvent     = new Command("attest", "Attest an event");
            Command attestSignEvent = new Command("sign", "Sign an attestation");

            attestSignEvent.Add(new Argument <string>("name", "The event full name, in format 'oraclename/name'")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            attestSignEvent.Add(new Argument <string>("outcome", "The outcome to attest")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            attestSignEvent.Add(new Option <bool>(new[] { "--force", "-f" }, "Force this action")
            {
                Argument   = new Argument <bool>(),
                IsRequired = false
            });
            attestSignEvent.Handler = new AttestSignCommand();
            Command attestAddEvent = new Command("add", "Add an attestation received by an oracle");

            attestAddEvent.Add(new Argument <string>("name", "The event full name, in format 'oraclename/name'")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            attestAddEvent.Add(new Argument <string>("attestation", "The received attestation")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            attestAddEvent.Handler = new AttestAddCommand();
            attestEvent.Add(attestAddEvent);
            attestEvent.Add(attestSignEvent);
            root.Add(evts);
            evts.Add(addEvent);
            evts.Add(listEvent);
            evts.Add(showEvents);
            evts.Add(generateEvents);
            evts.Add(attestEvent);

            Command reviewOffer = new Command("review", "Review an offer");

            offer.Add(reviewOffer);
            reviewOffer.AddOption(new Option <bool>(new[] { "-h", "--human" }, "Show the offer in a human readable way"));
            reviewOffer.AddArgument(new Argument <string>("offer", "The JSON offer to review")
            {
                Arity = ArgumentArity.ExactlyOne
            });
            reviewOffer.Handler = new ReviewOfferCommand();
            return(root);
        }
 public void SendCommand(Command com, bool immediate = false)
 {
     if (com == null)
         return;
     if (Agent.Controller.SelectionChanged)
         com.Add(new Selection(Agent.Controller.SelectedAgents));
     CommandManager.SendCommand(com, false);
     if (immediate) sendOut = true;
 }
        internal static Command Verbose(this Command command)
        {
            command.Add(new Option(new[] { "-v", "--verbose" }, "Show verbose output."));

            return(command);
        }
示例#21
0
        public Command Connection()
        {
            Command connections = new Command("connection", "List, Add, Remove connections");

            connections.AddCommand(List());
            connections.AddCommand(Show());
            connections.AddCommand(Add());
            connections.AddCommand(Remove());

            return(connections);

            Command List() => new Command("list", "List connections")
            {
                Handler = CommandHandler.Create(_connectionCommands.ListConnections)
            };

            Command Show()
            {
                var cmd = new Command("show", "Show connection details")
                {
                    Handler = CommandHandler.Create <string>(_connectionCommands.ShowConnections)
                };

                cmd.Add(ConnectionNameArgument());

                return(cmd);
            }

            Command Remove()
            {
                var cmd = new Command("remove", "Remove connection(s)")
                {
                    Handler = CommandHandler.Create <string, bool>(_connectionCommands.RemoveConnection)
                };

                cmd.AddOption(GlobalOption());
                cmd.AddArgument(ConnectionNameArgument());

                return(cmd);
            }

            Command Add()
            {
                var cmd = new Command("add", "Add a Connection");

                cmd.AddOption(new Option(new[] { "--global", "-g" })
                {
                    Argument = new Argument <bool>()
                });
                cmd.AddOption(new Option(new[] { "--document-endpoint", "-c" })
                {
                    Argument = new Argument <Uri>()
                });
                cmd.AddOption(new Option(new[] { "--gremlin-endpoint", "-t" })
                {
                    Argument = new Argument <string>()
                });
                cmd.AddOption(new Option(new[] { "--gremlin-port", "-p" })
                {
                    Argument = new Argument <int>(() => 443)
                });
                cmd.AddOption(new Option(new[] { "--authkey", "-k" })
                {
                    Argument = new Argument <string>()
                });
                cmd.AddOption(new Option(new[] { "--database", "-d" })
                {
                    Argument = new Argument <string>()
                });
                cmd.AddOption(new Option(new[] { "--graph" })
                {
                    Argument = new Argument <string>()
                });
                cmd.AddOption(new Option(new[] { "--partitionkey" })
                {
                    Argument = new Argument <string>()
                });

                cmd.AddArgument(
                    new Argument <string>()
                {
                    Name = "connectionName", Arity = ArgumentArity.ExactlyOne
                });
                cmd.Handler = CommandHandler.Create <string, CosmosDbConnection, bool>(_connectionCommands.AddConnection);

                return(cmd);
            }
        }
示例#22
0
        public void TargetUnit(Unit unit, Unit target, UnitAction?action, UnitFormation?formation, UnitStance?stance, int min_next_attack = int.MinValue, int max_next_attack = int.MaxValue, Unit backup = null)
        {
            if (backup == null)
            {
                backup = target;
            }

            var command = new Command();

            const int GL_CHECKS    = 100;
            const int GL_TEMP      = 101;
            const int GL_TARGET_ID = 102;

            var op_add   = Bot.GameVersion == GameVersion.AOC ? 1 : 25;
            var op_g_min = Bot.GameVersion == GameVersion.AOC ? 14 : 14;

            command.Add(new SetGoal()
            {
                InConstGoalId = GL_CHECKS, InConstValue = 0
            });
            command.Add(new SetGoal()
            {
                InConstGoalId = GL_TEMP, InConstValue = -1
            });
            command.Add(new SetGoal()
            {
                InConstGoalId = GL_TARGET_ID, InConstValue = -1
            });

            // check 1: unit exists

            command.Add(new UpSetTargetById()
            {
                InConstId = unit.Id
            });
            command.Add(new UpGetObjectData()
            {
                InConstObjectData = (int)ObjectData.ID, OutGoalData = GL_TEMP
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, "==", unit.Id, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // check 2: next_attack >= min_next_attack

            command.Add(new UpGetObjectData()
            {
                InConstObjectData = (int)ObjectData.NEXT_ATTACK, OutGoalData = GL_TEMP
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, ">=", min_next_attack, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // check 3: next_attack <= max_next_attack

            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, "<=", max_next_attack, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // check 4: target exists as GL_TARGET_ID

            command.Add(new UpSetTargetById()
            {
                InConstId = backup.Id
            });
            command.Add(new UpGetObjectData()
            {
                InConstObjectData = (int)ObjectData.ID, OutGoalData = GL_TEMP
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, "==", backup.Id, new SetGoal()
            {
                InConstGoalId = GL_TARGET_ID, InConstValue = backup.Id
            });
            command.Add(new UpSetTargetById()
            {
                InConstId = target.Id
            });
            command.Add(new UpGetObjectData()
            {
                InConstObjectData = (int)ObjectData.ID, OutGoalData = GL_TEMP
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, "==", target.Id, new SetGoal()
            {
                InConstGoalId = GL_TARGET_ID, InConstValue = target.Id
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TARGET_ID
            }, "!=", -1, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // check 5: unit is not already targeting GL_TARGET_ID

            command.Add(new UpSetTargetById()
            {
                InConstId = unit.Id
            });
            command.Add(new UpGetObjectData()
            {
                InConstObjectData = (int)ObjectData.TARGET_ID, OutGoalData = GL_TEMP
            });
            command.Add(new UpModifyGoal()
            {
                IoGoalId = GL_TEMP, MathOp = op_g_min, InOpValue = GL_TARGET_ID
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, "!=", 0, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // run if all checks passed

            command.Add(new Goal()
            {
                InConstGoalId = GL_CHECKS
            }, "==", 5,
                        new UpSetTargetById()
            {
                InGoalId = GL_TARGET_ID
            },
                        new UpFullResetSearch(),
                        new UpAddObjectById()
            {
                InConstSearchSource = 1, InConstId = unit.Id
            },
                        new UpTargetObjects()
            {
                InConstTarget       = 1,
                InConstTargetAction = action.HasValue ? (int)action.Value : (int)UnitAction.DEFAULT,
                InConstFormation    = formation.HasValue ? (int)formation.Value : -1,
                InConstAttackStance = stance.HasValue ? (int)stance.Value : -1
            }
                        );

            Commands.Add(command);
        }
示例#23
0
        public void TargetPosition(Unit unit, Position position, UnitAction?action, UnitFormation?formation, UnitStance?stance, int min_next_attack = int.MinValue, int max_next_attack = int.MaxValue)
        {
            if (action == UnitAction.MOVE && unit.Position == position)
            {
                return;
            }

            if (action == UnitAction.MOVE && unit[ObjectData.PRECISE_MOVE_X] == position.PreciseX && unit[ObjectData.PRECISE_MOVE_Y] == position.PreciseY)
            {
                return;
            }

            position = Bot.MapModule.Clamp(position);

            const int GL_CHECKS    = 100;
            const int GL_TEMP      = 101;
            const int GL_PRECISE_X = 102;
            const int GL_PRECISE_Y = 103;

            var op_add = Bot.GameVersion == GameVersion.AOC ? 1 : 25;

            var command = new Command();

            command.Add(new SetGoal()
            {
                InConstGoalId = GL_CHECKS, InConstValue = 0
            });
            command.Add(new SetGoal()
            {
                InConstGoalId = GL_TEMP, InConstValue = -1
            });

            command.Add(new SetGoal()
            {
                InConstGoalId = GL_PRECISE_X, InConstValue = position.PreciseX
            });
            command.Add(new SetGoal()
            {
                InConstGoalId = GL_PRECISE_Y, InConstValue = position.PreciseY
            });

            // check 1: unit exists

            command.Add(new UpSetTargetById()
            {
                InConstId = unit.Id
            });
            command.Add(new UpGetObjectData()
            {
                InConstObjectData = (int)ObjectData.ID, OutGoalData = GL_TEMP
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, "==", unit.Id, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // check 2: next_attack >= min_next_attack

            command.Add(new UpGetObjectData()
            {
                InConstObjectData = (int)ObjectData.NEXT_ATTACK, OutGoalData = GL_TEMP
            });
            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, ">=", min_next_attack, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // check 3: next_attack <= max_next_attack

            command.Add(new Goal()
            {
                InConstGoalId = GL_TEMP
            }, "<=", max_next_attack, new UpModifyGoal()
            {
                IoGoalId = GL_CHECKS, MathOp = op_add, InOpValue = 1
            });

            // run if all checks pass

            command.Add(new Goal()
            {
                InConstGoalId = GL_CHECKS
            }, "==", 3,
                        new SetStrategicNumber()
            {
                InConstSnId = (int)StrategicNumber.TARGET_POINT_ADJUSTMENT, InConstValue = 6
            },
                        new UpFullResetSearch(),
                        new UpAddObjectById()
            {
                InConstSearchSource = 1, InConstId = unit.Id
            },
                        new UpTargetPoint()
            {
                InGoalPoint         = GL_PRECISE_X,
                InConstTargetAction = action.HasValue ? (int)action.Value : -1,
                InConstFormation    = formation.HasValue ? (int)formation.Value : -1,
                InConstAttackStance = stance.HasValue ? (int)stance.Value : -1
            }
                        );

            Commands.Add(command);
        }
示例#24
0
        public static int Main(string[] args)
        {
            var root = new RootCommand(typeof(Program).Assembly.GetCustomAttribute <AssemblyTitleAttribute> ().Title);

            root.AddLicenseOption();


            var cmdPak = new Command("pak", "Process PAK files");

            root.Add(cmdPak);

            var cmdPakList = new Command("list", "List contents of a PAK file")
            {
                IsHidden = true
            };

            cmdPakList.AddArgument(new Argument <FileInfo> ("source", "Path to the PAK file").ExistingOnly());
            cmdPakList.AddOption(new Option <LocalHeaderField[]> ("--local-header")
            {
                IsHidden = true
            });                                                                                                           //uglifies help output
            cmdPakList.AddOption(new Option("--sort"));
            cmdPakList.Handler = CommandHandler.Create <FileInfo, LocalHeaderField[], bool> (DoPakList);
            cmdPak.Add(cmdPakList);

            var cmdPakPack = new Command("pack", "Pack contents of a directory into a single PAK file");

            cmdPakPack.AddArgument(new Argument <DirectoryInfo> ("source", "Path to the directory containing files").ExistingOnly());
            cmdPakPack.AddArgument(new Argument <FileInfo> ("target", "Path to a PAK file that will be created").NonExistingOnly());
            cmdPakPack.AddOption(new Option("--mixed-cache-block", "Indicates the source directory contains mixed contents of initial.pak and initial.pak\\initial.cache_block"));
            cmdPakPack.Handler = CommandHandler.Create <DirectoryInfo, FileInfo, bool> (DoPakPack);
            cmdPak.Add(cmdPakPack);


            var cmdCacheBlock = new Command("cache_block", "Process cache_block files");

            cmdCacheBlock.AddAlias("cb");
            root.Add(cmdCacheBlock);

            var cmdCacheBlockList = new Command("list", "List contents of a cache_block file");

            cmdCacheBlockList.AddArgument(new Argument <FileInfo> ("source", "Path to the cache_block file").ExistingOnly());
            cmdCacheBlockList.Handler = CommandHandler.Create <FileInfo> (DoCacheBlockList);
            cmdCacheBlock.Add(cmdCacheBlockList);

            var cmdCacheBlockUnpack             = new Command("unpack", "Unpack contents of a cache_block file into a directory");
            var cmdCacheBlockUnpack_AllowMixing = new Option("--allow-mixing", "Allow mixing of contents for initial.pak and initial.pak\\initial.cache_block");

            cmdCacheBlockUnpack.AddArgument(new Argument <FileInfo> ("source", "Path to the cache_block file").ExistingOnly());
            cmdCacheBlockUnpack.AddArgument(new Argument <DirectoryInfo> ("target", "Path to a directory that will be created to unpack into").NonExistingOnly(unless: cmdCacheBlockUnpack_AllowMixing));
            cmdCacheBlockUnpack.AddOption(cmdCacheBlockUnpack_AllowMixing);
            cmdCacheBlockUnpack.Handler = CommandHandler.Create <FileInfo, DirectoryInfo, bool> (DoCacheBlockUnpack);
            cmdCacheBlock.Add(cmdCacheBlockUnpack);

            var cmdCacheBlockPack = new Command("pack", "Pack contents of a directory into a single cache_block file");

            cmdCacheBlockPack.AddArgument(new Argument <DirectoryInfo> ("source", "Path to the directory containing files").ExistingOnly());
            cmdCacheBlockPack.AddArgument(new Argument <FileInfo> ("target", "Path to a cache_block file that will be created").NonExistingOnly());
            cmdCacheBlockPack.AddOption(new Option("--mixed-cache-block", "Indicates the source directory contains mixed contents of initial.pak and initial.pak\\initial.cache_block"));
            cmdCacheBlockPack.Handler = CommandHandler.Create <DirectoryInfo, FileInfo, bool> (DoCacheBlockPack);
            cmdCacheBlock.Add(cmdCacheBlockPack);


            var cmdLoadList = new Command("load_list", "Process load_list files");

            cmdLoadList.AddAlias("ll");
            root.Add(cmdLoadList);

            var cmdLoadListList = new Command("list", "List contents of a load_list file");

            cmdLoadListList.AddOption(new Option("--compact", "Use compact format (internal names only)"));
            cmdLoadListList.AddArgument(new Argument <FileInfo> ("source", "Path to the load_list file").ExistingOnly());
            cmdLoadListList.Handler = CommandHandler.Create <FileInfo, bool> (DoLoadListList);
            cmdLoadList.Add(cmdLoadListList);

            var cmdLoadListCreate = new Command("create-initial", "Create load_list file using conventions for initial.pak\\pak.load_list");

            cmdLoadListCreate.AddAlias("ci");
            cmdLoadListCreate.AddArgument(new Argument <FileInfo> ("target", "Path to a load_list file that will be created").NonExistingOnly());
            cmdLoadListCreate.AddArgument(new Argument <FileSystemInfo> ("initial", "Path to the initial.pak file or a directory with its contents").ExistingOnly());
            cmdLoadListCreate.AddArgument(new Argument <FileSystemInfo> ("shared", "Path to the shared.pak file or a directory with its contents").ExistingOnly());
            cmdLoadListCreate.AddArgument(new Argument <FileSystemInfo> ("shared_sound", "Path to the shared_sound.pak file or a directory with its contents").ExistingOnly());
            cmdLoadListCreate.Handler = CommandHandler.Create <FileInfo, FileSystemInfo, FileSystemInfo, FileSystemInfo> (DoLoadListCreate);
            cmdLoadList.Add(cmdLoadListCreate);


            var cmdSoundList = new Command("sound_list", "Process sound_list files");

            cmdSoundList.AddAlias("sl");
            root.Add(cmdSoundList);

            var cmdSoundListList = new Command("list", "List contents of a sound_list file");

            cmdSoundListList.AddArgument(new Argument <FileInfo> ("source", "Path to the sound_list file").ExistingOnly());
            cmdSoundListList.Handler = CommandHandler.Create <FileInfo> (DoSoundListList);
            cmdSoundList.Add(cmdSoundListList);

            var cmdSoundListCreate = new Command("create", "Create sound_list file");

            cmdSoundListCreate.AddArgument(new Argument <FileSystemInfo> ("source", "Path to the PAK file or a directory containing PCM files").ExistingOnly());
            cmdSoundListCreate.AddArgument(new Argument <FileInfo> ("target", "Path to the sound_list file").NonExistingOnly());
            cmdSoundListCreate.Handler = CommandHandler.Create <FileSystemInfo, FileInfo> (DoSoundListCreate);
            cmdSoundList.Add(cmdSoundListCreate);

            return(root.InvokeWithMiddleware(args, CommandLineExtensions.MakePrintLicenseResourceMiddleware(typeof(Program))));
        }
示例#25
0
        static void Main(string[] args)
        {
            var startOption = new Option(new string[] { "--start", "-s" }, "Start time (earliest videos to download)")
            {
                Argument   = new Argument <DateTime>("start", () => DateTime.MinValue),
                IsRequired = false
            };

            var endOption = new Option(new string[] { "--end", "-e" }, "End time (latest videos to download)")
            {
                Argument   = new Argument <DateTime>("end", () => DateTime.MaxValue),
                IsRequired = false
            };

            var pathOption = new Option(new string[] { "--path" }, "Path to save videos to")
            {
                Argument   = new Argument <string>("path", () => string.Empty),
                IsRequired = false
            };

            var passwordOption = new Option(new string[] { "--password", "-p" }, "Ring account password")
            {
                Argument   = new Argument <string>("password", () => string.Empty),
                IsRequired = false
            };

            var userNameOption = new Option(new string[] { "--username", "-u" }, "Ring account username")
            {
                Argument   = new Argument <string>("username", () => string.Empty),
                IsRequired = false
            };

            var starredOption = new Option(new string[] { "--starred" }, "Flag to only download Starred videos")
            {
                Argument   = new Argument <bool>("starred", () => false),
                IsRequired = false
            };

            var maxcountOption = new Option(new string[] { "--maxcount", "-m" }, "Maximum number of videos to download")
            {
                Argument   = new Argument <int>("maxcount", () => 1000),
                IsRequired = false
            };
            RootCommand rootCommand = new RootCommand(description: "Simple command line tool to download videos from your Ring account");

            var starCommand = new Command("starred", "Download only starred videos")
            {
                Handler = CommandHandler.Create <string, string, string, DateTime, DateTime, int>(GetStarredVideos)
            };
            var allCommand = new Command("all", "Download all videos (starred and unstarred)")
            {
                Handler = CommandHandler.Create <string, string, string, DateTime, DateTime, int>(GetAllVideos)
            };
            var snapshotCommand = new Command("snapshot", "Download only snapshot images")
            {
                Handler = CommandHandler.Create <string, string, string, DateTime, DateTime>(GetSnapshotImages)
            };

            rootCommand.Add(starCommand);
            rootCommand.Add(allCommand);
            rootCommand.Add(snapshotCommand);

            starCommand.Add(userNameOption);
            starCommand.Add(passwordOption);
            starCommand.Add(pathOption);
            starCommand.Add(startOption);
            starCommand.Add(endOption);
            starCommand.Add(maxcountOption);

            allCommand.Add(userNameOption);
            allCommand.Add(passwordOption);
            allCommand.Add(pathOption);
            allCommand.Add(startOption);
            allCommand.Add(endOption);
            allCommand.Add(maxcountOption);

            snapshotCommand.Add(userNameOption);
            snapshotCommand.Add(passwordOption);
            snapshotCommand.Add(pathOption);
            snapshotCommand.Add(startOption);
            snapshotCommand.Add(endOption);


            var services = new ServiceCollection();

            ConfigureServices(services, args);
            using (ServiceProvider serviceProvider = services.BuildServiceProvider())
            {
                app  = serviceProvider.GetService <RingVideoApplication>();
                auth = Configuration.GetSection("Authentication").Get <Authentication>();
                if (auth != null)
                {
                    auth.Decrypt();
                }
                else
                {
                    auth = new Authentication();
                }
                filter = Configuration.GetSection("Filter").Get <Filter>();
                if (filter == null)
                {
                    filter = new Filter();
                }

                Task <int> val = rootCommand.InvokeAsync(args);
                val.Wait();

                SaveSettings(Program.filter, Program.auth, val.Result);
            }
        }
        public static RootCommand WireUpBase64UrlCommands(this RootCommand rootCommand)
        {
            var base64UrlCommand    = new Command("base64url", "Base64 URL");
            var base64UrlEncCommand = new Command("encode", "Encode");

            base64UrlEncCommand.AddAlias("enc");
            base64UrlEncCommand.AddOption(new Option <string>(new string[] { "--text", "-t" }, "Input Text"));
            base64UrlEncCommand.AddOption(new Option <FileInfo>(new string[] { "--input", "-i" }, "Input file path"));
            base64UrlEncCommand.AddOption(new Option <FileInfo>(new string[] { "--output", "-o" }, "Output file path"));

            base64UrlEncCommand.Handler = CommandHandler.Create <string, FileInfo, FileInfo, IConsole>(async(text, input, output, console) =>
            {
                try
                {
                    string base64UrlEncodedText = null;

                    if (text != null)
                    {
                        base64UrlEncodedText = Base64Url.Encode(text);
                    }
                    if (input != null)
                    {
                        base64UrlEncodedText = Base64Url.Encode(await File.ReadAllTextAsync(input.FullName).ConfigureAwait(false));
                    }

                    if (output == null)
                    {
                        console.Out.WriteLine(base64UrlEncodedText);
                    }
                    else
                    {
                        await File.WriteAllTextAsync(output.FullName, base64UrlEncodedText).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                    return(22);
                }
                return(0);
            });
            var base64UrlDecCommand = new Command("decode", "Decode");

            base64UrlDecCommand.AddAlias("dec");
            base64UrlDecCommand.AddOption(new Option(new string[] { "--text", "-t" }, "Input Text")
            {
                Argument = new Argument <string>("text")
            });
            base64UrlDecCommand.AddOption(new Option(new string[] { "--input", "-i" }, "Input file path")
            {
                Argument = new Argument <FileInfo>("input")
            });
            base64UrlDecCommand.AddOption(new Option(new string[] { "--output", "-o" }, "Output file path")
            {
                Argument = new Argument <FileInfo>("output")
            });
            base64UrlDecCommand.Handler = CommandHandler.Create <string, FileInfo, FileInfo, IConsole>(async(text, input, output, console) =>
            {
                try
                {
                    string base64UrlDecodedText = null;

                    if (text != null)
                    {
                        base64UrlDecodedText = Base64Url.Decode(text);
                    }
                    if (input != null)
                    {
                        base64UrlDecodedText = Base64Url.Decode(await File.ReadAllTextAsync(input.FullName).ConfigureAwait(false));
                    }

                    if (output == null)
                    {
                        console.Out.WriteLine(base64UrlDecodedText);
                    }
                    else
                    {
                        await File.WriteAllTextAsync(output.FullName, base64UrlDecodedText).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                    return(22);
                }
                return(0);
            });

            base64UrlCommand.Add(base64UrlEncCommand);
            base64UrlCommand.Add(base64UrlDecCommand);
            rootCommand.AddCommand(base64UrlCommand);

            return(rootCommand);
        }
示例#27
0
        /*
         *      truck CustomizationCameras --FOV:40 "D:\Games\SnowRunner_backs\mods\.staging\initial-pak\[media]\classes\trucks\ank_mk38.xml"
         */

        public static int Main(string[] args)
        {
            var root = new RootCommand(typeof(Program).Assembly.GetCustomAttribute <AssemblyTitleAttribute> ().Title);

            root.AddLicenseOption();


            var cmdTruck = new Command("truck", "Trucks configuration");

            root.Add(cmdTruck);

            var cmdTruckCustomizationCameras = new Command("CustomizationCameras");

            cmdTruckCustomizationCameras.AddOption(new Option <float?> ("--FOV"));
            cmdTruckCustomizationCameras.AddOption(new Option <float?> ("--MaxZoom"));
            var targetXmlWildcardsArgument = new Argument <IEnumerable <FileInfo> > ("targetXmls", CommandLineExtensions.ParseWildcards)
            {
                Description = "Truck XML file to modify (wildcards supported)"
            }.ExistingOrWildcardOnly();

            cmdTruckCustomizationCameras.AddArgument(targetXmlWildcardsArgument);
            cmdTruckCustomizationCameras.Handler = CommandHandler.Create <IEnumerable <FileInfo>, float?, float?> (DoTruckCustomizationCameras);
            cmdTruck.Add(cmdTruckCustomizationCameras);


            var cmdTruckCraneSocket = new Command("CraneSocket");

            cmdTruck.Add(cmdTruckCraneSocket);

            var cmdTruckCraneSocketAdd = new Command("add");

            cmdTruckCraneSocket.Add(cmdTruckCraneSocketAdd);

            var cmdTruckCraneSocketAddTopCentral = new Command("top-central");
            var targetXmlArgument = new Argument <FileInfo> ("targetXml").ExistingOnly();

            cmdTruckCraneSocketAddTopCentral.AddArgument(targetXmlArgument);
            cmdTruckCraneSocketAddTopCentral.Handler = CommandHandler.Create <FileInfo> (DoTruckCraneSocketAddTopCentral);
            cmdTruckCraneSocketAdd.Add(cmdTruckCraneSocketAddTopCentral);


            var cmdTruckExtents = new Command("extents");

            cmdTruckExtents.AddArgument(targetXmlArgument);
            cmdTruckExtents.Handler = CommandHandler.Create <FileInfo> (DoTruckExtents);
            cmdTruck.Add(cmdTruckExtents);


            var cmdExtras = new Command("extras", "Extra configuration");

            root.Add(cmdExtras);

            var cmdExtrasRename = new Command("rename", "Rename game objects");

            cmdExtras.Add(cmdExtrasRename);

            var cmdExtrasRenameTires = new Command("tires", "Rename tires");
            var languageOption       = new Option <GameLanguage> ("--language")
            {
                Required = true
            };

            cmdExtrasRenameTires.AddOption(languageOption);
            var directoryArgument = new Argument <DirectoryInfo> ("directory", "Path to the directory with mixed contents of initial.pak and initial.pak\\initial.cache_block").ExistingOnly();

            cmdExtrasRenameTires.AddArgument(directoryArgument);
            cmdExtrasRenameTires.Handler = CommandHandler.Create <DirectoryInfo, GameLanguage> (ExtrasRenamer.RenameTires);
            cmdExtrasRename.Add(cmdExtrasRenameTires);

            var cmdExtrasRenameTrucks = new Command("trucks", "Rename trucks");

            cmdExtrasRenameTrucks.AddOption(languageOption);
            cmdExtrasRenameTrucks.AddArgument(directoryArgument);
            cmdExtrasRenameTrucks.Handler = CommandHandler.Create <DirectoryInfo, GameLanguage> (ExtrasRenamer.RenameTrucks);
            cmdExtrasRename.Add(cmdExtrasRenameTrucks);

            var cmdExtrasRenameEngines = new Command("engines", "Rename engines");

            cmdExtrasRenameEngines.AddOption(languageOption);
            cmdExtrasRenameEngines.AddArgument(directoryArgument);
            cmdExtrasRenameEngines.Handler = CommandHandler.Create <DirectoryInfo, GameLanguage> (ExtrasRenamer.RenameEngines);
            cmdExtrasRename.Add(cmdExtrasRenameEngines);

            return(root.InvokeWithMiddleware(args, CommandLineExtensions.MakePrintLicenseResourceMiddleware(typeof(Program))));
        }
示例#28
0
        public static async Task Main(string[] args)
        {
            try
            {
                var command = new RootCommand("satellite", treatUnmatchedTokensAsErrors: true, isHidden: true);

                List <Option> commonOptions = new List <Option>();
                commonOptions.Add(new Option("--test", "Call the test API", argument: new Argument <bool> {
                    Arity = ArgumentArity.ZeroOrOne
                }));
                commonOptions.Add(new Option("--url", "Call an API at this URL", argument: new Argument <string> {
                    Arity = ArgumentArity.ExactlyOne
                }));
                commonOptions.Add(new Option("--pretty", "Prettify the JSON result", argument: new Argument <bool> {
                    Arity = ArgumentArity.ZeroOrOne
                }));

                #region Create order

                var createOrderArgument = new Argument();
                createOrderArgument.AddValidator(symbol =>
                {
                    if (symbol.Children.Contains("filepath") && symbol.Children.Contains("message"))
                    {
                        return("Options '--filepath' and '--message' cannot be used together.");
                    }

                    if (!symbol.Children.Contains("filepath") && !symbol.Children.Contains("message"))
                    {
                        return("Options '--filepath' or '--message' must be set.");
                    }

                    if (!symbol.Children.Contains("bid"))
                    {
                        return("Option '--bid' must be set.");
                    }

                    return(null);
                });

                var createOrderCommand = new Command("create-order", description: "Place an order for a message transmission", argument: createOrderArgument, symbols: commonOptions)
                {
                    new Option("--bid", argument: new Argument <int>()),
                    new Option("--filepath", argument: new Argument <string>()),
                    new Option("--message", argument: new Argument <string>())
                };

                createOrderCommand.Handler = CommandHandler.Create((int bid, string filePath, string message, bool test, string url, bool pretty) =>
                {
                    try
                    {
                        ISatelliteApi api   = InitializeApi(test, url);
                        InvoiceModel result = api.CreateOrderAsync(bid, filePath, message).GetAwaiter().GetResult();
                        ShowApiCallResult(result, pretty);
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(createOrderCommand);

                #endregion

                #region Cancel order

                var cancelOrderArgument = new Argument();
                cancelOrderArgument.AddValidator(symbol =>
                {
                    if (!symbol.Children.Contains("orderid") || !symbol.Children.Contains("authtoken"))
                    {
                        return("Options '--orderid' and '--authtoken' must be set.");
                    }

                    return(null);
                });

                var cancelOrderCommand = new Command("cancel-order", description: "Cancel an order", argument: cancelOrderArgument, symbols: commonOptions)
                {
                    new Option("--orderid", argument: new Argument <string>()),
                    new Option("--authtoken", argument: new Argument <string>())
                };

                cancelOrderCommand.Handler = CommandHandler.Create((string orderId, string authToken, bool test, string url) =>
                {
                    try
                    {
                        ISatelliteApi api = InitializeApi(test, url);
                        bool result       = api.CancelOrderAsync(orderId, authToken).GetAwaiter().GetResult();
                        string message    = result ? "Order cancelled" : "Order has not been cancelled";
                        Console.WriteLine(message);
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(cancelOrderCommand);

                #endregion

                #region Get order

                var getOrderArgument = new Argument();
                getOrderArgument.AddValidator(symbol =>
                {
                    if (!symbol.Children.Contains("orderid") || !symbol.Children.Contains("authtoken"))
                    {
                        return("Options '--orderid' and '--authtoken' must be set.");
                    }

                    return(null);
                });

                var getOrderCommand = new Command("get-order", description: "Retrieve an order", argument: getOrderArgument, symbols: commonOptions)
                {
                    new Option("--orderid", argument: new Argument <string>()),
                    new Option("--authtoken", argument: new Argument <string>())
                };

                getOrderCommand.Handler = CommandHandler.Create((string orderId, string authToken, bool test, string url, bool pretty) =>
                {
                    try
                    {
                        ISatelliteApi api = InitializeApi(test, url);
                        OrderModel result = api.GetOrderAsync(orderId, authToken).GetAwaiter().GetResult();
                        ShowApiCallResult(result, pretty);
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(getOrderCommand);

                #endregion

                #region Bump order

                var bumpOrderArgument = new Argument();
                bumpOrderArgument.AddValidator(symbol =>
                {
                    if (!symbol.Children.Contains("orderid") || !symbol.Children.Contains("authtoken") || !symbol.Children.Contains("amount"))
                    {
                        return("Options '--orderid', '--authtoken' and '--amount' must be set.");
                    }

                    return(null);
                });

                var bumpOrderCommand = new Command("bump-order", description: "Increase the bid for an order sitting in the transmission queue", argument: bumpOrderArgument, symbols: commonOptions)
                {
                    new Option("--orderid", argument: new Argument <string>()),
                    new Option("--authtoken", argument: new Argument <string>()),
                    new Option("--amount", argument: new Argument <int>())
                };

                bumpOrderCommand.Handler = CommandHandler.Create((string orderId, string authToken, int amount, bool test, string url, bool pretty) =>
                {
                    try
                    {
                        ISatelliteApi api   = InitializeApi(test, url);
                        InvoiceModel result = api.BumpBidAsync(orderId, authToken, amount).GetAwaiter().GetResult();
                        ShowApiCallResult(result, pretty);
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(bumpOrderCommand);

                #endregion

                #region Get queued orders.

                var queuedCommand = new Command("queued-orders", description: "Retrieve a list of paid, but unsent orders in descending order of bid-per-byte", symbols: commonOptions);
                queuedCommand.Add(new Option("--limit", "(optional) Specifies the limit of queued orders to return", new Argument <int>()));
                queuedCommand.Handler = CommandHandler.Create((int?limit, bool test, string url, bool pretty) =>
                {
                    try
                    {
                        ISatelliteApi api = InitializeApi(test, url);
                        IEnumerable <OrderModel> result = api.GetQueuedOrdersAsync(limit).GetAwaiter().GetResult();
                        ShowApiCallResult(result, pretty);
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(queuedCommand);

                #endregion

                #region Get pending orders

                var pendingCommand = new Command("pending-orders", description: "Retrieve a list of 20 orders awaiting payment sorted in reverse chronological order", symbols: commonOptions);
                pendingCommand.Add(new Option("--before", "(optional) The 20 orders immediately prior to the given date will be returned", new Argument <DateTime>()));
                pendingCommand.Handler = CommandHandler.Create((DateTime? before, bool test, string url, bool pretty) =>
                {
                    try
                    {
                        ISatelliteApi api = InitializeApi(test, url);
                        IEnumerable <OrderModel> result = api.GetPendingOrdersAsync(before).GetAwaiter().GetResult();
                        ShowApiCallResult(result, pretty);
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(pendingCommand);

                #endregion

                #region Get sent orders.

                var sentCommand = new Command("sent-orders", description: "Retrieve a list of 20 paid orders sorted in reverse chronological order", symbols: commonOptions);
                sentCommand.Add(new Option("--before", "(optional) The 20 orders immediately prior to the given date will be returned", new Argument <DateTime>()));
                sentCommand.Handler = CommandHandler.Create((DateTime? before, bool test, string url, bool pretty) =>
                {
                    try
                    {
                        ISatelliteApi api = InitializeApi(test, url);
                        IEnumerable <OrderModel> result = api.GetSentOrdersAsync(before).GetAwaiter().GetResult();
                        ShowApiCallResult(result, pretty);
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(sentCommand);

                #endregion

                #region Get message

                var getMessageArgument = new Argument();
                getMessageArgument.AddValidator(symbol =>
                {
                    if (!symbol.Children.Contains("num"))
                    {
                        return("Options '--num' must be set.");
                    }

                    return(null);
                });

                var msgCommand = new Command("msg", description: "Retrieve the message sent in an order", argument: getMessageArgument, symbols: commonOptions);
                msgCommand.Add(new Option("--num", description: "The message number", argument: new Argument <int>()));
                msgCommand.Handler = CommandHandler.Create((int num, bool test, string url, bool pretty) =>
                {
                    try
                    {
                        ISatelliteApi api   = InitializeApi(test, url);
                        Stream result       = api.RetrieveMessageAsync(num).GetAwaiter().GetResult();
                        StreamReader reader = new StreamReader(result);
                        Console.WriteLine(reader.ReadToEnd());
                    }
                    catch (ApiException ex)
                    {
                        ShowException(ex);
                    }
                });

                command.Add(msgCommand);

                #endregion

                #region Get Info

                var infoCommand = new Command("info", description: "Return information about the c-lightning node where satellite API payments are terminated", symbols: commonOptions)
                {
                    Handler = CommandHandler.Create((bool test, string url, bool pretty) =>
                    {
                        try
                        {
                            ISatelliteApi api = InitializeApi(test, url);
                            InfoModel result  = api.GetInfoAsync().GetAwaiter().GetResult();
                            ShowApiCallResult(result, pretty);
                        }
                        catch (ApiException ex)
                        {
                            ShowException(ex);
                        }
                    })
                };

                command.Add(infoCommand);

                #endregion

                #region Stream transmissions

                var transmissionsCommand = new Command("stream-transmissions", description: "Subscribe to server-sent events for transmission messages.", symbols: commonOptions)
                {
                    Handler = CommandHandler.Create((bool test, string url, bool pretty) =>
                    {
                        try
                        {
                            Console.WriteLine("Listening to new messages. Press Enter to stop.");

                            ISatelliteApi api = InitializeApi(test, url);
                            api.ReceiveTransmissionsMessages(
                                (EventSourceMessageEventArgs e) =>
                            {
                                Console.WriteLine($"Event: {e.Event}. Message: {e.Message}. Id: {e.Id}.");
                            },
                                (DisconnectEventArgs e) =>
                            {
                                Console.WriteLine($"Retry in: {e.ReconnectDelay}. Error: {e.Exception.Message}");
                            });

                            Console.Read();
                        }
                        catch (ApiException ex)
                        {
                            ShowException(ex);
                        }
                    })
                };

                command.Add(transmissionsCommand);

                #endregion

                await command.InvokeAsync(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An exception occurred: {ex.Message}");
            }
        }
示例#29
0
        private Command GetPurchasesCommand()
        {
            var purchases = new Command("purchases", "Return, add or remove purchases")
            {
                new Option <Guid>("--transaction-id", "The transaction ID.")
                {
                    Required = true
                },
                new Option <Guid>("--person-id", "The transaction person ID.")
                {
                    Required = true
                }
            };

            purchases.Handler = CommandHandler.Create <IHost, Transaction>(async(host, transaction) =>
            {
                var client = host.Services.GetRequiredService <IDummyGrpcClient>();
                Print(await client.GetPurchasesAsync(transaction));
            });
            var add = new Command("add", "Add a purchase.")
            {
                new Option <Guid>("--purchase-id", "The purchase ID.")
                {
                    Required = true
                },
                new Option <Guid>("--transaction-id", "The transaction ID.")
                {
                    Required = true
                },
                new Option <decimal>("--price", "The purchase price.")
                {
                    Required = true
                },
                new Option <int>("--count", "The purchase count.")
                {
                    Required = true
                },
            };

            add.Handler = CommandHandler.Create <IHost, Purchase>(async(host, purchase) =>
            {
                var client = host.Services.GetRequiredService <IDummyGrpcClient>();
                Print(await client.AddPurchaseAsync(purchase));
            });
            var remove = new Command("remove", "Remove a purchase.")
            {
                new Option <Guid>("--purchase-id", "The purchase ID.")
                {
                    Required = true
                },
                new Option <Guid>("--transaction-id", "The transaction ID.")
                {
                    Required = true
                },
            };

            remove.Handler = CommandHandler.Create <IHost, Purchase>(async(host, purchase) =>
            {
                var client = host.Services.GetRequiredService <IDummyGrpcClient>();
                Print(await client.RemovePurchaseAsync(purchase));
            });
            purchases.Add(add);
            purchases.Add(remove);
            return(purchases);
        }
示例#30
0
 public void SimulateMouseClick(Type resolver)
 {
     Start(resolver, (InputCommands input) =>
     {
         var command = new Command();
         input.Add(command);
         command.Add(new MouseButtonTrigger(MouseButton.Left, State.Releasing));
         bool triggered = false;
         command.Attach(trigger => triggered = true);
         if (testResolver != null)
         {
             testResolver.SetMouseButtonState(MouseButton.Left, State.Releasing, Point.Zero);
             testResolver.AdvanceTimeAndExecuteRunners(0.1f);
             Assert.IsTrue(triggered);
         }
     });
 }
示例#31
0
        public Command CreateCommand()
        {
            var iothubCommand = new Command("iothub");


            // set-context
            var iotHubContextCommand = new Command("set-context");

            iotHubContextCommand.AddArgument(new Argument <string>("name"));
            iotHubContextCommand.Add(new Option <string>("--eventhub-endpoint"));
            iotHubContextCommand.Add(new Option <string>("--eventhub-name"));
            iotHubContextCommand.Add(new Option <string>("--storage-connection"));
            iotHubContextCommand.Add(new Option <string>("--consumer-group"));
            iotHubContextCommand.Add(new Option <string>("--device-connection-string"));
            iotHubContextCommand.Handler = CommandHandler.Create <string, string, string, string, string, string>(SetContext);
            iothubCommand.AddCommand(iotHubContextCommand);

            // get-context
            var iotHubGetContextCommand = new Command("get-context");

            iotHubGetContextCommand.Add(new Option <string>("--name"));
            iotHubGetContextCommand.Handler = CommandHandler.Create <string>(GetContext);
            iothubCommand.AddCommand(iotHubGetContextCommand);

            // use-context
            var iotHubUseContextCommand = new Command("use-context");

            iotHubUseContextCommand.AddArgument(new Argument("context-name"));
            iotHubUseContextCommand.Handler = CommandHandler.Create <string>(UseContext);
            iothubCommand.AddCommand(iotHubUseContextCommand);

            // message
            var messageCommand = new Command("message");

            messageCommand.Add(new Option <int>("--limit", "number of messages to retrieve"));
            messageCommand.Add(new Option <int>("--message-timeout", "message timeout in seconds"));
            messageCommand.Add(new Option("--follow", "stream latest messages"));
            messageCommand.Add(new Option <string>("--context", "context for reading messages"));
            messageCommand.Handler = CommandHandler.Create <bool, int, int, string>(WatchMessage);
            iothubCommand.AddCommand(messageCommand);

            // d2c
            var d2cCommand = new Command("d2c");

            d2cCommand.Add(new Option <string>("--message", "text to send"));
            d2cCommand.Add(new Option <string>("--from-file", "send contents of file"));
            d2cCommand.Add(new Option <TransportType>("--transport-type", "Override the default, options are as per Microsoft.Azure.Devices.Client.TransportType"));
            d2cCommand.Handler = CommandHandler.Create <string, string, TransportType>(Device2CloudMessage);
            iothubCommand.AddCommand(d2cCommand);

            // simulate
            var simulateCommand = new Command("simulate-device");

            simulateCommand.Add(new Option <string>("--device-type", () => { return("temperature"); }, "Supported types: [\"temperature\", \"temperature_pair\"]"));
            simulateCommand.Add(new Option <int>("--message-delay", () => { return(5000); }, "Delay between messages in milliseconds. Default 5 seconds"));
            simulateCommand.Add(new Option <int>("--n", () => { return(-1); }, "Number of messages to send. Default is unbounded"));
            simulateCommand.Add(new Option <string>("--ca-file", "CA cert to be trusted"));
            simulateCommand.Add(new Option <string[]>("--device-context", "List of context names to generate simulated data for. Separate context names with spaces"));
            simulateCommand.Add(new Option <string>("--pattern", () => { return("none"); }, "Supported patterns: [\"none\", \"sine\"]"));
            simulateCommand.Add(new Option <string>("--pattern-period", "Cycle time for pattern generator"));
            //simulateCommand.Add(new Option<string>("--output", () => { return "csv"; }, "Supported output formats: [\"csv\", \"json\"]. Default: csv"));
            simulateCommand.Add(new Option <string>("--output", () => { return("json"); }, "Supported output formats: [\"csv\", \"json\"]. Default: json"));
            simulateCommand.Handler = Create <string, int, int, string, string[], string, string, string>(SimulateDevice);
            iothubCommand.Add(simulateCommand);


            return(iothubCommand);
        }
 private void RegisterPluginCommands(Command root)
 {
     _generators
     .Select(CreateCommandInLifeTimeScope)
     .ForEach(o => o.AndThen(c => root.Add(c)));
 }
 public Command GenerateCrouchCommand (bool crouch) {
     Command com = new Command(this.Data.ListenInputID,Agent.Controller.ControllerID);
     com.Add<DefaultData> (new DefaultData(DataType.Bool,crouch));
     return com;
 }
示例#34
0
        public void AddTrigger(string commandName, MouseButton mousButton, State buttonState)
        {
            Command c = GetCommandByName(commandName);

            c.Add(new MouseButtonTrigger(mousButton, buttonState));
        }
        public SuggestionDispatcher(ISuggestionRegistration suggestionRegistration, ISuggestionStore suggestionStore = null)
        {
            _suggestionRegistration = suggestionRegistration ?? throw new ArgumentNullException(nameof(suggestionRegistration));
            _suggestionStore        = suggestionStore ?? new SuggestionStore();

            Parser = new CommandLineBuilder()
                     .UseVersionOption()
                     .UseHelp()
                     .UseParseDirective()
                     .UseDebugDirective()
                     .UseSuggestDirective()
                     .UseParseErrorReporting()
                     .UseExceptionHandler()

                     .AddCommand(ListCommand())
                     .AddCommand(GetCommand())
                     .AddCommand(RegisterCommand())
                     .AddCommand(CompleteScriptCommand())

                     .Build();

            Command GetCommand()
            {
                var command = new Command("get")
                {
                    ExecutableOption(),
                    PositionOption()
                };

                command.Description = "Gets suggestions from the specified executable";
                command.Handler     = CommandHandler.Create <ParseResult, IConsole>(Get);
                return(command);
            }

            Option ExecutableOption() =>
            new Option(new[] { "-e", "--executable" })
            {
                Argument = new Argument <string>().LegalFilePathsOnly(), Description = "The executable to call for suggestions"
            };

            Option PositionOption() =>
            new Option(new[] { "-p", "--position" })
            {
                Argument    = new Argument <int>(),
                Description = "The current character position on the command line"
            };

            Command ListCommand() =>
            new Command("list")
            {
                Description = "Lists apps registered for suggestions",
                Handler     = CommandHandler.Create <IConsole>(
                    c => c.Out.WriteLine(ShellPrefixesToMatch(_suggestionRegistration)))
            };

            Command CompleteScriptCommand() =>
            new Command("script")
            {
                Argument = new Argument <ShellType>
                {
                    Name = nameof(ShellType)
                },
                Description = "Print complete script for specific shell",
                Handler     = CommandHandler.Create <IConsole, ShellType>(SuggestionShellScriptHandler.Handle)
            };

            Command RegisterCommand()
            {
                var description = "Registers an app for suggestions";

                var command = new Command("register")
                {
                    Description = description,
                    Handler     = CommandHandler.Create <string, string, IConsole>(Register)
                };

                command.Add(CommandPathOption());
                command.Add(SuggestionCommandOption());
                return(command);
            }

            Option CommandPathOption() =>
            new Option("--command-path")
            {
                Argument    = new Argument <string>(),
                Description = "The path to the command for which to register suggestions"
            };

            Option SuggestionCommandOption() =>
            new Option("--suggestion-command")
            {
                Argument    = new Argument <string>(),
                Description = "The command to invoke to retrieve suggestions"
            };
        }
示例#36
0
        public void AddTrigger(string commandName, Key key, State keyState)
        {
            Command c = GetCommandByName(commandName);

            c.Add(new KeyTrigger(key, keyState));
        }
示例#37
0
		private void DisplayGameOverMessage()
		{
			Chunk.Dispose();
			var fontGameOverText = ContentLoader.Load<Font>("Tahoma30");
			var fontReplayText = ContentLoader.Load<Font>("Verdana12");
			gameOverMsg = new FontText(fontGameOverText, "Game Over",
				Rectangle.FromCenter(Vector2D.Half, new Size(0.6f, 0.3f)))
			{
				Color = menu.gameColors[1],
				RenderLayer = 3
			};
			restartMsg = new FontText(fontReplayText, "Do you want to continue (Y/N)",
				Rectangle.FromCenter(new Vector2D(0.5f, 0.7f), new Size(0.6f, 0.3f)))
			{
				Color = menu.gameColors[2],
				RenderLayer = 3
			};
			yesCommand = new Command(RestartGame);
			yesCommand.Add(new KeyTrigger(Key.Y));
			noCommand = new Command(BackToMenu);
			noCommand.Add(new KeyTrigger(Key.N));
		}
示例#38
0
        public void AddTrigger(string commandName, GamePadButton gamePadButton, State gamePadState)
        {
            Command c = GetCommandByName(commandName);

            c.Add(new GamePadButtonTrigger(gamePadButton, gamePadState));
        }
示例#39
0
        protected override IEnumerable <Command> RequestUpdate()
        {
            CommandInfo.Reset();

            CommandInfo.Add(new GameTime());
            CommandInfo.Add(new UpGetPoint()
            {
                OutGoalPoint = 50, InConstPositionType = (int)PositionType.SELF
            });
            CommandInfo.Add(new Goal()
            {
                InConstGoalId = 50
            });
            CommandInfo.Add(new Goal()
            {
                InConstGoalId = 51
            });
            CommandInfo.Add(new WoodAmount());
            CommandInfo.Add(new FoodAmount());
            CommandInfo.Add(new GoldAmount());
            CommandInfo.Add(new StoneAmount());
            CommandInfo.Add(new EscrowAmount()
            {
                InConstResource = (int)Resource.WOOD
            });
            CommandInfo.Add(new EscrowAmount()
            {
                InConstResource = (int)Resource.FOOD
            });
            CommandInfo.Add(new EscrowAmount()
            {
                InConstResource = (int)Resource.GOLD
            });
            CommandInfo.Add(new EscrowAmount()
            {
                InConstResource = (int)Resource.STONE
            });
            CommandInfo.Add(new PopulationHeadroom());
            CommandInfo.Add(new HousingHeadroom());
            CommandInfo.Add(new PopulationCap());

            foreach (var sn in StrategicNumbers)
            {
                CommandInfo.Add(new SetStrategicNumber()
                {
                    InConstSnId = (int)sn.Key, InConstValue = sn.Value
                });
            }

            yield return(CommandInfo);

            CommandSn.Reset();

            foreach (var sn in Enum.GetValues(typeof(StrategicNumber)).Cast <StrategicNumber>())
            {
                CommandSn.Add(new Protos.Expert.Fact.StrategicNumber()
                {
                    InConstSnId = (int)sn
                });
            }

            yield return(CommandSn);
        }
示例#40
0
        public void AddTrigger(string commandName, State touchState)
        {
            Command c = GetCommandByName(commandName);

            c.Add(new TouchPressTrigger(touchState));
        }
示例#41
0
        public static RootCommand WireUpPfxCommands(this RootCommand rootCommand)
        {
            var pfxCommand    = new Command("pfx", "PFX, PKCS #12");
            var pfxEncCommand = new Command("encrypt", "Encrypt");

            pfxEncCommand.AddAlias("enc");
            pfxEncCommand.AddOption(new Option <string>(new string[] { "--text", "-t" }, "Input Text"));
            pfxEncCommand.AddOption(new Option <FileInfo>(new string[] { "--input", "-i" }, "Input file path"));
            pfxEncCommand.AddOption(new Option <FileInfo>(new string[] { "--output", "-o" }, "Output file path"));
            pfxEncCommand.AddOption(new Option <FileInfo>(new string[] { "--certinput", "-ci" }, "Certificate file path (.pfx)"));
            pfxEncCommand.AddOption(new Option <string>(new string[] { "--keytext", "-kt" }, "Key Text"));

            pfxEncCommand.Handler = CommandHandler.Create <string, FileInfo, FileInfo, FileInfo, string, IConsole>(async(text, input, output, certInput, keyText, console) =>
            {
                try
                {
                    if (input != null)
                    {
                        text = await File.ReadAllTextAsync(input.FullName).ConfigureAwait(false);
                    }

                    using var certificate = new X509Certificate2(certInput.FullName, keyText);
                    using var rsa         = certificate.GetRSAPublicKey();
                    var encryptedText     = rsa.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.Pkcs1);

                    if (output == null)
                    {
                        console.Out.WriteLine(Convert.ToBase64String(encryptedText));
                    }
                    else
                    {
                        var outputStream = output.OpenWrite();
                        await outputStream.WriteAsync(encryptedText).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                    return(22);
                }
                return(0);
            });

            var pfxDecCommand = new Command("decrypt", "Decrypt");

            pfxDecCommand.AddAlias("dec");
            pfxDecCommand.AddOption(new Option <string>(new string[] { "--text", "-t" }, "Input Text"));
            pfxDecCommand.AddOption(new Option <FileInfo>(new string[] { "--input", "-i" }, "Input file path"));
            pfxDecCommand.AddOption(new Option <FileInfo>(new string[] { "--output", "-o" }, "Output file path"));
            pfxDecCommand.AddOption(new Option <FileInfo>(new string[] { "--certinput", "-ci" }, "Certificate file path (.pfx)"));
            pfxDecCommand.AddOption(new Option <string>(new string[] { "--keytext", "-kt" }, "Key Text"));

            pfxDecCommand.Handler = CommandHandler.Create <string, FileInfo, FileInfo, FileInfo, string, IConsole>(async(text, input, output, certInput, keyText, console) =>
            {
                try
                {
                    using var certificate = new X509Certificate2(certInput.FullName, keyText, X509KeyStorageFlags.EphemeralKeySet);
                    using var rsa         = certificate.GetRSAPrivateKey();

                    var textBytes = Convert.FromBase64String(text);
                    if (input != null)
                    {
                        textBytes = await File.ReadAllBytesAsync(input.FullName).ConfigureAwait(false);
                    }
                    var decryptedText = rsa.Decrypt(textBytes, RSAEncryptionPadding.Pkcs1);
                    if (output == null)
                    {
                        console.Out.WriteLine(Encoding.UTF8.GetString(decryptedText));
                    }
                    else
                    {
                        using var outputStream = output.OpenWrite();
                        await outputStream.WriteAsync(decryptedText).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                    return(22);
                }
                return(0);
            });

            var pfxInfoCommand = new Command("info", "Information");

            pfxInfoCommand.AddAlias("info");
            pfxInfoCommand.AddOption(new Option <FileInfo>(new string[] { "--certinput", "-ci" }, "Certificate file path (.pfx)"));
            pfxInfoCommand.AddOption(new Option <string>(new string[] { "--keytext", "-kt" }, "Key Text"));

            pfxInfoCommand.Handler = CommandHandler.Create <FileInfo, string, IConsole>((certInput, keyText, console) =>
            {
                try
                {
                    using var certificate = new X509Certificate2(certInput.FullName, keyText);
                    console.Out.WriteLine($"Thumbprint\t: {certificate.Thumbprint}");
                    console.Out.WriteLine($"Subject\t\t: {certificate.Subject}");
                    console.Out.WriteLine($"FriendlyName\t: {certificate.FriendlyName}");
                    console.Out.WriteLine($"Issuer\t\t: {certificate.Issuer}");
                    console.Out.WriteLine($"NotAfter\t: {certificate.NotAfter:dd-MMM-yyyy}");
                    console.Out.WriteLine($"NotBefore\t: {certificate.NotBefore:dd-MMM-yyyy}");
                    console.Out.WriteLine($"HasPrivateKey\t: {certificate.HasPrivateKey}");
                    console.Out.WriteLine($"PublicKey\t: {certificate.PublicKey.Oid.FriendlyName} ({certificate.PublicKey.Oid.Value})");
                    console.Out.WriteLine($"Signature\t: {certificate.SignatureAlgorithm.FriendlyName} ({certificate.SignatureAlgorithm.Value})");
                    console.Out.WriteLine($"SerialNumber\t: {certificate.SerialNumber}");
                    console.Out.WriteLine($"Version\t\t: V{certificate.Version}");
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                    return(22);
                }
                return(0);
            });

            var pfxCreateCommand = new Command("create", "Create Self Signed Certificate");

            pfxCreateCommand.AddOption(new Option <string>(new string[] { "--subjecttext", "-st" }, "Subject Text"));
            pfxCreateCommand.AddOption(new Option <string>(new string[] { "--keytext", "-kt" }, "Key Text"));
            pfxCreateCommand.AddOption(new Option <FileInfo>(new string[] { "--output", "-o" }, "Output file path"));

            pfxCreateCommand.Handler = CommandHandler.Create <string, string, FileInfo, IConsole>((subjectText, keyText, output, console) =>
            {
                try
                {
                    using var rsa                     = RSA.Create(3072);
                    var certificateRequest            = new CertificateRequest($"CN={subjectText}", rsa, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
                    var subjectAlternativeNameBuilder = new SubjectAlternativeNameBuilder();
                    subjectAlternativeNameBuilder.AddIpAddress(IPAddress.Loopback);
                    subjectAlternativeNameBuilder.AddIpAddress(IPAddress.IPv6Loopback);
                    subjectAlternativeNameBuilder.AddDnsName("localhost");
                    certificateRequest.CertificateExtensions.Add(subjectAlternativeNameBuilder.Build());

                    var certificate          = certificateRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(3));
                    certificate.FriendlyName = subjectText;

                    if (output == null)
                    {
                        console.Out.WriteLine("-----BEGIN CERTIFICATE-----\r\n");
                        console.Out.WriteLine(Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
                        console.Out.WriteLine("\r\n-----END CERTIFICATE-----");
                    }
                    else
                    {
                        File.WriteAllBytesAsync(output.FullName, certificate.Export(X509ContentType.Pfx, keyText));
                    }
                }
                catch (Exception ex)
                {
                    console.Out.WriteLine(ex.Message);
                    return(22);
                }
                return(0);
            });

            pfxCommand.Add(pfxEncCommand);
            pfxCommand.Add(pfxDecCommand);
            pfxCommand.Add(pfxInfoCommand);
            pfxCommand.Add(pfxCreateCommand);
            rootCommand.AddCommand(pfxCommand);

            return(rootCommand);
        }
示例#42
0
 public void SimulateMouseMovement(Type resolver)
 {
     Start(resolver, (InputCommands input) =>
     {
         var command = new Command();
         input.Add(command);
         command.Add(new MouseMovementTrigger());
         if (testResolver != null)
         {
             testResolver.SetMousePosition(Point.Half);
             testResolver.AdvanceTimeAndExecuteRunners(0.1f);
             testResolver.SetMousePosition(Point.One);
             testResolver.AdvanceTimeAndExecuteRunners(0.1f);
             Assert.IsTrue(command.TriggerFired);
         }
     });
 }
示例#43
0
        static void AddLaunchCommand(Command rootCommand)
        {
            var launchCommand = new Command("launch");

            rootCommand.Add(launchCommand);
        }
示例#44
0
    void AppendAddCommand(Command rootCommand)
    {
        var cmd = new Command("aad");

        rootCommand.Add(cmd);

        var tempdir = @"c:\temp\aad-dev";

        var loginAzCliOption = new Option <bool>("--login-az-cli",
                                                 "Login from az cli Service Principial, not from Environment vars");
        var dataDirOption = new Option <string>("--data-dir",
                                                () => tempdir,
                                                "The Directory which contains the data files. Defaults to Current Directory");
        var defaultPassordOption = new Option <string>("--default-password",
                                                       () => "Password01",
                                                       "The Default Passwort on User Creation");
        var userFilePatternOption = new Option <string>("--user-file-pattern",
                                                        () => "benutzer*.json",
                                                        "Pattern to read the User Files");
        var groupFilePatternOption = new Option <string>("--group-file-pattern",
                                                         () => "gruppen*.json",
                                                         "Pattern to read the Group Files");
        var dryRunOption = new Option <bool>("--dry-run",
                                             "Just dry run. No changes");

        var show = new Command("show", "Parse and list the Data Files and Load From AAD")
        {
            loginAzCliOption,
            dataDirOption,
            userFilePatternOption,
            groupFilePatternOption
        };

        cmd.Add(show);
        show.SetHandler((bool loginAzCli, string dataDir, string userFilePattern,
                         string groupFilePattern)
                        => _azureAdWorker.ShowAadUsersAndGroups(loginAzCli, dataDir, userFilePattern, groupFilePattern));

        var export = new Command("export", "Export existing AAD")
        {
            loginAzCliOption,
            dataDirOption,
            userFilePatternOption,
            groupFilePatternOption
        };

        cmd.Add(export);
        export.SetHandler((bool loginAzCli, string dataDir, string userFilePattern,
                           string groupFilePattern) =>
                          _azureAdWorker.ExportAadUsersAndGroups(loginAzCli, dataDir, userFilePattern, groupFilePattern));

        var deploy = new Command("deploy", "Deploy the AAD")
        {
            loginAzCliOption,
            dataDirOption,
            defaultPassordOption,
            userFilePatternOption,
            groupFilePatternOption,
            dryRunOption
        };

        cmd.Add(deploy);
        deploy.SetHandler((bool loginAzCli, string dataDir, string defaultPassword,
                           string userFilePattern, string groupFilePattern, bool dryRun) =>
                          _azureAdWorker
                          .DeployAadUsersAndGroups(loginAzCli,
                                                   dataDir,
                                                   defaultPassword,
                                                   userFilePattern,
                                                   groupFilePattern,
                                                   dryRun));
    }