Exemplo n.º 1
0
        private static void PrintFrames(ConsoleOperations ops, IConsole console)
        {
            var        text1Colors          = new ConsoleFontColor(Color.Gold, Color.Black);
            var        text2Colors          = new ConsoleFontColor(Color.Brown, Color.Black);
            var        text3Colors          = new ConsoleFontColor(Color.Black, Color.Silver);
            var        frame2Colors         = new ConsoleFontColor(Color.Silver, Color.Black);
            var        solidFrameTextColors = new ConsoleFontColor(Color.Red, Color.Yellow);
            var        solidFrameColors     = new ConsoleFontColor(Color.Yellow, Color.Black);
            FrameStyle block3Frame          = new FrameStyle(frame2Colors, text3Colors, @"┌─┐││└─┘", '░');
            FrameStyle doubleFrame          = new FrameStyle(frame2Colors, text3Colors, @"╔═╗║║╚═╝", '▒');
            FrameStyle solidFrame           = new FrameStyle(solidFrameColors, solidFrameTextColors, @"▄▄▄██▀▀▀", '▓');

            ops.WriteTextBox(5, 5, 50, 7,
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, laoreet enim. Phasellus fermentum in, dolor.",
                             text1Colors);
            ops.WriteTextBox(25, 15, 80, 37,
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, laoreet enim. Phasellus fermentum in, dolor. Pellentesque facilisis. Nulla imperdiet sit amet magna. Vestibulum dapibus, mauris nec malesuada fames ac turpis velit, rhoncus eu, luctus et interdum adipiscing wisi. Aliquam erat ac ipsum. Integer aliquam purus. Quisque lorem tortor fringilla sed, vestibulum id, eleifend justo vel bibendum sapien massa ac turpis faucibus orci luctus non, consectetuer lobortis quis, varius in, purus.",
                             text2Colors);

            ops.WriteTextBox(new Rectangle(26, 26, 60, 20),
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, laoreet enim. Phasellus fermentum in, dolor. Pellentesque facilisis. Nulla imperdiet sit amet magna. Vestibulum dapibus, mauris nec malesuada fames ac turpis velit, rhoncus eu, luctus et interdum adipiscing wisi. Aliquam erat ac ipsum. Integer aliquam purus. Quisque lorem tortor fringilla sed, vestibulum id, eleifend justo vel bibendum sapien massa ac turpis faucibus orci luctus non, consectetuer lobortis quis, varius in, purus.",
                             block3Frame);
            ops.WriteTextBox(new Rectangle(80, 10, 30, 7),
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.",
                             doubleFrame);
            ops.WriteTextBox(new Rectangle(100, 20, 25, 7),
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.",
                             solidFrame);

            console.WriteText(0, 20, "", Color.Gray, Color.Black); // reset

            Console.ReadLine();
            console.Clear();
        }
 public FrameDefinition(ConsoleFontColor frameColor, ConsoleFontColor textColor, string frameChars, char backgroundFiller)
 {
     this.FrameColor       = frameColor;
     this.TextColor        = textColor;
     this.BackgroundFiller = backgroundFiller;
     this._frameChars      = frameChars.ToCharArray();
 }
Exemplo n.º 3
0
        private static void PrintTables(ConsoleOperations ops)
        {
            var tableFrameColor   = new ConsoleFontColor(Color.Silver, Color.Black);
            var tableHeaderColor  = new ConsoleFontColor(Color.White, Color.Black);
            var tableOddRowColor  = new ConsoleFontColor(Color.Black, Color.Silver);
            var tableEvenRowColor = new ConsoleFontColor(Color.Black, Color.DimGray);

            TableStyle tableStyle = new TableStyle(
                tableFrameColor,
                tableHeaderColor,
                tableOddRowColor,
                tableEvenRowColor,
                @"|-||||-||-|--", // simple, ascii table
                ' ',
                TableLargeRowContentBehavior.Ellipsis);

            var headers = new[] { "Row 1", "Longer row 2", "Third row" };
            var values  = new[]
            {
                new[] { "1", "2", "3" },
                new[] { "10", "223423", "3" },
                new[] { "1", "2", "3" },
                new[] { "12332 ", "22332423", "3223434234" },
                new[] { "1df ds fsd fsfs fsdf s", "2234  4234 23", "3 23423423" },
            };

            ops.WriteTabelaricData(5, 5, 50, headers, values, tableStyle);

            Console.ReadLine();
        }
Exemplo n.º 4
0
        /// <summary>
        /// The write text.
        /// </summary>
        /// <param name="style">
        /// The style.
        /// </param>
        /// <param name="text">
        /// The text.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        public void WriteText(ConsoleFontColor style, string text)
        {
            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }
            if (text.ToCharArray().Any(ch => (int)ch < 32))
            {
                throw new ArgumentException("Messages that contain special characters are forbidden.", paramName: nameof(text));
            }

            lock (this.consoleInstance.AtomicHandle)
            {
                var backupPosition = this.consoleInstance.GetCursorPosition();

                int remainingArea = this.windowWidth - this.currentPosition;
                if (remainingArea > text.Length)
                {
                    this.consoleInstance.SetCursorPosition(this.currentPosition, this.lineY);
                    this.consoleInstance.WriteText(style, text);
                    this.currentPosition += text.Length;
                }
                else
                {
                    if (remainingArea > 0)
                    {
                        this.consoleInstance.SetCursorPosition(this.currentPosition, this.lineY);
                        this.consoleInstance.WriteText(style, text.Substring(0, remainingArea));
                        this.currentPosition += remainingArea;
                    }
                }

                this.consoleInstance.SetCursorPosition(backupPosition.X, backupPosition.Y);
            }
        }
Exemplo n.º 5
0
        public void WriteLine(string message,ConsoleFontColor fontColor = null)
        {
            if (this.ConsoleInfo == null || string.IsNullOrEmpty(message)) return;
            if (string.IsNullOrEmpty(this.ConsoleInfo.HashKey) || string.IsNullOrEmpty(this.ConsoleInfo.SetKey)) return;
            message = "【JobAgent】" + message;
            lock (this)
            {
                string value;

                ConsoleLine line = new ConsoleLine
                {
                    Message = message
                };

                if (fontColor != null)
                {
                    line.TextColor = fontColor.ToString();
                }

                line.TimeOffset = Math.Round((DateTime.UtcNow - ConsoleInfo.StartTime).TotalSeconds, 3);
                if (_lastTimeOffset >= line.TimeOffset)
                {
                    // prevent duplicate lines collapsing
                    line.TimeOffset = _lastTimeOffset + 0.0001;
                }

                _lastTimeOffset = line.TimeOffset;

                if (line.Message.Length > ValueFieldLimit - 36)
                {
                    // pretty sure it won't fit
                    // (36 is an upper bound for JSON formatting, TimeOffset and TextColor)
                    value = null;
                }
                else
                {
                    // try to encode and see if it fits
                    value = JsonConvert.SerializeObject(line);

                    if (value.Length > ValueFieldLimit)
                    {
                        value = null;
                    }
                }

                if (value == null)
                {
                    var referenceKey = Guid.NewGuid().ToString("N");

                    Storage.SetRangeInHash(ConsoleInfo.HashKey, new[] { new KeyValuePair<string, string>(referenceKey, line.Message) });

                    line.Message = referenceKey;
                    line.IsReference = true;

                    value = JsonConvert.SerializeObject(line);
                }

                Storage.AddToSet(ConsoleInfo.SetKey, value, line.TimeOffset);
            }
        }
Exemplo n.º 6
0
 /// <inheritdoc />
 public void WriteLine(ConsoleFontColor colors, string text) // TODO: add flag to keep BG color to next line
 {
     this.SetColors(colors.ForeColor, colors.BgColor);
     Console.Write(text);
     Console.ResetColor();
     // this.SetColors(colors.ForeColor, Color.Black); // try resetting BG color...
     Console.WriteLine();
 }
Exemplo n.º 7
0
        public FrameStyle(ConsoleFontColor frameColor, ConsoleFontColor textColor, string frameChars, char backgroundFiller)
        {
            this.FrameColor       = frameColor;
            this.TextColor        = textColor;
            this.BackgroundFiller = backgroundFiller;
            this._frameChars      = frameChars.ToCharArray();

            // TODO: Performance-wise - read all these chars only once, in the ctor. Can be refactored at any time - does not alter interface.
        }
Exemplo n.º 8
0
 public SimpleTableStyle(
     ConsoleFontColor tableHeaderColor,
     ConsoleFontColor tableRowColor,
     TableOverflowContentBehavior overflowBehavior = TableOverflowContentBehavior.Ellipsis)
 {
     this.HeaderColor       = tableHeaderColor;
     this.RowColor          = tableRowColor;
     this.OverflowBehaviour = overflowBehavior;
 }
Exemplo n.º 9
0
        public VirtualEntryLine(IConsole console, IClipboard clipboard, ConsoleFontColor cmdColor)
        {
            console.Requires(nameof(console)).IsNotNull();
            clipboard.Requires(nameof(clipboard)).IsNotNull();

            this._console   = console;
            this._clipboard = clipboard;
            this._cmdColor  = cmdColor;
        }
Exemplo n.º 10
0
        public IProgressBar WriteProgressBar(string name, double value=1, ConsoleFontColor color = null)
        {
            var progressBarId = Interlocked.Increment(ref _nextProgressBarId);

            var progressBar = new RedisProgressBar(this, progressBarId.ToString(CultureInfo.InvariantCulture), name, color);
            // set initial value
            progressBar.SetValue(value);

            return progressBar;
        }
Exemplo n.º 11
0
 /// <inheritdoc />
 public void SetColors(ConsoleFontColor style)
 {
     if (this.VirtualConsoleEnabled)
     {
         Console.Write($"\x1b[38;2;{style.ForeColor.R};{style.ForeColor.G};{style.ForeColor.B};48;2;{style.BgColor.R};{style.BgColor.G};{style.BgColor.B}m");
     }
     else
     {
         this.SetColors(style.ForeColor, style.BgColor);
     }
 }
Exemplo n.º 12
0
 public TableStyle(ConsoleFontColor frameColor, ConsoleFontColor headerColor, ConsoleFontColor rowColor, ConsoleFontColor evenRowColor,
                   string frameChars, char backgroundFiller, TableOverflowContentBehavior overflowBehaviour)
 {
     this.FrameColor        = frameColor;
     this.HeaderColor       = headerColor;
     this.RowColor          = rowColor;
     this.EvenRowColor      = evenRowColor;
     this.BackgroundFiller  = backgroundFiller;
     this.OverflowBehaviour = overflowBehaviour;
     this._frameChars       = frameChars.ToCharArray();
 }
Exemplo n.º 13
0
 /// <inheritdoc />
 public void WriteText(ConsoleFontColor colors, string text)
 {
     if (this.VirtualConsoleEnabled)
     {
         Console.Write($"\x1b[38;2;{colors.ForeColor.R};{colors.ForeColor.G};{colors.ForeColor.B};48;2;{colors.BgColor.R};{colors.BgColor.G};{colors.BgColor.B}m{text}");
     }
     else
     {
         this.SetColors(colors.ForeColor, colors.BgColor);
         Console.Write(text);
     }
 }
Exemplo n.º 14
0
        /// <inheritdoc />
        public void WriteLine(ConsoleFontColor colors, string text) // TODO: add flag to keep BG color to next line
        {
            if (this.VirtualConsoleEnabled)
            {
                Console.Write($"\x1b[38;2;{colors.ForeColor.R};{colors.ForeColor.G};{colors.ForeColor.B};48;2;{colors.BgColor.R};{colors.BgColor.G};{colors.BgColor.B}m{text}");
            }
            else
            {
                this.SetColors(colors.ForeColor, colors.BgColor);
                Console.Write(text);
                // this.SetColors(colors.ForeColor, Color.Black); // try resetting BG color...
            }

            Console.ResetColor();
            Console.WriteLine();
        }
Exemplo n.º 15
0
        // TODO: write simulation console to automatically test complex printing functions results (content only, no color abstracting)

        private static void SimulateConsole(IConsole console)
        {
            console.WriteLine("Starting command line simulator (entry line only, no real commands). Type 'exit' `command` to stop it.");

            var promptConsoleColor = new ConsoleFontColor(Color.LightSkyBlue, Color.Black);
            var cmdColor           = new ConsoleFontColor(Color.LightGray, Color.Black);
            var retypeColor        = new ConsoleFontColor(Color.Lime, Color.Black);

            VirtualEntryLine cmdSimulator = new VirtualEntryLine(console, new FakeClipBoard(), cmdColor);

            var    fakeAutocompleter = new TestAutoCompleter("abcd", "aabbdd", "nbbdbd", "sdsdsds", "sddsdssfdf", "abc");
            string cmd = "";

            while (!string.Equals(cmd, "EXIT", StringComparison.OrdinalIgnoreCase))
            {
                console.WriteText(promptConsoleColor, "c:\\");
                cmd = cmdSimulator.GetUserEntry(fakeAutocompleter);
                console.WriteLine();
                console.WriteLine(retypeColor, cmd);
                console.WriteLine();
            }
        }
Exemplo n.º 16
0
        public void Run(IConsole console)
        {
            console.WriteLine("Starting command line simulator (entry line only, no real commands). Type 'exit' `command` to stop it.");
            console.WriteLine("There are also some fake auto-completion suggestions starting with 'a*' and 's'. Use (Shit)+Tab to test them.");

            var promptConsoleColor = new ConsoleFontColor(Color.LightSkyBlue, Color.Black);
            var cmdColor           = new ConsoleFontColor(Color.LightGray, Color.Black);
            var retypeColor        = new ConsoleFontColor(Color.Lime, Color.Black);

            VirtualEntryLine cmdSimulator = new VirtualEntryLine(console, new FakeClipBoard(), cmdColor);

            var fakeAutocompleter = new TestingAutoCompleter("abcd", "aabbdd", "asddhhhs", "nbbdbd", "sdsdsds", "sddsdssfdf", "abc", "sdessse");
            // TODO: replace with dynamic auto-completer that does not ignore letter already enetered
            string cmd = "";

            while (!string.Equals(cmd, "EXIT", StringComparison.OrdinalIgnoreCase))
            {
                console.WriteText(promptConsoleColor, "c:\\");
                cmd = cmdSimulator.GetUserEntry(fakeAutocompleter);
                console.WriteLine();
                console.WriteLine(retypeColor, cmd);
                console.WriteLine();
            }
        }
Exemplo n.º 17
0
        private static void Main(string[] args)
        {
            ConsoleColorsHelper helper = new ConsoleColorsHelper();

            //helper.ReplaceConsoleColor(ConsoleColor.DarkCyan, Color.Salmon);
            helper.ReplaceConsoleColors(
                new Tuple <ConsoleColor, Color>(ConsoleColor.DarkCyan, Color.Chocolate),
                new Tuple <ConsoleColor, Color>(ConsoleColor.Blue, Color.DodgerBlue),
                new Tuple <ConsoleColor, Color>(ConsoleColor.Yellow, Color.Gold),
                new Tuple <ConsoleColor, Color>(ConsoleColor.DarkBlue, Color.MidnightBlue)
                );

            IConsole          console = new SystemConsole(helper);
            ConsoleOperations ops     = new ConsoleOperations(console);

            console.WriteText(0, 0, "test message", Color.Red, Color.Black);
            console.WriteText(0, 1, "test message 2", Color.Cyan, Color.YellowGreen);
            console.WriteText(0, 2, "test message 3d ds sfsdfsad ", Color.Orange, Color.Plum);
            console.WriteText(0, 3, "test messaf sdf s sfsdfsad ", Color.DarkOliveGreen, Color.Silver);
            console.WriteText(0, 4, "tsd fsfsd fds fsd f fa fas fad ", Color.AliceBlue, Color.PaleVioletRed);
            console.WriteText(0, 5, "tsd fsfsd fds fsd f fa fas fad ", Color.Blue, Color.CadetBlue);
            console.WriteText(0, 6, "tsd fsdfsdfsd fds fa fas fad ", Color.Maroon, Color.ForestGreen);

            // lol: http://stackoverflow.com/questions/3811973/why-is-darkgray-lighter-than-gray
            console.WriteText(0, 10, "test message", Color.Gray, Color.Black);
            console.WriteText(0, 11, "test message 2", Color.DarkGray, Color.Black);
            console.WriteText(0, 12, "test message 3d ds sfsdfsad ", Color.DimGray, Color.Black);
            console.WriteText(0, 20, "", Color.Gray, Color.Black); // reset

            var props = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public).Where(p => p.PropertyType == typeof(Color));

            foreach (var propertyInfo in props)
            {
                Color        c  = (Color)propertyInfo.GetValue(null);
                ConsoleColor cc = helper.FindClosestColor(c);
                Console.ForegroundColor = cc;
                Console.WriteLine("{0,-25} {1,-18} #{2,-8}", propertyInfo.Name, Enum.GetName(typeof(ConsoleColor), cc), c.ToArgb().ToString("X"));
            }

            var             text1Colors          = new ConsoleFontColor(Color.Gold, Color.Black);
            var             text2Colors          = new ConsoleFontColor(Color.Brown, Color.Black);
            var             text3Colors          = new ConsoleFontColor(Color.Black, Color.Silver);
            var             frame2Colors         = new ConsoleFontColor(Color.Silver, Color.Black);
            var             solidFrameTextColors = new ConsoleFontColor(Color.Red, Color.Yellow);
            var             solidFrameColors     = new ConsoleFontColor(Color.Yellow, Color.Black);
            FrameDefinition block3Frame          = new FrameDefinition(frame2Colors, text3Colors, @"┌─┐││└─┘", '░');
            FrameDefinition doubleFrame          = new FrameDefinition(frame2Colors, text3Colors, @"╔═╗║║╚═╝", '▒');
            FrameDefinition solidFrame           = new FrameDefinition(solidFrameColors, solidFrameTextColors, @"▄▄▄██▀▀▀", '▓');

            //console.Clear();
            ops.WriteTextBox(5, 5, 50, 7, @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, laoreet enim. Phasellus fermentum in, dolor.", text1Colors);
            ops.WriteTextBox(25, 15, 80, 37, @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, laoreet enim. Phasellus fermentum in, dolor. Pellentesque facilisis. Nulla imperdiet sit amet magna. Vestibulum dapibus, mauris nec malesuada fames ac turpis velit, rhoncus eu, luctus et interdum adipiscing wisi. Aliquam erat ac ipsum. Integer aliquam purus. Quisque lorem tortor fringilla sed, vestibulum id, eleifend justo vel bibendum sapien massa ac turpis faucibus orci luctus non, consectetuer lobortis quis, varius in, purus.", text2Colors);

            ops.WriteTextBox(new Rectangle(26, 26, 60, 20),
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, laoreet enim. Phasellus fermentum in, dolor. Pellentesque facilisis. Nulla imperdiet sit amet magna. Vestibulum dapibus, mauris nec malesuada fames ac turpis velit, rhoncus eu, luctus et interdum adipiscing wisi. Aliquam erat ac ipsum. Integer aliquam purus. Quisque lorem tortor fringilla sed, vestibulum id, eleifend justo vel bibendum sapien massa ac turpis faucibus orci luctus non, consectetuer lobortis quis, varius in, purus.",
                             block3Frame);
            ops.WriteTextBox(new Rectangle(80, 10, 30, 7),
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.",
                             doubleFrame);
            ops.WriteTextBox(new Rectangle(100, 20, 25, 7),
                             @"Lorem ipsum dolor sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.",
                             solidFrame);

            console.WriteText(0, 20, "", Color.Gray, Color.Black); // reset


            Console.ReadLine();
        }
Exemplo n.º 18
0
 public void SetColors(ConsoleFontColor style)
 {
 }
Exemplo n.º 19
0
 public void WriteLine(ConsoleFontColor colors, string text)
 {
     Console.WriteLine(text);
 }
Exemplo n.º 20
0
 /// <inheritdoc />
 public void SetColors(ConsoleFontColor style)
 {
     this.SetColors(style.ForeColor, style.BgColor);
 }
Exemplo n.º 21
0
 /// <inheritdoc />
 public void WriteText(ConsoleFontColor colors, string text)
 {
     this.SetColors(colors.ForeColor, colors.BgColor);
     Console.Write(text);
 }
 /// <summary>
 /// Returns an <see cref="IEnumerable{T}"/> reporting enumeration progress.
 /// </summary>
 /// <typeparam name="T">Item type</typeparam>
 /// <param name="enumerable">Source enumerable</param>
 /// <param name="context">Perform context</param>
 /// <param name="name">Progress bar name</param>
 /// <param name="color">Progress bar color</param>
 /// <param name="count">Item count</param>
 public static IEnumerable <T> WithProgress <T>(this IEnumerable <T> enumerable, IHangfireConsole context, string name, ConsoleFontColor color = null, int count = -1)
 {
     return(WithProgress(enumerable, context.WriteProgressBar(name, 0, color), count));
 }
Exemplo n.º 23
0
        /// <inheritdoc />
        public void Run(IConsole console)
        {
            console.Clear();
            var exitGuid = new Guid(@"a7725515-7f82-4c18-9c36-343003bdf20d");

            var menuItems = new ConsoleMenuItem[]
            {
                new ConsoleMenuItem
                {
                    Enabled = true,
                    Caption = "menu item number one",
                    Code    = Guid.NewGuid()
                },
                new ConsoleMenuItem
                {
                    Enabled = true,
                    Caption = "menu item number two",
                    Code    = Guid.NewGuid()
                },
                new ConsoleMenuItem
                {
                    Enabled = false,
                    Caption = "menu item number three",
                    Code    = Guid.NewGuid()
                },
                new ConsoleMenuItem
                {
                    Enabled = true,
                    Caption = "menu item number four with very long description",
                    Code    = Guid.NewGuid()
                },
                new ConsoleMenuItem
                {
                    Enabled = false,
                    Caption = "menu item number five",
                    Code    = Guid.NewGuid()
                },
                new ConsoleMenuItem
                {
                    Enabled = true,
                    Caption = "menu item number six",
                    Code    = Guid.NewGuid()
                },
                new ConsoleMenuItem
                {
                    Enabled = true,
                    Caption = "Exit menu DEMO",
                    Code    = exitGuid
                }
            };

            var menuStyling = new MenuStyles
            {
                ActiveItem   = new ConsoleFontColor(Color.Red, Color.Black),
                DisabledItem = new ConsoleFontColor(Color.Gray, Color.Black),
                NormalItem   = new ConsoleFontColor(Color.WhiteSmoke, Color.Black),
                SelectedItem = new ConsoleFontColor(Color.Black, Color.LightGray),
                Alignment    = TextAlign.Center
            };

            var aConsole = new AtomicConsole(console);

            int menuStartY       = 6;
            int menuStartX       = 5;
            int menuContentWidth = 25;

            var frameColors    = new ConsoleFontColor(Color.Yellow, Color.Black);
            var boxInnerColors = new ConsoleFontColor(Color.WhiteSmoke, Color.Black);
            var frameStyle     = new FrameStyle(frameColors, boxInnerColors, @"┌─┐││└─┘", ' ');

            var ops = new ConsoleOperations(aConsole);

            ops.WriteTextBox(new Rectangle(menuStartX - 1, menuStartY - 1, menuContentWidth + 2, menuItems.Length + 2), "", frameStyle);

            var menu = new ConsoleMenu(aConsole, new Rectangle(menuStartX, menuStartY, menuContentWidth, 0), menuItems, menuStyling);

            menu.RenderAll();

            ConsoleMenuItem result = null;

            while (result == null || result.Code != exitGuid)
            {
                result = menu.Focus(resetActiveItem: true);

                aConsole.CleanLineSync(0, Color.Black);
                aConsole.RunAtomicOperations(ac =>
                {
                    aConsole.SetCursorPosition(0, 0);
                    aConsole.PrintColorfullText(
                        new KeyValuePair <ConsoleFontColor, string>(new ConsoleFontColor(Color.BlanchedAlmond, Color.Black), @"Selected menu: "),
                        new KeyValuePair <ConsoleFontColor, string>(new ConsoleFontColor(Color.Gold, Color.Black), result?.Caption ?? "#NULL#")
                        );
                });
                Thread.Sleep(1000);
            }

            aConsole.SetCursorPosition(0, menuStartY + menuItems.Length + 1);
            aConsole.ShowCursor();

            aConsole.WaitForNextPage();
        }
        internal MysqlProgressBar(MysqlConsole context, string progressBarId, string name, ConsoleFontColor color = null)
        {
            if (string.IsNullOrEmpty(progressBarId))
            {
                throw new ArgumentNullException(nameof(progressBarId));
            }

            _context       = context ?? throw new ArgumentNullException(nameof(context));
            _progressBarId = progressBarId;
            _name          = name;
            _color         = color;
            _value         = -1;
        }
 /// <summary>
 /// Returns ab <see cref="IEnumerable"/> reporting enumeration progress.
 /// </summary>
 /// <param name="enumerable">Source enumerable</param>
 /// <param name="context">Perform context</param>
 /// <param name="color">Progress bar color</param>
 /// <param name="count">Item count</param>
 public static IEnumerable WithProgress(this IEnumerable enumerable, IHangfireConsole context, ConsoleFontColor color = null, int count = -1)
 {
     return(WithProgress(enumerable, context.WriteProgressBar("ProgressBar", 0, color), count));
 }
Exemplo n.º 26
0
        public void Run(IConsole console)
        {
            var tableFrameColor   = new ConsoleFontColor(Color.Silver, Color.Black);
            var tableHeaderColor  = new ConsoleFontColor(Color.White, Color.Black);
            var tableOddRowColor  = new ConsoleFontColor(Color.Silver, Color.Black);
            var tableEvenRowColor = new ConsoleFontColor(Color.DimGray, Color.Black);

            TableStyle tableStyle = new TableStyle(
                tableFrameColor,
                tableHeaderColor,
                tableOddRowColor,
                tableEvenRowColor,
                @"|-||||-||-|--", // simple, ascii table
                ' ',
                TableOverflowContentBehavior.Ellipsis);

            TableStyle wrappingTableStyle = new TableStyle(
                tableFrameColor,
                tableHeaderColor,
                tableOddRowColor,
                tableEvenRowColor,
                @"|-||||-||-|--", // simple, ascii table
                ' ',
                TableOverflowContentBehavior.Wrap);

            var headers = new[] { "Row 1", "Longer row 2", "Third row" };
            var values  = new[]
            {
                new[] { "1", "2", "3" },
                new[] { "10", "223423", "3" },
                new[] { "1", "2", "3" },
                new[] { "12332 ", "22332423", "3223434234" },
                new[] { "1df ds fsd fsfs fsdf s", "2234  4234 23", "3 23423423" },
            };

            var simpleTableStyleWithWrap = new SimpleTableStyle(
                tableHeaderColor,
                tableEvenRowColor,
                TableOverflowContentBehavior.Wrap)
            {
                EvenRowColor = tableOddRowColor
            };

            var simpleTableStyleWithEllipsis = new SimpleTableStyle(tableHeaderColor, tableEvenRowColor)
            {
                EvenRowColor = tableOddRowColor
            };

            // ops.WriteTabelaricData(5, 5, 50, headers, values, tableStyle);


            console.WriteLine(tableFrameColor, "Small tables");

            DataTable <string> dt = new DataTable <string>(
                new ColumnInfo("Column a", ColumnAlignment.Left),
                new ColumnInfo("Column B", ColumnAlignment.Left),
                new ColumnInfo("Column V1", ColumnAlignment.Right),
                new ColumnInfo("Column V2", ColumnAlignment.Right));

            for (int i = 0; i < 20; i++)
            {
                dt.AddRow(
                    i.ToString(),
                    new[]
                {
                    TestTools.AlphanumericIdentifier.BuildRandomStringFrom(5, 10).Trim(),
                    TestTools.AlphaSentence.BuildRandomStringFrom(4, 15).Trim(),
                    TestTools.GetRandomFloat(10000).ToString("N2", CultureInfo.CurrentCulture),
                    TestTools.GetRandomFloat(30000).ToString("N2", CultureInfo.CurrentCulture)
                });
            }

            SimpleTablePrinter       simpleTablePrinter      = new SimpleTablePrinter(console, simpleTableStyleWithEllipsis);
            SimpleTablePrinter       simpleTableWithWrapping = new SimpleTablePrinter(console, simpleTableStyleWithWrap);
            FramedTablePrinter       framedPrinter           = new FramedTablePrinter(console, tableStyle);
            SpeflowStyleTablePrinter specflowPrinter         = new SpeflowStyleTablePrinter(console, tableStyle);
            var specflowTableWithWrapping = new SpeflowStyleTablePrinter(console, wrappingTableStyle);

            simpleTablePrinter.PrintTable(dt);
            console.WriteLine();

            simpleTableWithWrapping.PrintTable(dt);
            console.WriteLine();

            framedPrinter.PrintTable(dt);
            console.WriteLine();

            specflowPrinter.PrintTable(dt);
            console.WriteLine();

            specflowTableWithWrapping.PrintTable(dt);
            console.WriteLine();

            console.WaitForNextPage();

            console.Clear();
            console.WriteLine(tableFrameColor, "Positioned tables");
            console.WriteLine();

            // TODO: PrintTableAt(dt, x, y);

            console.WaitForNextPage();

            console.WriteLine(tableFrameColor, "Large tables");
            console.WriteLine();

            dt = new DataTable <string>(
                new ColumnInfo("Column A1", ColumnAlignment.Left),
                new ColumnInfo("Column B", ColumnAlignment.Left),
                new ColumnInfo("Column C", ColumnAlignment.Left),
                new ColumnInfo("Column V1", ColumnAlignment.Right, fixedLength: 9),
                new ColumnInfo("Column V2", ColumnAlignment.Right, fixedLength: 9),
                new ColumnInfo("Column VXX", ColumnAlignment.Right, fixedLength: 12));

            for (int i = 0; i < 20; i++)
            {
                dt.AddRow(
                    i.ToString(),
                    new[]
                {
                    TestTools.UpperAlphanumeric.BuildRandomStringFrom(10, 15).Trim(),
                    TestTools.AlphanumericIdentifier.BuildRandomStringFrom(8, 40).Trim(),
                    TestTools.AlphaSentence.BuildRandomStringFrom(20, 50).Trim(),
                    TestTools.GetRandomFloat(10000).ToString("N2", CultureInfo.CurrentCulture),
                    TestTools.GetRandomFloat(50000).ToString("N2", CultureInfo.CurrentCulture),
                    TestTools.GetRandomFloat(3000000).ToString("N2", CultureInfo.CurrentCulture)
                });
            }

            simpleTablePrinter.PrintTable(dt);
            console.WriteLine();

            simpleTableWithWrapping.PrintTable(dt);
            console.WriteLine();

            framedPrinter.PrintTable(dt);
            console.WriteLine();

            // TODO: also wrapping framed table

            specflowPrinter.PrintTable(dt);
            console.WriteLine();

            specflowTableWithWrapping.PrintTable(dt);
            console.WriteLine();

            console.WriteLine(tableFrameColor, "");


            console.WaitForNextPage();
        }
        /// <summary>
        /// Prints data as simple, frame-less table
        /// </summary>
        /// <param name="columns"></param>
        /// <param name="rows"></param>
        /// <param name="tableHeaderColor"></param>
        /// <param name="tableRowColor"></param>
        public void PrintAsSimpleTable(ColumnInfo[] columns, string[][] rows, ConsoleFontColor tableHeaderColor, ConsoleFontColor tableRowColor)
        {
            this.CalculateRequiredRowSizes(columns, rows);

            int spacingWidth        = columns.Length - 1;
            int totalAvailableWidth = this._console.WindowWidth - 1; // -1 for ENDL - need to not overflow, to avoid empty lines
            int maxRequiredWidth    = columns.Select(col => col.CurrentLength).Sum() + spacingWidth;

            if (maxRequiredWidth < totalAvailableWidth)
            {
                // cool, table fits to the screen
                int    index     = 0;
                string formatter = string.Join(" ", columns.Select(col => $"{{{index++},{col.CurrentLength * (int)col.Alignment}}}"));
                this._console.WriteLine(tableHeaderColor, string.Format(formatter, columns.Select(col => col.Header).ToArray()));
                foreach (string[] row in rows)
                {
                    // TODO: add missing cells...
                    this._console.WriteLine(tableRowColor, string.Format(formatter, row));
                }
            }
            else
            {
                int   availableWidth = totalAvailableWidth - spacingWidth;
                float scale          = (float)this._console.WindowWidth / (float)maxRequiredWidth;
                for (int i = 0; i < columns.Length; i++)
                {
                    // TODO:probably round would be as good... gonna check
                    int newLength = (int)Math.Floor(columns[i].CurrentLength * scale);
                    if (newLength < columns[i].MinLength)
                    {
                        newLength = Math.Min(availableWidth, columns[i].MinLength); // if all columns have minWidth and overflow the screen - some will not be displayed at all...
                        columns[i].CurrentLength = newLength;
                    }

                    availableWidth -= newLength;
                    if (availableWidth < 0)
                    {
                        newLength      = newLength - (Math.Abs(availableWidth));
                        availableWidth = 0;
                    }
                    columns[i].CurrentLength = Math.Max(0, newLength);
                }

                int    index     = 0;
                string formatter = string.Join(" ", columns.Select(col => $"{{{index++},{(col.CurrentLength) * (int)col.Alignment}}}"));
                // ReSharper disable once CoVariantArrayConversion, fine I want string version
                this._console.WriteLine(tableHeaderColor, string.Format(formatter, columns.Select(col => col.Header.Substring(0, Math.Min(col.Header.Length, col.CurrentLength))).ToArray()));
                foreach (string[] row in rows)
                {
                    string[] result = new string[columns.Length];
                    for (int i = 0; i < columns.Length; i++)
                    {
                        if (row.Length > i) // taking care for assymetric array, btw
                        {
                            if (row[i].Length <= columns[i].CurrentLength)
                            {
                                result[i] = row[i];
                            }
                            else
                            {
                                result[i] = row[i].Substring(0, columns[i].CurrentLength);
                            }
                        }
                    }

                    this._console.WriteLine(tableRowColor, string.Format(formatter, result));
                }
            }
        }
 public void PrintAsSimpleTable <T>(DataTable <T> table, ConsoleFontColor tableHeaderColor, ConsoleFontColor tableRowColor)
 {
     this.PrintAsSimpleTable(table.Columns.Values.ToArray(), table.GetRows().ToArray(), tableHeaderColor, tableRowColor);
 }
 public bool WriteTextBox(Rectangle textArea, string text, ConsoleFontColor colorDef)
 {
     return(this.WriteTextBox(textArea.X, textArea.Y, textArea.Width, textArea.Height, text, colorDef));
 }
        public bool WriteTextBox(int x, int y, int boxWidth, int boxHeight, string text, ConsoleFontColor colorDef)
        {
            this.LimitBoxDimensions(x, y, ref boxWidth, ref boxHeight); // so do not have to check for this every line is drawn...
            this._console.SetCursorPosition(x, y);
            this._console.SetColors(colorDef.ForeColor, colorDef.BgColor);

            string[] lines = this.SplitText(text, boxWidth);
            int      i;

            for (i = 0; i < lines.Length && i < boxHeight; ++i)
            {
                this._console.SetCursorPosition(x, y + i);
                this.WriteJustified(lines[i], boxWidth);
            }

            return(i == lines.Length);
        }