示例#1
0
        public static bool Exist(string name)
        {
            string accPath = Reference.RootPath + @"Accs\" + name + ".txt";
            bool   exists  = false;

            if (!Directory.Exists(Reference.RootPath + "Accs"))
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "This account doesn't exist.");
            }
            if (File.Exists(accPath))
            {
                exists = true;
            }
            else
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "This account doesn't exist.");
            }

            return(exists);
        }
示例#2
0
        public static void DrawChart(this IList <Result> results)
        {
            ColorConsole.WriteLine("\n\n", " Responses ".White().OnGreen());
            var maxIdLength       = results.Max(x => x.id.ToString().Length);
            var maxDurationLength = results.Max(x => x.duration_s_round);

            foreach (var result in results)
            {
                ColorConsole.WriteLine(VerticalChar.PadLeft(maxIdLength + 2).DarkCyan());
                ColorConsole.WriteLine(VerticalChar.PadLeft(maxIdLength + 2).DarkCyan(), result.op_Id.DarkGray(), " / ", result.result.GetColorTokenForStatusCode(), " / ", result.full_url.DarkGray());
                ColorConsole.WriteLine(result.id.ToString().PadLeft(maxIdLength).Green(), " ", VerticalChar.DarkCyan(), result.duration_ms.GetColorTokenForDuration(' '), " ", result.duration_s_str, "s".Green(), " / ", result.size_str.Color(result.size_b.GetColorForSize(result.sla_size_kb)), $" (".White(), $"sla: {result.sla_dur_s}s".DarkGray(), " / ".White(), $"{result.sla_size_kb}Kb".DarkGray(), ")".White());
            }

            var minBarLength = (10 - maxDurationLength % 10) + maxDurationLength;

            ColorConsole.WriteLine(string.Empty.PadLeft(maxIdLength + 1),
                                   BroderChar.DarkCyan(),
                                   string.Empty.PadLeft(maxDurationLength > MaxBarLength ? MaxBarLength + 2 : minBarLength, HorizontalChar).DarkCyan(),
                                   "[", $"{(maxDurationLength > MaxBarLength ? MaxBarLength : minBarLength)}".DarkCyan(), "]");
        }
示例#3
0
        private void HitPlayer(HitPlayer command)
        {
            ColorConsole.WriteLine($"{_state.PlayerName} received HitPlayer Command", ConsoleColor.Magenta);
            var @event = new PlayerHit(command.Damage);

            ColorConsole.WriteLine($"{_state.PlayerName} persisting PlayerHit event", ConsoleColor.Magenta);
            Persist(@event, playerHitEvent =>
            {
                ColorConsole.WriteLine($"{_state.PlayerName} persisted PlayerHit event ok, updating actor state", ConsoleColor.Magenta);
                _state.Health -= playerHitEvent.DamageTaken;
                _eventCount++;
                if (_eventCount == 5)
                {
                    ColorConsole.WriteLine($"{_state.PlayerName} saving snapshot", ConsoleColor.Magenta);
                    SaveSnapshot(_state);
                    ColorConsole.WriteLine($"{_state.PlayerName} resetting event count to 0", ConsoleColor.Magenta);
                    _eventCount = 0;
                }
            });
        }
示例#4
0
        protected override void Generate()
        {
            if (options.Tables.Count == 0 && String.IsNullOrEmpty(options.TablesRegex) &&
                options.ExcludedTables.Count == 0 && String.IsNullOrEmpty(options.ExcludedTablesRegex))
            {
                ColorConsole.WriteLine($"No tables were selected. Use options Tables, TableRegex, ExcludedTables or ExcludedTablesRegex to specity the tables for which Seed data will be generated ", ConsoleColor.Red);
                return;
            }

            var tables = Db.Schemas.SelectMany(s => s.Tables)
                         .Where(t => (options.Tables.Any(n => Util.TableNameMaches(t, n)) ||
                                      Util.TableNameMachesRegex(t, options.TablesRegex, true)) &&
                                !options.ExcludedTables.Any(n => Util.TableNameMaches(t, n)) &&
                                !Util.TableNameMachesRegex(t, options.ExcludedTablesRegex, false)).OrderBy(t => t.Schema.Name + "." + t.Name).ToArray();

            TopologicalSort(tables);
            GenerateSeedFile(options.OutputFileName, tables);

            ColorConsole.WriteLine($"File: '{Path.GetFileName(options.OutputFileName)}' was generated.", ConsoleColor.Yellow);
        }
示例#5
0
文件: Program.cs 项目: volnet/v-labs
        static void Main(string[] args)
        {
            ConsoleColor color = ConsoleColor.Green;
            string       url   = "http://localhost:4883/Sleep.aspx";

            ColorConsole.WriteLine("Main -> 1. SyncRPC(url);", color);
            SyncRPC(url);

            ColorConsole.WriteLine("----------------------", color);
            ColorConsole.WriteLine("Main -> 2. AsyncRPC1(url);", color);
            AsyncRPC1(url);

            ColorConsole.WriteLine("----------------------", color);
            ColorConsole.WriteLine("Main -> 3. var task = AsyncRPC2(url);", color);
            var task = AsyncRPC2(url);

            ColorConsole.WriteLine("Main -> Task.WaitAll(task);", color);
            Task.WaitAll(task);
            ColorConsole.WriteLine("Main -> end", color);
        }
示例#6
0
        public static bool Init()
        {
            Console.Clear();
            dosetup : ColorConsole.Write(ConsoleColor.Yellow, "Install Sartox OS? (y/n) ");
            string answer = Console.ReadLine();
            bool   setup;

            if (answer == "y")
            {
                setup = true;

                ColorConsole.WriteLine(ConsoleColor.Yellow, "Create your user account.");
                ColorConsole.Write(ConsoleColor.White, "User");
                ColorConsole.Write(ConsoleColor.Yellow, " => ");
                string user = Console.ReadLine();
                ColorConsole.Write(ConsoleColor.White, "Password");
                ColorConsole.Write(ConsoleColor.Yellow, " => ");
                string pass = Console.ReadLine();

                ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Creating user account...");
                Reference.UserAccount = new Acc(user, pass);
                Reference.UserAccount.Create();
                ColorConsole.WriteLine(ConsoleColor.Green, "=> Created user account.");

                ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Finishing installation...");
                File.WriteAllText(Reference.RootPath + "Installed.txt", "Sartox OS is installed... no, there is no easter egg here.", Encoding.ASCII);

                Power.Restart();
            }
            else if (answer == "n")
            {
                setup = false;
            }
            else
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "Invalid answer.");
                goto dosetup;
            }

            return(setup);
        }
示例#7
0
        public static void MaskingColorsAndBackgroundColors(
            TestConsole console, ColorToken[] input, ColorToken[] output)
        {
            "Given a console"
            .x(c => console = new TestConsole(ConsoleColor.White, ConsoleColor.Black).Using(c));

            "And the text 'Hello' in red on yellow, a space and 'world'"
            .x(() => input = new[] { "Hello".Red().OnYellow(), " ", "world" });

            "When I mask the text with blue on cyan"
            .x(() => input = input.Mask(ConsoleColor.Blue, ConsoleColor.Cyan));

            "When I write a line containing the text"
            .x(() => ColorConsole.WriteLine(input));

            "And look at the console"
            .x(() => output = console.Tokens.ToArray());

            "Then the console contains a line"
            .x(() =>
            {
                output.Length.Should().Be(
                    4, "there should be two tokens for the words, a token for the space and a token for the line ending");

                output[3].Text.Should().Be(Environment.NewLine, "the last token should be a new line");
            });

            "And the line contains 'Hello' in red on yellow, a space and 'world' in blue on cyan"
            .x(() =>
            {
                output[0].Text.Should().Be("Hello");
                output[0].Color.Should().Be(ConsoleColor.Red);
                output[0].BackgroundColor.Should().Be(ConsoleColor.Yellow);
                output[1].Text.Should().Be(" ");
                output[1].Color.Should().Be(ConsoleColor.Blue);
                output[1].BackgroundColor.Should().Be(ConsoleColor.Cyan);
                output[2].Text.Should().Be("world");
                output[2].Color.Should().Be(ConsoleColor.Blue);
                output[2].BackgroundColor.Should().Be(ConsoleColor.Cyan);
            });
        }
示例#8
0
        public async Task ExecuteAppInsights(IList <Result> results, string timeframe = "60m", int retries = 60, CancellationToken stopToken = default)
        {
            if (!string.IsNullOrWhiteSpace(settings.AppInsightsAppId) && !string.IsNullOrWhiteSpace(settings.AppInsightsApiKey))
            {
                try
                {
                    ColorConsole.Write(" App-Insights ".White().OnDarkGreen(), "[", results.Count.ToString().Green(), "]");
                    var        found  = false;
                    var        i      = 0;
                    List <Log> aiLogs = null;
                    do
                    {
                        i++;
                        aiLogs = (await this.GetLogs(results.Select(t => t.op_Id), stopToken, timeframe))?.ToList();
                        found  = aiLogs?.Count >= results.Count;
                        ColorConsole.Write((aiLogs?.Count > 0 ? $"{aiLogs?.Count.ToString()}" : string.Empty), ".".Green());
                        await Task.Delay(1000);
                    }while (!stopToken.IsCancellationRequested && found == false && i < retries);

                    if (aiLogs?.Count > 0)
                    {
                        aiLogs.ForEach(ai =>
                        {
                            var result      = results.SingleOrDefault(r => ai.operation_ParentId.Contains(r.op_Id, StringComparison.OrdinalIgnoreCase));
                            result.ai_ms    = ai.duration;
                            result.ai_op_Id = ai.operation_Id;
                            // TODO: Rest of the props
                        });
                        ColorConsole.WriteLine();
                    }
                    else
                    {
                        ColorConsole.WriteLine("\nNo logs found!".Yellow());
                    }
                }
                catch (Exception ex)
                {
                    ColorConsole.WriteLine(ex.Message.White().OnRed());
                }
            }
        }
示例#9
0
        private static void Main(string[] args)
        {
            var historyFile = "history.txt";
            var shell       = new Shell();
            var interactive = !args.Any();

            RegisterCommands(shell, interactive);

            if (interactive)
            {
                shell.WritePrompt          += ShellOnWritePrompt;
                shell.ShellCommandNotFound += ShellOnShellCommandNotFound;
                shell.PrintAlternatives    += ShellOnPrintAlternatives;

                if (File.Exists(historyFile))
                {
                    shell.History.Load(historyFile);
                }

                try
                {
                    shell.RunShell();
                }
                catch (ApplicationExitException)
                {
                }

                shell.History.Save(historyFile);
            }
            else
            {
                try
                {
                    shell.ExecuteCommand(args);
                }
                catch (ShellCommandNotFoundException)
                {
                    ColorConsole.WriteLine("Invalid arguments".Red());
                }
            }
        }
        public List <string> Map(IEnumerable <JobProfileContentItem> jobProfiles)
        {
            List <string> mappedOccupationUris = new List <string>();

            using (var reader = new StreamReader(@"SeedData\esco_job_profile_map.csv"))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    //read all the rows in the csv
                    var escoJobProfileMap         = csv.GetRecords <EscoJobProfileMap>().ToArray().OrderBy(jp => jp.Url);
                    var distinctEscoJobProfileMap = escoJobProfileMap.DistinctBy(jp => jp.Url).OrderBy(jp => jp.Url);

                    if (escoJobProfileMap.Count() != distinctEscoJobProfileMap.Count())
                    {
                        ColorConsole.WriteLine($"{escoJobProfileMap.Count() - distinctEscoJobProfileMap.Count()} duplicate job profiles in map", ConsoleColor.Black, ConsoleColor.Red);
                    }

                    foreach (var item in distinctEscoJobProfileMap)
                    {
                        JobProfileContentItem profile = jobProfiles
                                                        .SingleOrDefault(x => x.PageLocationPart.FullUrl?.Split("/").Last() == item.Url);

                        if (profile != null && !_exclusions.Contains(item.Url))
                        {
                            string title = item.EscoTitle.Split(new[] { "\r\n" }, StringSplitOptions.None).First().Trim();
                            string uri   = item.EscoUri.Split(new[] { "\r\n" }, StringSplitOptions.None).First().Trim();

                            //todo: GetContentItemIdByUri would be better - even better GetContentItemIdByUserId and take into account settings
                            profile.EponymousPart.Occupation = new ContentPicker {
                                ContentItemIds = new[]
                                {
                                    $"«c#: await Content.GetContentItemIdByDisplayText(\"Occupation\", \"{title}\")»"
                                }
                            };

                            mappedOccupationUris.Add(uri);
                        }
                    }
                }

            return(mappedOccupationUris);
        }
示例#11
0
        private static async Task IterateWorkItems(List <WorkitemRelation> relations, EFU parent, WiqlRelationList wis)
        {
            if (relations.Count > 0)
            {
                workitems = await GetWorkItems(relations.ToList());

                foreach (var wi in workitems)
                {
                    ColorConsole.WriteLine($" {wi.fields.SystemWorkItemType} ".PadLeft(22) + wi.id.ToString().PadLeft(6) + Dot + wi.fields.SystemTitle + $" [Tags: {wi.fields.SystemTags}]");
                    var efu = new EFU
                    {
                        Id           = wi.id,
                        Title        = wi.fields.SystemTitle,
                        Workitemtype = wi.fields.SystemWorkItemType,
                        Tags         = wi.fields.SystemTags?.Split(TagsDelimiters, StringSplitOptions.RemoveEmptyEntries)?.Select(x => x.Trim())?.ToList(),
                        Parent       = parent?.Id
                    };

                    var updates = (await ProcessRequest <Updates>(string.Format(CultureInfo.InvariantCulture, WorkItemUpdatesUrl, efu.Id)).ConfigureAwait(false))?.value;
                    if (updates?.Length > 0)
                    {
                        foreach (var tag in TagsToPromote)
                        {
                            var tagged   = updates?.Where(x => !(x?.fields?.SystemTags?.oldValues?.Contains(tag) == true) && (x?.fields?.SystemTags?.newValues?.Contains(tag) == true))?.OrderBy(x => x.rev)?.FirstOrDefault();
                            var untagged = efu.Tags?.Contains(tag) == true ? null : updates?.Where(x => (x?.fields?.SystemTags?.oldValues?.Contains(tag) == true) && !(x?.fields?.SystemTags?.newValues?.Contains(tag) == true))?.OrderByDescending(x => x.rev)?.FirstOrDefault(); // x => x.revisedDate.Year > DateTime.MinValue.Year && x.revisedDate.Year < DateTime.MaxValue.Year
                            if (tagged != null || untagged != null)
                            {
                                var wtag = new WorkItemTag {
                                    Id = efu.Id, Title = efu.Title, ChangedBy = $"{tagged?.revisedBy?.displayName} / {untagged?.revisedBy?.displayName}", Type = efu.Workitemtype, Tag = tag, CurrentTags = efu.Tags == null ? string.Empty : string.Join(", ", efu.Tags), Added = tagged?.fields?.SystemChangedDate?.newValue, Removed = untagged?.fields?.SystemChangedDate?.newValue
                                };
                                workItemTags.Add(wtag);
                            }
                        }
                    }

                    efus.Add(efu);
                    parent?.Children.Add(efu.Id);
                    await IterateWorkItems(wis.workItemRelations.Where(x => x.source != null && x.source.id.Equals(wi.id)).ToList(), efu, wis);
                }
            }
        }
示例#12
0
 private void Ready()
 {
     ColorConsole.WriteLine($"{PageActorName} has become Ready", ConsoleColor.Magenta);
     ReceiveAsync <UrlForUrlAndObjectParsingMessage>(async url =>
     {
         ColorConsole.WriteLine($"{PageActorName} started downloading: {url.Url}", ConsoleColor.Magenta);
         HtmlContentMessage htmlContent = await GetHtmlContent(url.Url);
         ColorConsole.WriteLine($"{PageActorName} finished downloading: {url.Url}", ConsoleColor.Magenta);
         Context.ActorSelection(ActorPaths.UrlParser).Tell(htmlContent);
         //Context.ActorSelection(ActorPaths.ObjectParser).Tell(htmlContent);
         //Context.ActorSelection(ActorPaths.UrlTracker).Tell(new ProcessedUrlMessage(htmlContent.SourceUrl));
     });
     ReceiveAsync <UrlForObjectParsingMessage>(async url =>
     {
         ColorConsole.WriteLine($"{PageActorName} started downloading: {url.Url}", ConsoleColor.Magenta);
         HtmlContentMessage htmlContent = await GetHtmlContent(url.Url);
         ColorConsole.WriteLine($"{PageActorName} finished downloading: {url.Url}", ConsoleColor.Magenta);
         Context.ActorSelection(ActorPaths.ObjectParser).Tell(htmlContent);
         Context.ActorSelection(ActorPaths.UrlTracker).Tell(new ProcessedUrlMessage(htmlContent.SourceUrl));
     });
 }
示例#13
0
        public void Display()
        {
            if (IsDisplaying)
            {
                return;
            }
            IsDisplaying      = true;
            NeedToBeRefreshed = false;
            Console.Clear();
            ColorConsole.Write("[POKE", "DEX]   ", ConsoleColor.Red, ConsoleColor.White);
            ColorConsole.WriteLine(Title, ConsoleColor.Yellow);
            ColorConsole.WriteLine("─────────────────────────────────", ConsoleColor.White);
            Console.WriteLine(" ");
            Run();
            IsDisplaying = false;

            if (NeedToBeRefreshed)
            {
                Display();
            }
        }
示例#14
0
        private async Task ListPriorities(string priorities, string[] terms, bool plain)
        {
            var query = new ListPriorityQuery {
                Priorities = priorities, Terms = terms
            };
            var result = await Mediator.Send(query);

            foreach (var task in result.Tasks)
            {
                if (plain)
                {
                    Console.WriteLine(task.ToColorString(true, Configuration).ToPlainString());
                }
                else
                {
                    ColorConsole.WriteLine(task.ToColorString(true, Configuration).ToColorTokens());
                }
            }
            Console.WriteLine("--");
            Console.WriteLine($"TODO: {result.Tasks.Count} of {result.TotalTasks} tasks shown");
        }
示例#15
0
        public override CommandResult Execute()
        {
            CommandResult result = new CommandResult(Command, Args);

            IFolder cFolder = Shell.CurrentFolder;

            IFolder[] subFolders = Shell.Client.MailboxManager.GetChildFolders(cFolder);



            ColorConsole.WriteLine("\n^15:00 {0} {1}     {2}^07:00", ("Name").PadRight(30), ("Unseen").PadRight(2), ("Exists").PadRight(5));
            ColorConsole.Write("^08:00{0}", new string('-', Console.BufferWidth));
            foreach (IFolder f in subFolders)
            {
                ColorConsole.WriteLine("^07:00{0}{1} {2}     {3}", f.SubFolders.Length > 0 ? "+":" ", f.Name.PadRight(30), f.Unseen.ToString().PadLeft(6), f.Exists.ToString().PadLeft(6));
            }

            Console.WriteLine();

            return(result);
        }
示例#16
0
        private async Task ListFile(string filename, string[] terms, bool plain)
        {
            var query = new ListTasksQuery {
                Filename = filename, Terms = terms
            };
            var result = await Mediator.Send(query);

            foreach (var task in result.Tasks)
            {
                if (plain)
                {
                    Console.WriteLine(task.ToColorString(true, Configuration).ToPlainString());
                }
                else
                {
                    ColorConsole.WriteLine(task.ToColorString(true, Configuration).ToColorTokens());
                }
            }
            Console.WriteLine("--");
            Console.WriteLine($"{filename.ToUpper()}: {result.Tasks.Count} of {result.TotalTasks} tasks shown");
        }
        public async Task Handle(Twitter.Analyzer.Events.TweetAnalyzed message, IMessageHandlerContext context)
        {
            if (!message.Tweet.Hashtags.Any())
            {
                return;
            }

            var trackHashtags = (await this.hashtags.GetAsync(message.Tweet.Track)
                                 .ConfigureAwait(false)).ToList();

            if (trackHashtags.Any(hashtag => hashtag.TweetId == message.Tweet.Id))
            {
                return;
            }

            var newHashtags = message.Tweet.Hashtags.Select(hashtag =>
                                                            new Hashtag
            {
                HashtaggedAt = message.Tweet.CreatedAt,
                TweetId      = message.Tweet.Id,
                Text         = hashtag.Text,
            })
                              .ToList();

            trackHashtags.AddRange(newHashtags);

            await this.hashtags.SaveAsync(message.Tweet.Track, trackHashtags)
            .ConfigureAwait(false);

            foreach (var hashtag in newHashtags)
            {
                ColorConsole.WriteLine(
                    $"{message.Tweet.CreatedAt.ToLocalTime()}".DarkGray(),
                    " ",
                    "Added ".Gray(),
                    $"#{hashtag.Text}".Cyan(),
                    " usage to ".Gray(),
                    $" {message.Tweet.Track} ".DarkCyan().On(ConsoleColor.White));
            }
        }
示例#18
0
        static void Main(string[] args)
        {
            logger.Info("Se cambia el aspecto de la consola");
            ChangeConsoleColor();

            logger.Info("Se crea el objeto del programa");
            var _program = new Program();

            logger.Info("Conecta al CRM");
            _program.GetConnection();

            ColorConsole.WriteLine("Deloitte Labs.".Yellow().OnBlue(), "Creación de campos.".Cyan().OnMagenta());
            Console.WriteLine("1- Crear picklist");
            Console.WriteLine("2- Get List of Plugins");
            Console.WriteLine("3- Create Plugins");
            var selec = Console.ReadLine();

            logger.Info($"Seleccion de datos { selec }");
            switch (selec)
            {
            case "1":
                Console.WriteLine("Set the entity to create the field".Yellow().OnBlue());
                var _entity = Console.ReadLine();
                _program.ReadExcel();
                _program.CreatePickLIst(_entity);
                break;

            case "2":
                Console.WriteLine("Get all plugin".Yellow().OnBlue());
                _program.GetAllPluginsList(_program._crmsvc);
                break;

            case "3":
                Console.WriteLine("Create assembly".Yellow().OnBlue());
                _program.CreateAssembly();
                break;
            }

            ColorConsole.WriteLine("FINALIZADO".Red().OnYellow());
        }
示例#19
0
        public override void Run()
        {
            if (isSearching)
            {
                ColorConsole.WriteLine($"Resulat de la recherche pour: ", input, ConsoleColor.White, ConsoleColor.Yellow);
                Console.WriteLine("");
                if (item != null)
                {
                    Console.WriteLine("     " + item);
                }
                else
                {
                    ColorConsole.WriteLine($"     {typeof(T).Name} inconnu. merci d'essayer avec un autre nom.", ConsoleColor.Red);
                }

                Console.WriteLine(" ");
                ColorConsole.WriteLine("─────────── COMMANDES ───────────", ConsoleColor.White);
                if (item != null)
                {
                    ColorConsole.WriteLine("ENTER    ", "Acceder aux details du " + typeof(T).Name, ConsoleColor.Yellow, ConsoleColor.White);
                }
                else
                {
                    ColorConsole.WriteLine("ENTER    ", "Modifier le nom a rechercher", ConsoleColor.Yellow, ConsoleColor.White);
                }
                ColorConsole.WriteLine("SPACEBAR ", "Retour au menu principal", ConsoleColor.Yellow, ConsoleColor.White);
            }
            else
            {
                ColorConsole.WriteLine($"Quel est le nom du {typeof(T).Name} a rechercher ?", ConsoleColor.White);
                Console.WriteLine("");
                ColorConsole.WriteLine($"   {input}|", ConsoleColor.Yellow);

                Console.WriteLine(" ");
                ColorConsole.WriteLine("─────────── COMMANDES ───────────", ConsoleColor.White);
                ColorConsole.WriteLine("ENTER    ", "Rechercher le pokemon", ConsoleColor.Yellow, ConsoleColor.White);
                ColorConsole.WriteLine("SPACEBAR ", "Retour au menu principal", ConsoleColor.Yellow, ConsoleColor.White);
            }
        }
示例#20
0
        private static void PrintTestResult(TestResult testResult)
        {
            const string tabulator = "       ";

            testResult.TestGroupResults.ToList().ForEach(tgr =>
            {
                ColorConsole.WriteLine(ConsoleColor.White, ConsoleColor.Black, tgr.TestGroupName + ":");
                System.Console.WriteLine("{0}{1}/{2} Tests passed", tabulator, tgr.TestCaseSuccessCount, tgr.TestCasesCount);

                tgr.Errors.ToList().ForEach(err =>
                {
                    System.Console.WriteLine();
                    ColorConsole.WriteLine(ConsoleColor.Red, ConsoleColor.White, tabulator + "Error:");
                    System.Console.WriteLine("{0}{1}", tabulator, err);
                });

                System.Console.WriteLine();
            });

            System.Console.WriteLine();
            ColorConsole.WriteLine(ConsoleColor.White, ConsoleColor.Black, "Total: " + testResult.TestCaseSuccessCount + "/" + testResult.TestCaseCount + " Tests passed");
        }
        static void Main(string[] args)
        {
            ColorConsole.Write();
            ColorConsole.WriteLine(null);
            ColorConsole.WriteLine("It's so easy to add some ", "color".Magenta(), " to your console.");
            ColorConsole.Write(null);
            ColorConsole.WriteLine();

            ColorConsole.WriteLine("You can use all these ", "colors".Color((ConsoleColor) new Random().Next(1, 14)), ".");
            foreach (var color in Enum.GetValues(typeof(ConsoleColor)).Cast <ConsoleColor>())
            {
                ColorConsole.WriteLine(color.ToString().Color(color), "  ", ("On " + color.ToString()).White().On(color));
            }

            ColorConsole.WriteLine();
            var colorToken = new ColorToken("I'm a ColorToken, change me when you want :)", ConsoleColor.White, ConsoleColor.Blue);

            ColorConsole.WriteLine(colorToken);
            ColorConsole.WriteLine(colorToken.Cyan().OnDarkYellow());
            ColorConsole.WriteLine();

            ColorConsole.WriteLine(new[] { "You can even use ", "masking".Magenta(), "." }.Mask(ConsoleColor.DarkYellow, null));
            ColorConsole.WriteLine(new[] { "You can even use ", "masking".Magenta(), "." }.Mask(ConsoleColor.DarkYellow));
            ColorConsole.WriteLine(new[] { "You can even use ", "masking".Magenta(), "." }.Mask(null, null));
            ColorConsole.WriteLine(new[] { "You can even use ", "masking".Magenta(), "." }.Mask(null, ConsoleColor.DarkYellow));
            ColorConsole.WriteLine(new[] { "You can even use ", "masking".Magenta().OnYellow(), "." }.Mask(null, ConsoleColor.DarkYellow));
            ColorConsole.WriteLine(new[] { "You can even use ", "masking".Magenta().OnYellow(), "." }.Mask(ConsoleColor.Black, ConsoleColor.DarkYellow));

            ColorToken[] noTokens = null;
            // watch as I do nothing
            ColorConsole.WriteLine(new[] { new ColorToken(), null }.Mask(null, null));
            ColorConsole.WriteLine(noTokens.Mask(ConsoleColor.Red));

            var lines = System.IO.File.ReadAllLines(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "kiwi.txt"));

            Array.ForEach(
                lines,
                line => ColorConsole.Write(line.DarkRed().OnDarkGreen(), " ".PadRight(Console.WindowWidth - line.Length).OnDarkGreen()));
        }
示例#22
0
        private static void PrintUsage()
        {
            Console.WriteLine("forever.net action exe_path [options]");
            Console.WriteLine();

            ColorConsole.WriteLine("actions:".Green());
            Console.WriteLine();
            Console.WriteLine("\tstart, stop, list");
            Console.WriteLine("\texplain, stopall, clean");
            Console.WriteLine();

            ColorConsole.WriteLine("exe path:".Green());
            Console.WriteLine();
            Console.WriteLine("\tPath to the executable. If its not valid, you will get an error");
            Console.WriteLine();

            ColorConsole.WriteLine("options:".Green());
            Console.WriteLine();
            Console.WriteLine("\t -w --working-dir            Working directory for the executable");
            Console.WriteLine("\t -s --spare-child-processes   If child processes may have been spawned, don't kill them (only for stop/stopall)");
            Console.WriteLine("\t -a --exe-args               Arguments to the executable launced in the background");
        }
示例#23
0
        protected override void Run()
        {
            ColorConsole.WriteLine(ConsoleColor.Yellow, "Login to your user account.");
            login : ColorConsole.Write(ConsoleColor.White, "User");
            ColorConsole.Write(ConsoleColor.Yellow, " => ");
            string user = Console.ReadLine();

            ColorConsole.Write(ConsoleColor.White, "Password");
            ColorConsole.Write(ConsoleColor.Yellow, " => ");
            string pass = Console.ReadLine();

            if (AccMan.Exist(user) && AccMan.GetPassword(user, true) == pass)
            {
                Reference.UserAccount = new Acc(user, pass);
                CmdMan.Init();
            }
            else
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "Incorrect credentials.");
                goto login;
            }
        }
示例#24
0
        public static void Init()
        {
            // Initializes the GUI...
            ColorConsole.WriteLine(ConsoleColor.White, "=> Loading driver...");
            Reference.Driver = new VMWareSVGAII();
            Reference.Driver.SetMode(Reference.Width, Reference.Height);
            //driver.Fill(0, 0, Width, Height, 0x6619135); // Equivalent to driver.Clear(0x6619135);

            DrawButton(Reference.Driver, 50, 110, 10, 0x255, "Restart");
            DrawButton(Reference.Driver, 50, 140, 115, 0x255, "Back to console");

            /*DrawUtils.DrawRectangle(driver, 50, 140, 30, 90, 0x255);
             * DrawUtils.DrawString(driver, string.Empty, "Back to Console (BETA)", 50, 140, 0x16777215);*/

            deltaT = RTC.Second;

            // ...and now the mouse
            ColorConsole.WriteLine(ConsoleColor.White, "=> Loading mouse...");
            Reference.Mouse = new Mouse(Reference.Width, Reference.Height);

            DrawComponents(); // Draws a simple mouse, rectangle and handles events
        }
示例#25
0
 private static void RunConsumer(Func <string, ColorToken> inColor, string workerName)
 {
     Task.Run(() =>
     {
         var queue = new MessageQueue(QUEUE_NAME)
         {
             Formatter = new XmlMessageFormatter(new[] { typeof(string) })
         };
         ColorConsole.WriteLine(inColor(string.Format("{0} - Iniciado", workerName)));
         while (true)
         {
             ColorConsole.WriteLine(inColor(string.Format("{0} - Carregando mensagens", workerName)));
             var message = queue.Receive();
             if (message != null)
             {
                 ColorConsole.WriteLine(inColor(string.Format("{0} - Received: {1}", workerName, message.Body)));
             }
             ColorConsole.WriteLine(inColor(string.Format("{0} - Tudo recebido", workerName)));
             Thread.Sleep(800);
         }
     });
 }
示例#26
0
        public static string GetPassword(string name)
        {
            string accPath  = Reference.RootPath + @"Accs\" + name + ".txt";
            string password = string.Empty;

            if (!Directory.Exists(Reference.RootPath + "Accs"))
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "This account doesn't exist.");
            }
            if (File.Exists(accPath))
            {
                ColorConsole.WriteLine(ConsoleColor.White, "Getting password...");
                password = File.ReadAllText(accPath).Split(":")[1];
                ColorConsole.WriteLine(ConsoleColor.Green, "Got password.");
            }
            else
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "This account doesn't exist.");
            }

            return(password);
        }
示例#27
0
        public static void Init()
        {
            ColorConsole.WriteLine(ConsoleColor.Yellow, "Login to your user account.");
            login : ColorConsole.Write(ConsoleColor.White, "User");
            ColorConsole.Write(ConsoleColor.Yellow, " => ");
            string user = Console.ReadLine();

            ColorConsole.Write(ConsoleColor.White, "Password");
            ColorConsole.Write(ConsoleColor.Yellow, " => ");
            string pass = Console.ReadLine();

            if (AccMan.Exist(user) && Encoding.ASCII.GetString(Convert.FromBase64String(AccMan.GetPassword(user))) == pass)
            {
                Reference.UserAccount = new Acc(user, pass);
                CmdMan.Init();
            }
            else
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "Incorrect credentials.");
                goto login;
            }
        }
示例#28
0
        public override IMAPShell.Shell.CommandResult Execute()
        {
            CommandResult result = new CommandResult(Command, Args);

            bool errorsOnly = (Args.Length > 0 && Args[0].Equals("errors"));

            foreach (string logLine in Shell.Client.Aggregator.LogEntries)
            {
                bool   thisLineIsError = false;
                string colorCode       = "^07:00";
                if (logLine.Contains("WARN"))
                {
                    colorCode = "^14:00";
                }

                if (logLine.Contains("ERROR"))
                {
                    colorCode       = "^12:00";
                    thisLineIsError = true;
                }

                if (logLine.Contains("INFO"))
                {
                    colorCode = "^11:00";
                }

                if (errorsOnly && thisLineIsError)
                {
                    ColorConsole.WriteLine("{0}{1}", colorCode, logLine);
                }
                else if (!errorsOnly)
                {
                    ColorConsole.WriteLine("{0}{1}", colorCode, logLine);
                }
            }

            return(result);
        }
示例#29
0
        protected override void BeforeRun()
        {
            ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Registering Extended ASCII encoding...");
            Encoding.RegisterProvider(CosmosEncodingProvider.Instance);
            Console.InputEncoding  = Encoding.GetEncoding(437);
            Console.OutputEncoding = Encoding.GetEncoding(437);

            ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Loading virtual FS...");
            VFSManager.RegisterVFS(Reference.FAT);
            if (Reference.FAT.GetVolumes().Count > 0)
            {
                ColorConsole.WriteLine(ConsoleColor.Green, "Sucessfully loaded the virtual FS!");
            }
            else
            {
                ColorConsole.WriteLine(ConsoleColor.Red, "Uh-oh, couldn't load the virtual FS...");
            }

            ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Initializing SSE...");
            Global.CPU.InitSSE();
            ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Initializing Float...");
            Global.CPU.InitFloat();

            ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Creating live account...");
            Acc acc = new Acc("Sartox", "123");

            acc.Create();

            Reference.Installed = File.Exists(Reference.RootPath + "Installed.txt");
            if (!Reference.Installed)
            {
                ColorConsole.WriteLine(ConsoleColor.Yellow, "=> Loading setup...");
                Setup.Init();
            }

            Console.Clear();
            ColorConsole.WriteLine(ConsoleColor.Green, "Welcome to Sartox OS v" + Reference.Version + "!");
        }
示例#30
0
        public Task Run(CancellationToken cancellationToken)
        {
            listener = new OutboundListener(8084);

            listener.Connections.Subscribe(
                async connection =>
            {
                await connection.Connect();
                Console.WriteLine("New Socket connected");

                connection.ChannelEvents.Where(x => x.UUID == connection.ChannelData.UUID && x.EventName == EventName.ChannelHangup)
                .Take(1)
                .Subscribe(
                    e =>
                {
                    ColorConsole.WriteLine(
                        "Hangup Detected on A-Leg ".Red(),
                        e.Headers[HeaderNames.CallerUniqueId],
                        " ",
                        e.Headers[HeaderNames.HangupCause]);

                    connection.Exit();
                });

                var uuid = connection.ChannelData.Headers[HeaderNames.UniqueId];
                await connection.SubscribeEvents(EventName.Dtmf, EventName.ChannelHangup);
                await connection.Linger();
                await connection.ExecuteApplication(uuid, "answer", null, true, false);
                await connection.Play(uuid, "$${base_dir}/sounds/en/us/callie/misc/8000/misc-freeswitch_is_state_of_the_art.wav");
            });

            listener.Start();

            Console.WriteLine("Listener started on 8084. Press [Enter] to exit");
            Console.ReadLine();

            return(Task.FromResult(0));
        }