Ejemplo n.º 1
0
        public void GivenCommandThatRequireFile_ShouldNotThrow(string command, string action)
        {
            string file = Path.GetTempFileName();

            try
            {
                IOption option = new OptionBuilder()
                                 .SetArgs(new[]
                {
                    command,
                    action,
                    $"File={file}"
                }
                                          .Concat(_storeArguments)
                                          .ToArray())
                                 .Build();

                option.File.Should().Be(file);

                GetValueFromObject <bool>(option, command).Should().BeTrue();
                GetValueFromObject <bool>(option, action).Should().BeTrue();
            }
            finally
            {
                File.Delete(file);
            }
        }
Ejemplo n.º 2
0
            internal virtual void AddOption(string longName, bool required, string description
                                            , string paramName)
            {
                Option option = OptionBuilder.Create(longName);

                options.AddOption(option);
            }
Ejemplo n.º 3
0
        public void GivenValidDeleteOption_WhenBuild_ShouldSucceed()
        {
            var args = new string[]
            {
                "Delete",
                "modelName=mymodel-temp",
                "VersionId=v1000",
                "Store:ContainerName=containerName",
                "Store:AccountName=accountName",
                "Store:AccountKey=dummyKey",
            };

            IOption option = new OptionBuilder()
                             .SetArgs(args)
                             .Build();

            option.Delete.Should().BeTrue();
            option.ModelName.Should().Be("mymodel-temp");
            option.VersionId.Should().Be("v1000");

            option.Store.Should().NotBeNull();
            option.Store !.ContainerName.Should().Be("containerName");
            option.Store !.AccountName.Should().Be("accountName");
            option.Store !.AccountKey.Should().Be("dummyKey");
        }
Ejemplo n.º 4
0
        private int CalculateScore(BoardPosition[,] boardState, TeamName teamName)
        {
            OptionBuilder        optionBuilder       = new OptionBuilder(teamName);
            List <BoardPosition> ownedBoardPositions = new List <BoardPosition>();
            int totalScore = 0;

            foreach (var bp in boardState)
            {
                if (bp.Owner == teamName)
                {
                    ownedBoardPositions.Add(bp);
                }
            }

            foreach (var pos in ownedBoardPositions)
            {
                Option option = optionBuilder.BuildOption(pos, boardState);
                foreach (var target in option.Targets)
                {
                    if (target.CheckIfTargetValid(boardState, teamName))
                    {
                        int score = target.FourChance(boardState, teamName);
                        if (score == 6 && IsBlockable(target))
                        {
                            score /= 4;
                        }
                        totalScore += score;
                    }
                }
            }
            return(totalScore);
        }
Ejemplo n.º 5
0
        private async Task <int> Run(string[] args)
        {
            Console.WriteLine(_programTitle);
            Console.WriteLine();

            IOption option = new OptionBuilder()
                             .SetArgs(args)
                             .Build();

            if (option.Help)
            {
                option.GetHelp()
                .Append(string.Empty)
                .ForEach(x => Console.WriteLine(x));

                return(_ok);
            }

            option.DumpConfigurations();

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            using (ServiceProvider serviceProvider = CreateContainer(option))
            {
                IServiceProvider container = serviceProvider;
                await InitializeRepository(option, container, cancellationTokenSource.Token);

                Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
                {
                    e.Cancel = true;
                    cancellationTokenSource.Cancel();
                    Console.WriteLine("Canceling...");
                };

                var activities = new Func <Task>[]
                {
                    () => option.Agent && option.Get ? container.GetRequiredService <AgentActivity>().Get(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Agent && option.List ? container.GetRequiredService <AgentActivity>().List(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Agent && option.Delete ? container.GetRequiredService <AgentActivity>().Delete(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Agent && option.Clear ? container.GetRequiredService <AgentActivity>().Clear(cancellationTokenSource.Token) : Task.CompletedTask,

                    () => option.Target && option.Get ? container.GetRequiredService <TargetActivity>().Get(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Target && option.List ? container.GetRequiredService <TargetActivity>().List(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Target && option.Delete ? container.GetRequiredService <TargetActivity>().Delete(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Target && option.Clear ? container.GetRequiredService <TargetActivity>().Clear(cancellationTokenSource.Token) : Task.CompletedTask,

                    () => option.Monitor ? container.GetRequiredService <MonitorActivity>().Run(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Template ? container.GetRequiredService <TemplateActivity>().Create() : Task.CompletedTask,
                    () => option.Import ? container.GetRequiredService <ImportActivity>().Import(cancellationTokenSource.Token) : Task.CompletedTask,
                    () => option.Balance ? container.GetRequiredService <BalanceActivity>().BalanceAgents(cancellationTokenSource.Token) : Task.CompletedTask,
                };

                await activities
                .ForEachAsync(async x => await x());
            }

            Console.WriteLine();
            Console.WriteLine("Completed");
            return(_ok);
        }
Ejemplo n.º 6
0
        public void GivenValidBindOption_WhenBuild_ShouldSucceed()
        {
            var args = new string[]
            {
                "Bind",
                "modelName=model-temp",
                "VersionId=v1000",
                "VsProject=c:\\folder\\installPath\\testproject.csproj",
                "Store:ContainerName=containerName",
                "Store:AccountName=accountName",
                "Store:AccountKey=dummyKey",
            };

            IOption option = new OptionBuilder()
                             .SetArgs(args)
                             .Build();

            option.ModelName.Should().Be("model-temp");
            option.VersionId.Should().Be("v1000");

            option.Store.Should().NotBeNull();
            option.Store !.ContainerName.Should().Be("containerName");
            option.Store !.AccountName.Should().Be("accountName");
            option.Store !.AccountKey.Should().Be("dummyKey");
        }
    public async Task Unspecified_option_arguments_with_no_default_value_are_bound_to_type_default(
        Type parameterType,
        object expectedValue)
    {
        var captureMethod = GetType()
                            .GetMethod(nameof(CaptureMethod), BindingFlags.NonPublic | BindingFlags.Static)
                            .MakeGenericMethod(parameterType);

        var handler = CommandHandler.Create(captureMethod);

        var command = new Command("command")
        {
            OptionBuilder.CreateOption("-x", parameterType)
        };

        command.Handler = handler;

        var parseResult = command.Parse("");

        var invocationContext = new InvocationContext(parseResult);

        await handler.InvokeAsync(invocationContext);

        var boundValue = ((BoundValueCapturer)invocationContext.InvocationResult).BoundValue;

        boundValue.Should().Be(expectedValue);
    }
Ejemplo n.º 8
0
        public void OptionBuilder_CreateOption_Command_Found_No_SubCommands()
        {
            string expectedCommand         = "Storage";
            int    expectedNumberOfOptions = 0;

            string environmentSetting = $"{{\"UseLiveClient\": \"True\"}}";
            NullLogger <Microsoft.Extensions.Logging.ILogger> logger = new NullLogger <Microsoft.Extensions.Logging.ILogger>();

            BuildEnvironment(environmentSetting);

            CfgCommand command = TestDataBuilder.CreateCfgCommand(expectedCommand);

            CfgCommandList commandList = new CfgCommandList();

            commandList.Commands = new List <CfgCommand>();
            commandList.Commands.Add(command);

            OptionBuilder builder = OptionBuilder.Instance(logger);

            builder.CfgCommands = commandList;

            GetDataHandler handler = new GetDataHandler(new NullLogger <GetDataHandler>());

            List <IOption> selectableOptions = builder.BuildAvailableOptions(handler);

            Assert.AreEqual(expectedNumberOfOptions, selectableOptions.Count);
        }
Ejemplo n.º 9
0
        private async Task <int> Run(string[] args)
        {
            Console.WriteLine(_programTitle);
            Console.WriteLine();

            ConfigOption option = new OptionBuilder().Build(args);

            try
            {
                using (ServiceProvider container = BuildContainer(option))
                {
                    var rc = new RootCommand()
                    {
                        new Option <RunEnvironment>(new[] { "--environment", "-e" }, "Specify environment to use"),

                        container.GetRequiredService <ListCommand>(),
                        container.GetRequiredService <GetCommand>(),
                        container.GetRequiredService <DeleteCommand>(),
                        container.GetRequiredService <SetCommand>(),
                    };

                    return(await rc.InvokeAsync(args));
                }
            }
            finally
            {
                Console.WriteLine();
                Console.WriteLine("Completed");
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Parses input parameters and finds the correct service and command handler for executing the command.
        /// </summary>
        /// <param name="input">
        /// User input from command line arguments, split into list of parameters separated by space.
        /// Commands are structured as follows: [command] [subCommand] [options]
        /// </param>
        /// <returns>A commandHandler that can execute the command given by user input</returns>
        private ISubCommandHandler ProcessArgs(string[] input)
        {
            ISubCommandHandler subCommandHandler = ServiceProvider.GetServices <ISubCommandHandler>()
                                                   .FirstOrDefault(s =>
                                                                   string.Equals(s.Name, input[1], StringComparison.OrdinalIgnoreCase) &&
                                                                   string.Equals(s.CommandProvider, input[0], StringComparison.OrdinalIgnoreCase));

            if (subCommandHandler != null)
            {
                subCommandHandler.BuildSelectableCommands();
                subCommandHandler.DictOptions = ParseArguments(input);
                OptionBuilder.Instance(_logger).AssignValueToCliOptions(subCommandHandler);
                return(subCommandHandler);
            }

            // No command found, find help command to display help.
            IHelp helpService = ServiceProvider.GetServices <IHelp>().FirstOrDefault();

            if (helpService != null)
            {
                helpService.GetHelp();
            }
            else
            {
                _logger.LogError("Help is not found");
            }

            return(null);
        }
Ejemplo n.º 11
0
        public void GivenValidDownloadOption_WhenBuild_ShouldSucceed()
        {
            var args = new string[]
            {
                "DOWNLOAD",
                "PackageFile=c:\\zipfile2.mlPackage",
                "modelName=mymodel99",
                "VersionId=x1000",
                "Store:ContainerName=containerName",
                "Store:AccountName=accountName",
                "Store:AccountKey=dummyKey",
            };

            IOption option = new OptionBuilder()
                             .SetArgs(args)
                             .Build();

            option.Download.Should().BeTrue();
            option.PackageFile.Should().Be("c:\\zipfile2.mlPackage");
            option.ModelName.Should().Be("mymodel99");
            option.VersionId.Should().Be("x1000");

            option.Store.Should().NotBeNull();
            option.Store !.ContainerName.Should().Be("containerName");
            option.Store !.AccountName.Should().Be("accountName");
            option.Store !.AccountKey.Should().Be("dummyKey");
        }
        public async Task Option_arguments_are_bound_by_name_to_the_constructor_parameters_of_method_parameters(
            Type type,
            string commandLine,
            object expectedValue)
        {
            var complexParameterType = typeof(ClassWithCtorParameter <>).MakeGenericType(type);

            var handlerType = typeof(ClassWithMethodHavingParameter <>).MakeGenericType(complexParameterType);

            var handlerMethod = handlerType.GetMethod("HandleAsync");

            var handler = HandlerDescriptor.FromMethodInfo(handlerMethod)
                          .GetCommandHandler();

            var command = new Command("the-command")
            {
                OptionBuilder.CreateOption("--value", type)
            };

            var console = new TestConsole();

            await handler.InvokeAsync(
                new InvocationContext(command.Parse(commandLine), console));

            console.Out.ToString().Should().Be($"ClassWithCtorParameter<{type.Name}>: {expectedValue}");
        }
Ejemplo n.º 13
0
        public void GivenNoOption_ShouldReturnHelp()
        {
            IOption option = new OptionBuilder()
                             .Build();

            option.Help.Should().BeTrue();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Register option for the command
        /// </summary>
        /// <param name="buildOption">Action to configure option using builder</param>
        /// <returns>Self instance</returns>
        public CommandConfigurator RegisterOption <T>(Action <OptionBuilder <T> > buildOption)
        {
            var optionBuilder = new OptionBuilder <T>();

            buildOption(optionBuilder);

            return(RegisterOptionInstance <T>(optionBuilder.Build()));
        }
Ejemplo n.º 15
0
        public void GivenHelpOption_ShouldReturnHel()
        {
            IOption option = new OptionBuilder()
                             .SetArgs(new[] { "help" })
                             .Build();

            option.Help.Should().BeTrue();
        }
Ejemplo n.º 16
0
        private static FakeGenerationOptions GetOptions <T>(Action <IFakeBuilderOptionsBuilder <T> > options)
        {
            var builder = new OptionBuilder <T>();

            options(builder);

            return(builder.Options);
        }
Ejemplo n.º 17
0
 protected Option(OptionBuilder builder)
 {
     this.StockPrice = builder.StockPrice;
     this.Strike = builder.Strike;
     this.Expiry = builder.Expiry;
     this.InterestRate = builder.InterestRate;
     this.Volatility = builder.Volatility;
     this.Income = builder.Income;
 }
Ejemplo n.º 18
0
        public static void Main(string[] args)
        {
            IOption option = new OptionBuilder()
                             .SetArgs(args)
                             .Build();

            CreateHostBuilder(args, option)
            .Build()
            .Run();
        }
Ejemplo n.º 19
0
        public void TestOptionBuilder_WhenDeployIsTrue_DeployShouldBeTrue()
        {
            var args = new string[]
            {
                "deploy=true"
            };

            IOption option = new OptionBuilder()
                             .Build(args);

            option.Deploy.Should().BeTrue();
        }
Ejemplo n.º 20
0
 /**
  * Private constructor used by the nested Builder class.
  *
  * @param builder builder used to create this option
  */
 private Option(OptionBuilder builder)
 {
     this.argName      = builder.argName;
     this.description  = builder.description;
     this.longOpt      = builder.longOpt;
     this.numberOfArgs = builder.numberOfArgs;
     this.opt          = builder.opt;
     this.optionalArg  = builder.optionalArg;
     this.required     = builder.required;
     this.type         = builder.type;
     this.valuesep     = builder.valuesep;
 }
Ejemplo n.º 21
0
            private static Options BuildCliOptions()
            {
                Options     opts  = new Options();
                Option      file  = OptionBuilder.Create("f");
                Option      paths = OptionBuilder.Create("p");
                OptionGroup group = new OptionGroup();

                group.AddOption(file);
                group.AddOption(paths);
                opts.AddOptionGroup(group);
                return(opts);
            }
Ejemplo n.º 22
0
 internal CommandLineOpts()
 {
     geteditsizeOpt = new Option("geteditsize", "return the number of uncheckpointed transactions on the NameNode"
                                 );
     checkpointOpt = OptionBuilder.Create("checkpoint");
     formatOpt     = new Option("format", "format the local storage during startup");
     helpOpt       = new Option("h", "help", false, "get help information");
     options.AddOption(geteditsizeOpt);
     options.AddOption(checkpointOpt);
     options.AddOption(formatOpt);
     options.AddOption(helpOpt);
 }
Ejemplo n.º 23
0
        public void GivenValidHelpOption_WhenBuild_ShouldSucceed()
        {
            var args = new string[]
            {
                "help"
            };

            IOption option = new OptionBuilder()
                             .SetArgs(args)
                             .Build();

            option.Help.Should().BeTrue();
        }
Ejemplo n.º 24
0
        public static async Task Main(string[] args)
        {
            IOption option = new OptionBuilder()
                             .SetArgs(args)
                             .Build();

            IHost host = CreateHostBuilder(args, option)
                         .Build();

            await InitializeDatabase(host, option);

            await host.RunAsync();
        }
Ejemplo n.º 25
0
        public void GivenValidDownloadOptionWithConfigFile_WhenBuild_ShouldSucceed()
        {
            var tempConfigFile = Path.Combine(Path.GetTempPath(), "test-configfile.json");

            IJson json = new Json();

            dynamic config = new
            {
                Download    = true,
                PackageFile = "c:\\zipfile2.mlPackage",
                ModelName   = "ml-model-temp",
                VersionID   = "v10-0-0-1",
                Store       = new
                {
                    ContainerName = "containerName",
                    AccountName   = "accountName",
                    AccountKey    = "accountKey",
                },
            };

            string data = json.Serialize(config);

            File.WriteAllText(tempConfigFile, data);

            try
            {
                var args = new string[]
                {
                    $"configfile={tempConfigFile}",
                    "ModelName=ml-model-temp-next-version",
                };

                IOption option = new OptionBuilder()
                                 .SetArgs(args)
                                 .Build();

                option.Download.Should().BeTrue();
                option.PackageFile.Should().Be("c:\\zipfile2.mlPackage");
                option.ModelName.Should().Be("ml-model-temp-next-version");
                option.VersionId.Should().Be("v10-0-0-1");

                option.Store.Should().NotBeNull();
                option.Store !.ContainerName.Should().Be("containerName");
                option.Store !.AccountName.Should().Be("accountName");
                option.Store !.AccountKey.Should().Be("accountKey");
            }
            finally
            {
                File.Delete(tempConfigFile);
            }
        }
Ejemplo n.º 26
0
        public void TestOptionBuilder_WhenDeployAndCustomerCount_CustomerCountAndDeployBe20AndTrue()
        {
            var args = new string[]
            {
                "deploy",
                "customercount=20"
            };

            IOption option = new OptionBuilder()
                             .Build(args);

            option.Deploy.Should().BeTrue();
            option.CustomerCount.Should().Be(20);
        }
Ejemplo n.º 27
0
        public static void Main(string[] args)
        {
            Option option = new OptionBuilder()
                            .SetArgs(args)
                            .Build();

            IHost host = CreateHostBuilder(args, option).Build();

            ILogger <Program> logger = host.Services.GetRequiredService <ILogger <Program> >();

            option.DumpConfigurations(logger);

            host.Run();
        }
Ejemplo n.º 28
0
            private Options BuildOptions()
            {
                Options opts = new Options();

                opts.AddOption(OptionBuilder.Create("s"));
                opts.AddOption(OptionBuilder.Create("r"));
                opts.AddOption(OptionBuilder.Create("c"));
                opts.AddOption(OptionBuilder.Create("m"));
                opts.AddOption(OptionBuilder.Create("t"));
                opts.AddOption(OptionBuilder.Create("p"));
                opts.AddOption(OptionBuilder.Create('h'));
                opts.AddOption(OptionBuilder.Create('e'));
                opts.AddOption(OptionBuilder.Create('?'));
                return(opts);
            }
Ejemplo n.º 29
0
        public static IOption CreateOption(string optionName, string dataType, string description, string apiName)
        {
            Type baseType = null;

            Type t = OptionBuilder.GetSystemType(dataType, out baseType);

            var     combinedType = baseType.MakeGenericType(t);
            IOption option       = (IOption)Activator.CreateInstance(combinedType);

            option.Description = description;
            option.Name        = optionName;
            option.IsAssigned  = false;
            option.ApiName     = apiName;
            return(option);
        }
Ejemplo n.º 30
0
        public static void Main(string[] args)
        {
            Option?option = new OptionBuilder()
                            .SetArgs(args)
                            .Build()
                            .VerifyNotNull("Help is not supported");

            IHost host = CreateHostBuilder(args, option).Build();

            ILogger <Program> logger = host.Services.GetRequiredService <ILogger <Program> >();

            logger.LogConfigurations(option);

            host.Run();
        }
Ejemplo n.º 31
0
        public void Should_register_translator_with_EF()
        {
            var translatorMock = new Mock <IExpressionFragmentTranslator>();

            OptionBuilder.AddExpressionFragmentTranslator(translatorMock.Object);
            DbContextWithSchema.Database.EnsureCreated();

            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            DbContextWithSchema.TestEntities.Where(e => e.Id == Guid.Empty).ToList();

            // 3 calls:
            //   e.Id == Guid.Empty
            //   e.Id
            //   Guid.Empty
            translatorMock.Verify(t => t.Translate(It.IsAny <Expression>()), Times.Exactly(3));
        }