コード例 #1
0
ファイル: GameShell.cs プロジェクト: kesac/WorldGM
        private void GameLoop()
        {
            var header = new Rule($"\n[grey]World of {this.Game.World.Name}[/]")
                         .RuleStyle(Style.Parse("white dim"))
                         .LeftAligned();

            AnsiConsole.Write(header);

            AnsiConsole.MarkupLine("[green]You are currently in the city of {0}.[/]", this.Game.HomeCity.Name);
            AnsiConsole.MarkupLine("[green]There are {0} members in your guild.[/]", this.Game.GuildMembers.Count);

            string input = string.Empty;

            while (input != "exit")
            {
                AnsiConsole.Write(new Rule());

                input = AnsiConsole.Prompt(this.IngameMenu).ToLower();

                if (input == "save")
                {
                    this.SaveGame();
                }
            }
        }
コード例 #2
0
ファイル: Commands.cs プロジェクト: bryjen/Calculator
        public static void Execute(string command, string fromWhere)
        {
            var mainCommand = Regex.Match(command, "/[a-zA-Z]+").Value.Trim();
            var tokens      = new Regex("/[a-zA-Z]+").Replace(command, "").Trim();

            switch (mainCommand)
            {
            case "/exit":
                AnsiConsole.MarkupLine("[blue]Bye![/]");
                Environment.Exit(0);
                return;

            case "/help":
                ExecuteHelp(tokens, fromWhere);
                break;

            case "/clear":
                if (!new Regex("/clear").Replace(command, "").Equals(""))
                {
                    AnsiConsole.MarkupLine("[red]Unknown token after \"/clear\"![/]");
                    return;
                }
                Console.Clear();
                return;

            case "/angle":
                ChangeAngle(tokens);
                break;

            default:
                AnsiConsole.MarkupLine("[red]Unknown Command![/]");
                break;
            }
        }
コード例 #3
0
        private async Task <IList <WitsmlRisk> > GetRisks(string wellUid, string wellboreUid, string source, string lastChanged)
        {
            var query = new WitsmlRisks
            {
                Risks = new WitsmlRisk
                {
                    UidWell     = wellUid,
                    UidWellbore = wellboreUid,
                    CommonData  = new WitsmlCommonData
                    {
                        SourceName     = source,
                        DTimLastChange = lastChanged
                    }
                }.AsSingletonList()
            };

            try
            {
                var result = await witsmlClient.GetFromStoreAsync(query, new OptionsIn(ReturnElements.All));

                return(result?.Risks
                       .OrderBy(risk => risk.NameWellbore)
                       .ThenBy(risk => DateTime.Parse(risk.CommonData.DTimLastChange))
                       .ToList());
            }
            catch (TimeoutException)
            {
                AnsiConsole.MarkupLine("\nThe request timed out. You might need to filter your request to reduce the query result".WithColor(Color.Red1));
                return(new List <WitsmlRisk>());
            }
        }
コード例 #4
0
        static int Main(string[] args)
        {
            var rootCommand = new RootCommand("CLI for executing various actions against elmah.io")
            {
                new Option <bool>("--nologo", "Doesn't display the startup banner or the copyright message"),
            };

            rootCommand.AddCommand(ClearCommand.Create());
            rootCommand.AddCommand(DataloaderCommand.Create());
            rootCommand.AddCommand(DeploymentCommand.Create());
            rootCommand.AddCommand(ExportCommand.Create());
            rootCommand.AddCommand(LogCommand.Create());
            rootCommand.AddCommand(SourceMapCommand.Create());
            rootCommand.AddCommand(TailCommand.Create());

            if (args == null || args.All(arg => arg != "--nologo"))
            {
                AnsiConsole.Write(new FigletText("elmah.io")
                                  .LeftAligned()
                                  .Color(new Color(13, 165, 142)));
                AnsiConsole.MarkupLine("[yellow]Copyright (C)[/] [rgb(13,165,142)]elmah.io[/]. All rights reserved.");
            }

            args = args.Where(arg => arg != "--nologo").ToArray();
            AnsiConsole.WriteLine();

            return(rootCommand.InvokeAsync(args).Result);
        }
コード例 #5
0
        public static async Task RunAsync(Source source, Compiler compiler)
        {
            if (await InitialTestAsync(compiler))
            {
                return;
            }

            IReadOnlyCollection <Mutation> mutants = await Mutator.MutateAsync(source.Production);

            int padding = mutants.Count.ToString().Length;

            var report = new Report();
            int i      = 0;

            foreach (IGrouping <SyntaxNode, Mutation> group in mutants.GroupBy(mutant => mutant.OriginalNode))
            {
                SyntaxNode mutated = group.Key;
                AnsiConsole.MarkupLine($"[bold]{mutated}[/]");

                foreach (Mutation mutant in group)
                {
                    bool hasFailed = await MutationTestAsync(compiler, i ++, mutant, padding);

                    report.Increment(hasFailed);
                }
            }

            report.WriteToConsole();
        }
コード例 #6
0
        private int List(Settings settings)
        {
            var examples = _finder.FindExamples();

            if (examples.Count == 0)
            {
                AnsiConsole.Markup("[yellow]No examples could be found.[/]");
                return(0);
            }

            AnsiConsole.WriteLine();

            var rows = new Grid().Collapse();

            rows.AddColumn();
            foreach (var group in examples.GroupBy(ex => ex.Group))
            {
                rows.AddRow(CreateTable(settings, group.Key, group));
                rows.AddEmptyRow();
            }

            AnsiConsole.Render(rows);

            AnsiConsole.MarkupLine("Type [blue]dotnet example --help[/] for help");

            return(0);
        }
コード例 #7
0
        private static void Main(string[] args)
        {
            var culture = CultureInfo.GetCultureInfo("en-US");

            if (args is null || args.Length != 1)
            {
                throw new InvalidOperationException("usage: advent <day>");
            }

            var number = int.Parse(args[0], culture.NumberFormat);
            var day    = CreateDay(number);

            if (day is null)
            {
                throw new InvalidOperationException($"unable to run day {number}");
            }

            day.LoadInput();
            day.Header();

            AnsiConsole.MarkupLine("Part A:");
            AnsiConsole.MarkupLine($"\t[bold yellow]{day.PartA()}[/]");

            AnsiConsole.MarkupLine("Part B:");
            AnsiConsole.MarkupLine($"\t[bold yellow]{day.PartB()}[/]");
        }
コード例 #8
0
        private static async Task Mult()
        {
            Console.Clear();

            var factors = new List <int>();
            int?factor;

            do
            {
                factor = PromptSelection("Enter an integer, or 'X' to end:");
                if (factor.HasValue)
                {
                    factors.Add(factor.Value);
                }
            }while (factor.HasValue);

            if (!factors.Any())
            {
                AnsiConsole.MarkupLine($"There are no factors, no operation performed\n");
                return;
            }

            var multRequest = new MultRequest {
                Factors = factors
            };
            var response = await CalculatorServiceClient.MultAsync(multRequest);

            AnsiConsole.MarkupLine($"The product of the factors is: {response.Product}\n");
        }
コード例 #9
0
        private static async Task Div()
        {
            Console.Clear();

            var dividend = PromptSelection("Enter the dividend, or 'X' to end:");

            if (dividend is null)
            {
                AnsiConsole.MarkupLine($"There is no dividend, no operation performed\n");
                return;
            }

            var divisor = PromptSelection("Enter the divisor, or 'X' to end:");

            if (dividend is null)
            {
                AnsiConsole.MarkupLine($"There is no divisor, no operation performed\n");
                return;
            }

            var divRequest = new DivRequest {
                Dividend = dividend.Value, Divisor = divisor.Value
            };
            var response = await CalculatorServiceClient.DivAsync(divRequest);

            AnsiConsole.MarkupLine($"The quotient is: {response.Quotient} and the remainder is {response.Remainder}\n");
        }
コード例 #10
0
        private void WriteSummaries(LamarServicesInput input, IGrouping <Assembly, IServiceFamilyConfiguration>[] configurations, WhatDoIHaveDisplay display,
                                    IContainer container)
        {
            if (display == WhatDoIHaveDisplay.Summary)
            {
                AnsiConsole.MarkupLine("[bold]Key:[/] ");

                var rule = new Rule($"[blue]Assembly Name (Assembly Version)[/]")
                {
                    Alignment = Justify.Left
                };
                AnsiConsole.Render(rule);


                var node = new Tree("{Service Type Namespace}");
                node.AddNode("{Service Type Full Name}").AddNode("{Lifetime}: {Description of Registration}");
                AnsiConsole.Render(node);
                Console.WriteLine();
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("Build Plans for registrations built by calling constructors");
                Console.WriteLine();
            }


            foreach (var group in configurations)
            {
                WriteAssemblyServices(input, @group, display, container);
            }
        }
コード例 #11
0
        private static async Task Sub()
        {
            Console.Clear();

            var minuend = PromptSelection("Enter the minuend, or 'X' to end:");

            if (minuend is null)
            {
                AnsiConsole.MarkupLine($"There is no minuend, no operation performed\n");
                return;
            }

            var substrahend = PromptSelection("Enter the substrahend, or 'X' to end:");

            if (minuend is null)
            {
                AnsiConsole.MarkupLine($"There is no substrahend, no operation performed\n");
                return;
            }

            var subRequest = new SubRequest {
                Minuend = minuend.Value, Subtrahend = substrahend.Value
            };
            var response = await CalculatorServiceClient.SubAsync(subRequest);

            AnsiConsole.MarkupLine($"The difference is: {response.Difference}\n");
        }
コード例 #12
0
ファイル: CalendarDataProvider.cs プロジェクト: YXGuan/guppi
        private async Task Execute(bool agenda)
        {
            var now = DateTime.Now;

            var query = new CalendarEventsQuery
            {
                MinDate = now,
                MaxDate = agenda ? new DateTime(now.Year, now.Month, now.Day, 23, 59, 59) : null
            };

            try
            {
                var events = await _mediator.Send(query);

                string title = agenda ? ":calendar: Today's agenda" : ":tear_off_calendar: Next event";

                AnsiConsoleHelper.TitleRule(title);

                try
                {
                    if (events.Count() > 0)
                    {
                        bool found = false;
                        foreach (var eventItem in events)
                        {
                            string start = eventItem.Start?.ToString(agenda ? "HH:mm" : "MMM dd HH:mm");
                            if (string.IsNullOrEmpty(start))
                            {
                                continue;
                            }
                            string end = eventItem.End?.ToString("-HH:mm") ?? "";
                            AnsiConsole.MarkupLine($"{eventItem.Start.GetEmoji()} [white]{start}{end}\t[/][silver]{eventItem.Summary}[/]");
                            found = true;
                            if (!agenda)
                            {
                                return;
                            }
                        }
                        if (found)
                        {
                            return;
                        }
                    }
                    AnsiConsole.MarkupLine("[white][[No upcoming events found.]][/]");
                }
                finally
                {
                    AnsiConsoleHelper.Rule("white");
                }
            }
            catch (UnauthorizedException ue)
            {
                AnsiConsole.MarkupLine($"[red][[:cross_mark: ${ue.Message}]][/]");
                return;
            }
            catch (UnconfiguredException ue)
            {
                AnsiConsole.MarkupLine($"[yellow][[:yellow_circle: ${ue.Message}]][/]");
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: shunty-gh/AdventOfCode2020
        static async Task Main(string[] args)
        {
            var timer = Stopwatch.StartNew();

            try
            {
                logger = InitialiseLogging();
                try
                {
                    AvailableDays = LoadDays().ToList();

                    await BuildCommandLine()
                    .UseDefaults()
                    .Build()
                    .InvokeAsync(args);
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "Error running AoC with args: {@Args}", args);
                    AnsiConsole.WriteException(ex);
                }
                finally
                {
                    Serilog.Log.CloseAndFlush();
                }
            }
            finally
            {
                timer.Stop();
                AnsiConsole.MarkupLine($"[blue]All completed in [yellow]{timer.ElapsedMilliseconds}[/]ms[/]");
            }
        }
コード例 #14
0
        public static T Load <T>(string name) where T : Configuration, new()
        {
            var configurationFile = Path.Combine(ConfigurationDirectory, $"{name}.json");

            try
            {
                if (File.Exists(configurationFile))
                {
                    string json   = File.ReadAllText(configurationFile);
                    T      config = JsonSerializer.Deserialize <T>(json);
                    config.Name = name;
                    config.ConfigurationFile = configurationFile;
                    return(config);
                }
            }
            catch (Exception ex)
            {
                AnsiConsole.MarkupLine($"[red][[:cross_mark: Failed to load the configuration file for {name}]][/]");
                AnsiConsole.WriteException(ex,
                                           ExceptionFormats.ShortenPaths | ExceptionFormats.ShortenTypes |
                                           ExceptionFormats.ShortenMethods | ExceptionFormats.ShowLinks);
            }
            return(new T()
            {
                Name = name,
                ConfigurationFile = configurationFile
            });
        }
コード例 #15
0
        private static IExample GetExampleFromPromptChoice(IServiceScope serviceScope)
        {
            var choice = AnsiConsole.Prompt(
                new TextPrompt <int>("Which example do you want to run (0 for exit) ?")
                .InvalidChoiceMessage("[red]That's not a valid choice[/]")
                .DefaultValue(0)
                .AddChoice(1)
                .AddChoice(2)
                .AddChoice(3)
                .AddChoice(4));

            if (choice == 0)
            {
                if (AnsiConsole.Capabilities.SupportLinks)
                {
                    var link = @"https://github.com/aimenux/SpectreDemo";
                    AnsiConsole.MarkupLine($"[link={link}]Click to go to github repo[/]!");
                }

                return(null);
            }

            var examples = serviceScope.ServiceProvider.GetServices <IExample>().ToList();

            return(examples.SingleOrDefault(x => x.GetType().Name.EndsWith($"{choice}")));
        }
コード例 #16
0
        private static async Task Add()
        {
            Console.Clear();

            var addends = new List <int>();
            int?addend;

            do
            {
                addend = PromptSelection("Enter an integer, or 'X' to end:");
                if (addend.HasValue)
                {
                    addends.Add(addend.Value);
                }
            }while (addend.HasValue);

            if (!addends.Any())
            {
                AnsiConsole.MarkupLine($"There are no addends, no operation performed\n");
                return;
            }

            var addRequest = new AddRequest {
                Addends = addends
            };
            var response = await CalculatorServiceClient.AddAsync(addRequest);

            AnsiConsole.MarkupLine($"The sum of the addends is: {response.Sum}\n");
        }
コード例 #17
0
        static void Main(string[] args)
        {
            var survey    = new Survey("questions.json");
            var questions = survey.GetQuestions();

            var voterAnswerMap = new SortedDictionary <string, List <Answer> >();

            // var users = getUsers();
            // hardcoded for now
            string[] users = { "Dan", "Leon", "Niki" };

            foreach (var user in users)
            {
                // Styled text announcing the next user
                var rule = new Rule("[red]" + user + "[/]");
                rule.LeftAligned();
                AnsiConsole.Render(rule);
                AnsiConsole.MarkupLine("[bold]" + user + "[/] - It's your turn to answer the questions.");

                var answers = new List <Answer>();
                foreach (var q in questions)
                {
                    var answer = q.ask();
                    answers.Add(answer);
                }
                voterAnswerMap.Add(user, answers);
            }


            // Create a canvas

            YesNoDetailedResult detailedResult = new YesNoDetailedResult();

            detailedResult.show(7, 5);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: rnelson/adventofcode
        private static void Main(string[] args)
        {
            var culture = CultureInfo.GetCultureInfo("en-US");

            if (args is null || args.Length != 1)
            {
                throw new InvalidOperationException("usage: advent <day>");
            }

            var number = int.Parse(args[0], culture.NumberFormat);
            var day    = CreateDay(number);

            if (day is null)
            {
                throw new InvalidOperationException($"unable to run day {number}");
            }

            day !.Header();
            if (!day !.Test())
            {
                AnsiConsole.MarkupLine($"[bold red]error[/]: test(s) for day {number} failed");
                return;
            }

            day !.PartA();
            day !.PartB();
        }
コード例 #19
0
        public override async Task <int> ExecuteAsync(CommandContext context, CheckSettings settings)
        {
            try
            {
                _pathToCsProjFile = _csProjFileService.GetPathToCsProjFile(settings.PathToCsProjFile);
            }
            catch (CsProjFileNotFoundException ex)
            {
                AnsiConsole.Markup($"[dim]WARN:[/] [red]{ex.Message}[/]");
                return(await Task.FromResult(-1));
            }

            AnsiConsole.MarkupLine($"Checking versions for [silver]{_pathToCsProjFile}[/]");

            await _nuGetPackagesService.GetPackagesDataFromCsProjFileAsync(_pathToCsProjFile, _packages);

            if (_packages.Count == 0)
            {
                AnsiConsole.MarkupLine($"Could not find any packages in [silver]{_pathToCsProjFile}[/]");
                return(await Task.FromResult(0));
            }

            await _nuGetPackagesService.GetPackagesDataFromNugetRepositoryAsync(_pathToCsProjFile, _packages);

            PrintResult();

            return(await Task.FromResult(0));
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: Meir017/GraphQLinq
        private static void RenderLaunches(List <Launch> launches)
        {
            var table = new Table().Title("Launches");

            table.AddColumn(nameof(Launch.Mission_name), column => column.Width = 12).AddColumn(nameof(Launch.Launch_date_utc), column => column.Width = 15)
            .AddColumn(nameof(Launch.Rocket.Rocket_name)).AddColumn(nameof(Launch.Links)).AddColumn(
                $"{nameof(Launch.Rocket.Second_stage.Payloads)}  {nameof(Payload.Manufacturer)}", column => column.Width = 12);

            foreach (var launch in launches)
            {
                var linksTable = new Table().AddColumn(nameof(launch.Links));
                linksTable.AddRow(new Markup($"[link={launch.Links.Article_link}]Article_link - {launch.Links.Article_link}[/]"));
                linksTable.AddRow(new Markup($"[link={launch.Links.Video_link}]Video_link - {launch.Links.Video_link}[/]"));
                linksTable.AddRow(new Markup($"[link={launch.Links.Presskit}]Presskit - {launch.Links.Presskit}[/]"));
                linksTable.AddRow(new Markup($"[link={launch.Links.Reddit_launch}]Reddit_launch - {launch.Links.Reddit_launch}[/]"));
                linksTable.AddRow(new Markup($"[link={launch.Links.Wikipedia}]Wikipedia - {launch.Links.Wikipedia}[/]"));

                var payloadManufacturers = string.Join(Environment.NewLine, launch.Rocket.Second_stage.Payloads.Where(payload => payload != null)
                                                       .Select(p => p.Manufacturer));

                table.AddRow(new Markup(launch.Mission_name),
                             new Markup(launch.Launch_date_utc.ToString()),
                             new Markup(launch.Rocket.Rocket_name),
                             linksTable,
                             new Markup(payloadManufacturers));
            }

            AnsiConsole.Render(table);
            AnsiConsole.MarkupLine("");
        }
コード例 #21
0
        public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings)
        {
            try
            {
                AnsiConsole.MarkupLine("[cyan]-=[[ EscapeFromTarkov-Trainer Universal Installer ]]=-[/]");
                AnsiConsole.WriteLine();

                var installation = Installation.GetTargetInstallation(settings.Path, "Please select from where to uninstall the trainer");
                if (installation == null)
                {
                    return((int)ExitCode.NoInstallationFound);
                }

                AnsiConsole.MarkupLine($"Target [green]EscapeFromTarkov ({installation.Version})[/] in [blue]{installation.Location}[/].");

                if (!RemoveFile(Path.Combine(installation.Managed, "NLog.EFT.Trainer.dll")))
                {
                    return((int)ExitCode.RemoveDllFailed);
                }

                if (!RemoveFile(Path.Combine(installation.Data, "outline")))
                {
                    return((int)ExitCode.RemoveOutlineFailed);
                }

                RemoveOrPatchConfiguration(installation);
            }
            catch (Exception ex)
            {
                AnsiConsole.MarkupLine($"[red]Error: {ex.Message}. Please file an issue here : https://github.com/sailro/EscapeFromTarkov-Trainer/issues [/]");
                return((int)ExitCode.Failure);
            }

            return((int)ExitCode.Success);
        }
        public async Task RunAsync()
        {
            var faultyOperationContext = new OperationContext();

            faultyOperationContext.ResponseReceived += (sender, args) =>
            {
                if (new Random().Next(3) == 0)
                {
                    args.Response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                }
            };

            var table = _cloudTableClient.GetTableReference("products");
            await table.CreateIfNotExistsAsync();

            await Task.WhenAll(_seedData.Select(async(product) =>
            {
                try
                {
                    await table.ExecuteAsync(TableOperation.InsertOrReplace(product),
                                             new TableRequestOptions(), faultyOperationContext);
                    AnsiConsole.MarkupLine($"[green]{product.Ean13} seeded.[/]");
                }
                catch (Exception exception)
                {
                    AnsiConsole.MarkupLine($"[red]{product.Ean13} failed.[/]");
                }
            }));
        }
コード例 #23
0
 private static void WriteLogMessage()
 {
     AnsiConsole.MarkupLine(
         "[grey]LOG:[/] " +
         DescriptionGenerator.Generate() +
         "[grey]...[/]");
 }
コード例 #24
0
        private async Task ListLights(string ip)
        {
            try
            {
                var lights = await _mediator.Send(new ListLightsQuery { IpAddress = ip, WaitForUserInput = WaitForUserInput });

                if (lights.Count() == 0)
                {
                    AnsiConsole.MarkupLine("[red][[:cross_mark: No lights found.]][/]");
                    return;
                }
                AnsiConsoleHelper.TitleRule(":light_bulb: Scans are complete. Found lights...");
                OutputLights(lights);
            }
            catch (ArgumentException ae)
            {
                AnsiConsole.MarkupLine($"[red][[:cross_mark: {ae.Message}]][/]");
            }
            catch (InvalidOperationException ex)
            {
                AnsiConsole.MarkupLine("[red][[:cross_mark: Failed to register with the bridge.]][/]");
                AnsiConsole.WriteException(ex,
                                           ExceptionFormats.ShortenPaths | ExceptionFormats.ShortenTypes |
                                           ExceptionFormats.ShortenMethods | ExceptionFormats.ShowLinks);
            }
        }
コード例 #25
0
        private static string AskFruit()
        {
            AnsiConsole.WriteLine();
            AnsiConsole.Render(new Rule("[yellow]Lists[/]").RuleStyle("grey").LeftAligned());

            var favorites = AnsiConsole.Prompt(
                new MultiSelectionPrompt <string>()
                .PageSize(10)
                .Title("What are your [green]favorite fruits[/]?")
                .AddChoices(new[]
            {
                "Apple", "Apricot", "Avocado", "Banana", "Blackcurrant", "Blueberry",
                "Cherry", "Cloudberry", "Cocunut", "Date", "Dragonfruit", "Durian",
                "Egg plant", "Elderberry", "Fig", "Grape", "Guava", "Honeyberry",
                "Jackfruit", "Jambul", "Kiwano", "Kiwifruit", "Lime", "Lylo",
                "Lychee", "Melon", "Mulberry", "Nectarine", "Orange", "Olive"
            }));

            var fruit = favorites.Count == 1 ? favorites[0] : null;

            if (string.IsNullOrWhiteSpace(fruit))
            {
                fruit = AnsiConsole.Prompt(
                    new SelectionPrompt <string>()
                    .Title("Ok, but if you could only choose [green]one[/]?")
                    .AddChoices(favorites));
            }

            AnsiConsole.MarkupLine("Your selected: [yellow]{0}[/]", fruit);
            return(fruit);
        }
コード例 #26
0
        private async Task Set(string ip, bool on, bool off, bool alert, byte?brightness, string color, uint light)
        {
            try
            {
                var command = new SetLightCommand {
                    IpAddress = ip, On = on, Off = off, Alert = alert, Brightness = brightness, Color = color, Light = light, WaitForUserInput = WaitForUserInput
                };
                await _mediator.Send(command);

                AnsiConsoleHelper.TitleRule(":light_bulb: Roamer systems dispatched. Lights have been adjusted...");

                var lights = await _mediator.Send(new ListLightsQuery { IpAddress = ip, WaitForUserInput = WaitForUserInput });

                OutputLights(lights);
            }
            catch (ArgumentException ae)
            {
                AnsiConsole.MarkupLine($"[red][[:cross_mark: {ae.Message}]][/]");
            }
            catch (InvalidOperationException ex)
            {
                AnsiConsole.MarkupLine("[red][[:cross_mark: Failed to register with the bridge.]][/]");
                AnsiConsole.WriteException(ex,
                                           ExceptionFormats.ShortenPaths | ExceptionFormats.ShortenTypes |
                                           ExceptionFormats.ShortenMethods | ExceptionFormats.ShowLinks);
            }
        }
コード例 #27
0
        public static void Enter()
        {
            do
            {
                AnsiConsole.Write("> ");
                var userInput = Console.ReadLine()
                                .Trim();

                //if the input is a command
                if (userInput.StartsWith("/"))
                {
                    command.Commands.Execute(userInput, "calc");
                    continue;
                }

                //if the input is an assignment
                if (userInput.Contains("="))
                {
                    Variables.Assign(userInput);
                    continue;
                }

                var expression = new Expression(userInput);
                if (expression.IsValid)
                {
                    var value = expression.Solve();
                    if (value is null)
                    {
                        continue;
                    }
                    AnsiConsole.MarkupLine($"[blue]{value}[/]");
                }
            } while (true);
        }
コード例 #28
0
ファイル: UtilitiesProvider.cs プロジェクト: YXGuan/guppi
        void DisplayDate(bool utc)
        {
            var now = utc ? DateTime.UtcNow : DateTime.Now;

            AnsiConsole.MarkupLine($":tear_off_calendar: [silver][[{now:yyyy-MM-dd}]][/]");
            AnsiConsole.WriteLine();
        }
コード例 #29
0
        private static async Task <(CSharpCompilation?, ZipArchive?)> GetCompilationAsync(Installation installation, string branch)
        {
            var archive = await GetSnapshotAsync(branch);

            if (archive == null)
            {
                return(null, null);
            }

            CSharpCompilation?compilation = null;

            AnsiConsole
            .Status()
            .Start("Compiling trainer", _ =>
            {
                var compiler = new Compiler(archive, installation);
                compilation  = compiler.Compile();
                var errors   = compilation
                               .GetDiagnostics()
                               .Where(d => d.Severity == DiagnosticSeverity.Error)
                               .ToList();

                if (errors.Any())
                {
                    AnsiConsole.MarkupLine($"[yellow]Compilation failed for {branch} branch.[/]");
                    compilation = null;
                }
                else
                {
                    AnsiConsole.MarkupLine($"Compilation [green]succeed[/] for [blue]{branch}[/] branch.");
                }
            });

            return(compilation, archive);
        }
コード例 #30
0
        private bool ReadActiveServices()
        {
            var useForDownload = AnsiConsole.Confirm("Do you want to use pdbMate to add downloads to your usenet client?");

            if (useForDownload)
            {
                var allowedQualities = AnsiConsole.Prompt(
                    new MultiSelectionPrompt <string>()
                    .Title("What [green]video quality[/] do you want to download?")
                    .InstructionsText(
                        "[grey](Press [blue]<space>[/] to toggle a quality, " +
                        "[green]<enter>[/] to accept)[/]")
                    .AddChoices(new[] {
                    "1080p", "2160p"
                }));

                var keepOnlyHighestQuality = AnsiConsole.Confirm("When downloading from usenet, only keep the highest quality of the same release?");
                var downloadFavoriteActors = AnsiConsole.Confirm("Add downloads based on your favorite actors?");
                var downloadFavoriteSites  = AnsiConsole.Confirm("Add downloads based on your favorite sites?");

                if (!downloadFavoriteActors && !downloadFavoriteSites)
                {
                    AnsiConsole.MarkupLine($"[red]You do not want to add downloads based on your [bold]favorite actors OR sites[/] - pdbMate would not add any downloads - let's start from the beginning.[/]");
                    ReadActiveServices();
                }

                appSettings.UsenetDownload.AllowedQualities       = allowedQualities;
                appSettings.UsenetDownload.KeepOnlyHighestQuality = keepOnlyHighestQuality;
                appSettings.UsenetDownload.DownloadFavoriteSites  = downloadFavoriteSites;
                appSettings.UsenetDownload.DownloadFavoriteActors = downloadFavoriteActors;
            }

            return(useForDownload);
        }