Exemplo n.º 1
0
        private static void Main([NotNull] string[] args)
        {
            Log.SetTrace(validLevels: LoggingLevels.None);
            Log.SetConsole(Log.ShortFormat);
            //Log.AddLogger(new EventLogger("Events"));

            FormatBuilder prompt = new FormatBuilder()
                .AppendForegroundColor(Color.Chartreuse)
                .Append('[')
                .AppendFormat("{time:hh:MM:ss.ffff}")
                .AppendResetForegroundColor()
                .Append("] > ");

            Log.Add(new LogContext().Set("Test key", "Test value"), "Test Message");

            Log.Add(new InvalidOperationException("An invalid operation example."));

            foreach (LoggingLevel level in Enum.GetValues(typeof (LoggingLevel)))
                Log.Add(level, level.ToString());

            string line;
            do
            {
                prompt.WriteToConsole(null, new Dictionary<string, object> {{"time", DateTime.UtcNow}});
                line = Console.ReadLine();
            } while (!string.IsNullOrWhiteSpace(line));
        }
        public void TestPadToWrap()
        {
            const int width = 60;

            string text =
                new FormatBuilder(new Layout(width, alignment: Alignment.Justify, wrapMode: LayoutWrapMode.PadToWrap))
                    .AppendLine(FormatResources.LoremIpsum)
                    .AppendLine()
                    .AppendLayout(alignment: Alignment.Left)
                    .AppendLine(FormatResources.SedUtPerspiciatis)
                    .AppendLine()
                    .AppendLayout(alignment: Alignment.Right)
                    .AppendLine(FormatResources.AtVeroEos)
                    .AppendLine()
                    .AppendLayout(
                        alignment: Alignment.Centre,
                        firstLineIndentSize: 4,
                        indentSize: 4,
                        rightMarginSize: 4)
                    .AppendLine(FormatResources.AtVeroEos).ToString();

            // Simulate console wrapping
            for (int i = 0; i < text.Length; i += width)
            {
                Trace.Write((i + width) >= text.Length ? text.Substring(i) : text.Substring(i, width));
                Trace.WriteLine("|");
            }

            Assert.IsFalse(text.Contains('\r'), "Text should not contain new line characters");
            Assert.IsFalse(text.Contains('\n'), "Text should not contain new line characters");
            Assert.IsTrue(text.Length % width == 0, "Text length should be a multiple of the width");
        }
Exemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TraceLogger" /> class.
 /// </summary>
 /// <param name="name">The logger name.</param>
 /// <param name="validLevels">The valid log levels.</param>
 /// <param name="format">The format.</param>
 public TraceLogger(
     [NotNull] string name,
     [CanBeNull] FormatBuilder format = null,
     LoggingLevels validLevels        = LoggingLevels.All)
     : base(name, TraceTextWriter.Default, format, false, validLevels)
 {
 }
Exemplo n.º 4
0
        public void TestResolver()
        {
            FormatBuilder builder = new FormatBuilder("{A}{B}{C}");

            builder.Resolve((_, c) => c.Tag.ToLowerInvariant() == "b" ? 5 : Resolution.Unknown);
            Assert.AreEqual("{A}5{C}", builder.ToString());
        }
        public void TestEmptyChunksIgnored()
        {
            Dictionary <string, object> dictionary = new Dictionary <string, object> {
                { "tag", Resolution.Empty }
            };

            FormatBuilder builder = new FormatBuilder(100, 4, firstLineIndentSize: 4)
                                    .AppendFormat("Text{tag}text");

            Assert.AreEqual("    Texttext", builder.ToString(dictionary));

            builder.Clear();
            builder.AppendFormat("Text{tag}");

            Assert.AreEqual("    Text", builder.ToString(dictionary));

            builder.Clear();
            builder.AppendFormat("Text{tag: sub {tag}}");

            Assert.AreEqual("    Text sub ", builder.ToString(dictionary));

            builder.Clear();
            builder.AppendFormat("Text{tag:{<items>:{<item>}}}");

            Assert.AreEqual("    Text", builder.ToString(dictionary));
        }
Exemplo n.º 6
0
        public void TestFormatBuilderToString()
        {
            FormatBuilder builder =
                new FormatBuilder().AppendFormat("{!control}{TestA}, {TestB,4}, {TestC,-4}, {TestD:F4}");

            Trace.WriteLine("default before resolving");
            string str = builder.ToString();
            Trace.WriteLine("    " + str);
            Assert.AreEqual("{TestA}, {TestB,4}, {TestC,-4}, {TestD:F4}", str);

            Trace.WriteLine("default after resolving the first 3 points");
            Dictionary<string, object> dictionary = new Dictionary<string, object>
            {
                {"TestA", "abc"},
                {"TestB", 4},
                {"TestC", 5},
            };
            str = builder.ToString(dictionary);
            Trace.WriteLine("    " + str);
            Assert.AreEqual("abc,    4, 5   , {TestD:F4}", str);

            Trace.WriteLine("'F' after resolving the first 3 points");
            str = builder.ToString("f", null, dictionary);
            Trace.WriteLine("    " + str);
            Assert.AreEqual("{!control}{TestA}, {TestB,4}, {TestC,-4}, {TestD:F4}", str);

            Trace.WriteLine("'S' after resolving the first 3 points");
            str = builder.ToString("s", null, dictionary);
            Trace.WriteLine("    " + str);
            Assert.AreEqual("abc,    4, 5   , ", str);
        }
Exemplo n.º 7
0
        public void TestFormatBuilderToString()
        {
            FormatBuilder builder =
                new FormatBuilder().AppendFormat("{!control}{TestA}, {TestB,4}, {TestC,-4}, {TestD:F4}");

            Trace.WriteLine("default before resolving");
            string str = builder.ToString();

            Trace.WriteLine("    " + str);
            Assert.AreEqual("{TestA}, {TestB,4}, {TestC,-4}, {TestD:F4}", str);

            Trace.WriteLine("default after resolving the first 3 points");
            Dictionary <string, object> dictionary = new Dictionary <string, object>
            {
                { "TestA", "abc" },
                { "TestB", 4 },
                { "TestC", 5 },
            };

            str = builder.ToString(dictionary);
            Trace.WriteLine("    " + str);
            Assert.AreEqual("abc,    4, 5   , {TestD:F4}", str);

            Trace.WriteLine("'F' after resolving the first 3 points");
            str = builder.ToString("f", null, dictionary);
            Trace.WriteLine("    " + str);
            Assert.AreEqual("{!control}{TestA}, {TestB,4}, {TestC,-4}, {TestD:F4}", str);

            Trace.WriteLine("'S' after resolving the first 3 points");
            str = builder.ToString("s", null, dictionary);
            Trace.WriteLine("    " + str);
            Assert.AreEqual("abc,    4, 5   , ", str);
        }
Exemplo n.º 8
0
        public void TestResolveControlChunk()
        {
            FormatBuilder builder = new FormatBuilder()
                                    .AppendFormat("{" + FormatBuilder.ForegroundColorTag + ":Custom}")
                                    .Resolve(
                (_, c) =>
            {
                if (string.Equals(
                        c.Tag,
                        FormatBuilder.ForegroundColorTag,
                        StringComparison.CurrentCultureIgnoreCase) &&
                    string.Equals(c.Format, "Custom"))
                {
                    return(Color.Green);
                }
                return(Resolution.Unknown);
            },
                false,
                true);

            using (TestColoredTextWriter writer = new TestColoredTextWriter(true))
            {
                builder.WriteTo(writer);
                Assert.AreEqual("{fg:Green}", writer.ToString());
            }
        }
Exemplo n.º 9
0
            /// <summary>
            /// Initializes a new instance of the <see cref="LogFile" /> class.
            /// </summary>
            /// <param name="fileStream">The file stream.</param>
            /// <param name="fileName">Name of the file.</param>
            /// <param name="format">The format.</param>
            /// <param name="start">The start.</param>
            public LogFile(
                [NotNull] FileStream fileStream,
                [NotNull] string fileName,
                [NotNull] FormatBuilder format,
                DateTime start)
            {
                Format = format;
                Start  = start;

                // Calculate style.
                Style = Format == Log.XMLFormat
                    ? LogFileStyle.XML
                    : (Format == Log.JSONFormat
                        ? LogFileStyle.JSON
                        : LogFileStyle.Text);

                FileName    = fileName;
                _fileStream = fileStream;

                switch (Style)
                {
                case LogFileStyle.XML:
                    WriteLine("<Logs>" + Environment.NewLine + "</Logs>").Wait();
                    break;

                case LogFileStyle.JSON:
                    WriteLine("[" + Environment.NewLine + "]").Wait();
                    break;

                default:
                    Write(Format.ToString("F") + Environment.NewLine + Environment.NewLine)
                    .Wait();
                    break;
                }
            }
Exemplo n.º 10
0
        private void ProcessOpeningBrace()
        {
            Pos++;
            if (Pos < TemplateString.Length && TemplateString[Pos] == '{')
            {
                Pos++;
                FormatBuilder.Append("{{");
                OpeningBraceIndex = TemplateString.IndexOf("{", Pos);
                return;
            }

            if (ClosingBraceIndex < 0)
            {
                FormatBuilder.Append("{{");
                OpeningBraceIndex = TemplateString.IndexOf("{", Pos);
                return;
            }

            var selectorExpression = TemplateString.Substring(Pos, ClosingBraceIndex - Pos);
            var valueSelector      = CreateValueSelector(selectorExpression);

            FormatBuilder.Append("{" + ValueSelectors.Count + "}");
            ValueSelectors.Add(valueSelector);

            Pos = ClosingBraceIndex + 1;
            OpeningBraceIndex = TemplateString.IndexOf("{", Pos);
            ClosingBraceIndex = TemplateString.IndexOf("}", Pos);
        }
Exemplo n.º 11
0
        public void TestFormatBuilderToStringWhitespaceAndAlign()
        {
            // Create a format builder with limited width and special characters.
            FormatBuilder f = new FormatBuilder(5, format: "{tag}\t\twith tabs\r\nand new lines.");

            Assert.AreEqual("{tag}\t\twith tabs\r\nand new lines.", f.ToString("f"));
        }
        public void TestPadToWrap()
        {
            const int width = 60;

            string text =
                new FormatBuilder(new Layout(width, alignment: Alignment.Justify, wrapMode: LayoutWrapMode.PadToWrap))
                .AppendLine(FormatResources.LoremIpsum)
                .AppendLine()
                .AppendLayout(alignment: Alignment.Left)
                .AppendLine(FormatResources.SedUtPerspiciatis)
                .AppendLine()
                .AppendLayout(alignment: Alignment.Right)
                .AppendLine(FormatResources.AtVeroEos)
                .AppendLine()
                .AppendLayout(
                    alignment: Alignment.Centre,
                    firstLineIndentSize: 4,
                    indentSize: 4,
                    rightMarginSize: 4)
                .AppendLine(FormatResources.AtVeroEos).ToString();

            // Simulate console wrapping
            for (int i = 0; i < text.Length; i += width)
            {
                Trace.Write((i + width) >= text.Length ? text.Substring(i) : text.Substring(i, width));
                Trace.WriteLine("|");
            }

            Assert.IsFalse(text.Contains('\r'), "Text should not contain new line characters");
            Assert.IsFalse(text.Contains('\n'), "Text should not contain new line characters");
            Assert.IsTrue(text.Length % width == 0, "Text length should be a multiple of the width");
        }
Exemplo n.º 13
0
        public void TestNestedResolver()
        {
            DictionaryResolvable resolvable = new DictionaryResolvable
            {
                {
                    "A", new DictionaryResolvable
                    {
                        {"A", "aa"},
                        {"B", "ab"}
                    }
                },
                {
                    "B", new DictionaryResolvable
                    {
                        {"A", "ba"},
                        {"B", "bb"}
                    }
                }
            };

            FormatBuilder builder = new FormatBuilder().AppendFormat("{0:{A:{B:{A}}} {B:{A:{B}}}}", resolvable);
            Assert.AreEqual("aa bb", builder.ToString());
            /* WHY????
             * Step 1: {0:...} is resolved to 'resolvable'
             * Step 2: There's a format, so the resolvable is called to resolve it.
             * Step 3: {A:...} and {B:...} are resolved to two new Resolvables (the two inside the dictionary above).
             *    This bits, important, these are the last two resolvables on the stack...
             * Step 4: {B:{A}} is resolved to "ab" (note not a resolvable), and {A:{B}} is resolved to "ba".
             * Step 5: {A} is resolved by the resolvable on the stack at that point (the one belonging to 'A') as the B
             *    is not a resolvable itself.  Therefore the A is "aa".  Similarly for the {B}.
             *    
             * {Context:\r\n{Key}\t: {Value}} =>
             * {Context.Resource:\r\n{Key}\t: {Value}
             */
        }
Exemplo n.º 14
0
        public void TestResolveObjects()
        {
            TestClass tc = new TestClass(123, true, new List <int> {
                1, 1, 2, 3, 5, 8
            });
            FormatBuilder builder = new FormatBuilder();

            builder.AppendFormat(
                "{0:({Number:N2}, {Boolean}) [{List:{<items>:{<item>}}{<join>:,}}]}",
                tc);
            Assert.AreEqual("(123.00, True) [1,1,2,3,5,8]", builder.ToString());

            builder.Clear();
            builder.AppendFormat(
                "{0:Count: {Count} \\{ {<items>:\\{{Key}: {Value}\\}}{<join>:, } \\}}",
                new Dictionary <string, int>
            {
                { "Foo", 123 },
                { "Bar", 456 },
                { "Test", 789 }
            });
            Assert.AreEqual("Count: 3 { {Foo: 123}, {Bar: 456}, {Test: 789} }", builder.ToString());

            builder.Clear();
            builder.AppendFormat(
                "Length: {0:{Length}} \"{0}\"",
                FormatResources.LoremIpsum);
            Assert.AreEqual(string.Format("Length: {0} \"{1}\"", FormatResources.LoremIpsum.Length, FormatResources.LoremIpsum), builder.ToString());
        }
Exemplo n.º 15
0
        private static void Main([NotNull] string[] args)
        {
            Log.SetTrace(validLevels: LoggingLevels.None);
            Log.SetConsole(Log.ShortFormat);
            //Log.AddLogger(new EventLogger("Events"));

            FormatBuilder prompt = new FormatBuilder()
                                   .AppendForegroundColor(Color.Chartreuse)
                                   .Append('[')
                                   .AppendFormat("{time:hh:MM:ss.ffff}")
                                   .AppendResetForegroundColor()
                                   .Append("] > ");

            Log.Add(new LogContext().Set("Test key", "Test value"), "Test Message");

            Log.Add(new InvalidOperationException("An invalid operation example."));

            foreach (LoggingLevel level in Enum.GetValues(typeof(LoggingLevel)))
            {
                Log.Add(level, level.ToString());
            }

            string line;

            do
            {
                prompt.WriteToConsole(null, new Dictionary <string, object> {
                    { "time", DateTime.UtcNow }
                });
                line = Console.ReadLine();
            } while (!string.IsNullOrWhiteSpace(line));
        }
Exemplo n.º 16
0
        public void TestResolableGetsCorrectPositionWithLayoutNone()
        {
            var           rwt     = new RWTest("key", "value");
            FormatBuilder builder = new FormatBuilder(20).AppendFormatLine(" {position} {position}\r\n{position}");

            Assert.AreEqual(" 1 3\r\n0\r\n", builder.ToString(rwt));
        }
Exemplo n.º 17
0
        public void TestResolvableEnumeration()
        {
            DictionaryResolvable resolvable = new DictionaryResolvable
            {
                {
                    "A", new List <IResolvable>
                    {
                        new DictionaryResolvable
                        {
                            { "A", "A" },
                            { "B", "B" },
                            { "C", "C" },
                        },
                        new DictionaryResolvable
                        {
                            { "A", "D" },
                            { "B", "E" },
                            { "C", "F" },
                        },
                        new DictionaryResolvable
                        {
                            { "A", "G" },
                            { "B", "H" },
                            { "C", "J" },
                            { "<INDEX>", "I" }
                        }
                    }
                }
            };

            FormatBuilder builder =
                new FormatBuilder().AppendFormat("{0:{A:[{<ITEMS>:{<INDEX>} {A} {B} {C}}{<JOIN>:, }]}}", resolvable);

            Assert.AreEqual("[0 A B C, 1 D E F, I G H J]", builder.ToString());
        }
Exemplo n.º 18
0
        public void TestNestedResolver()
        {
            FormatBuilder builder = new FormatBuilder("{t:A {t:nested {t}}}");

            builder.Resolve((_, c) => string.Equals(c.Tag, "t", StringComparison.CurrentCultureIgnoreCase) ? "tag" : Resolution.Unknown);
            Assert.AreEqual("A nested tag", builder.ToString());
        }
        public void TestIndents()
        {
            FormatBuilder builder = new FormatBuilder(20, 3, firstLineIndentSize: 1, alignment: Alignment.Left)
                                    .Append("Some really long string that should be laid out properly");

            Assert.AreEqual(" Some really long\r\n   string that\r\n   should be laid\r\n   out properly", builder.ToString());
        }
Exemplo n.º 20
0
 public string ToString([CanBeNull] FormatBuilder format, [CanBeNull] IFormatProvider formatProvider = null)
 {
     using (TextWriter writer = new StringWriter(formatProvider))
     {
         WriteTo(writer, format);
         return(writer.ToString());
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="FormattedStringWriter" /> class.
 /// </summary>
 /// <param name="builder">The builder.</param>
 /// <param name="formatProvider">The format provider.</param>
 public FormattedStringWriter(
     [CanBeNull] FormatBuilder builder = null,
     [CanBeNull] IFormatProvider formatProvider = null)
     : base(formatProvider)
 {
     _builder = builder ?? new FormatBuilder();
     _isOpen = true;
 }
Exemplo n.º 22
0
        public void TestResolableGetsCorrectPositionWithLayoutLeft()
        {
            var           rwt     = new RWTest("key", "value");
            FormatBuilder builder = new FormatBuilder(20, alignment: Alignment.Left).AppendFormatLine(" {position} {position}\r\n{position}");

            // Position is always pre-alignment...
            Assert.AreEqual("1 3\r\n0\r\n", builder.ToString(rwt));
        }
Exemplo n.º 23
0
 /// <summary>
 /// Writes the specified builder.
 /// </summary>
 /// <param name="builder">The builder.</param>
 public void Write([CanBeNull] FormatBuilder builder)
 {
     if (!_isOpen)
     {
         throw new InvalidOperationException(Resources.FormatWriter_IsClosed);
     }
     _builder.Append(builder);
 }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FormattedStringWriter" /> class.
 /// </summary>
 /// <param name="builder">The builder.</param>
 /// <param name="formatProvider">The format provider.</param>
 public FormattedStringWriter(
     [CanBeNull] FormatBuilder builder          = null,
     [CanBeNull] IFormatProvider formatProvider = null)
     : base(formatProvider)
 {
     _builder = builder ?? new FormatBuilder();
     _isOpen  = true;
 }
Exemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TraceLogger" /> class.
 /// </summary>
 /// <param name="name">The logger name.</param>
 /// <param name="writer">The writer.</param>
 /// <param name="format">The format.</param>
 /// <param name="validLevels">The valid log levels.</param>
 public TextWriterLogger(
     [NotNull] string name,
     [NotNull] TextWriter writer,
     [CanBeNull] FormatBuilder format = null,
     LoggingLevels validLevels        = LoggingLevels.All)
     : this(name, writer, format, true, validLevels)
 {
 }
Exemplo n.º 26
0
        public void TestEnumerations()
        {
            FormatBuilder builder = new FormatBuilder().AppendFormat(
                "{0:[{<Items>:0.00}{<JOIN>:, }]}",
                new[] { 1, 2, 3, 4 });

            Assert.AreEqual("[1.00, 2.00, 3.00, 4.00]", builder.ToString());
        }
Exemplo n.º 27
0
        public void TestEnumerationsWithItemIndex()
        {
            FormatBuilder builder = new FormatBuilder().AppendFormat(
                "{0:[{<items>:{<Index>}-{<Item>:0.00}}{<JOIN>:, }]}",
                new[] { 1, 2, 3, 4 });

            Assert.AreEqual("[0-1.00, 1-2.00, 2-3.00, 3-4.00]", builder.ToString());
        }
Exemplo n.º 28
0
        public void TestNestedResolvable()
        {
            var           rwt     = new RWTest("key", "value");
            FormatBuilder builder = new FormatBuilder(50)
                                    .AppendFormatLine("{nest}");

            // Position is always pre-alignment...
            Assert.AreEqual("UnspecKeyUnspecValue\r\n", builder.ToString(rwt));
        }
Exemplo n.º 29
0
        public void TestNestedFormat()
        {
            var           rwt     = new RWTest("key", "value");
            FormatBuilder builder = new FormatBuilder(10, firstLineIndentSize: 2, indentSize: 4, alignment: Alignment.Left)
                                    .AppendFormatLine("{key:-{position:-{value}}}");

            // Position is always pre-alignment...
            Assert.AreEqual("  --value\r\n", builder.ToString(rwt));
        }
Exemplo n.º 30
0
        public void TestDynamicFill()
        {
            var           rwt     = new RWTest("key", "value");
            FormatBuilder builder = new FormatBuilder(10, firstLineIndentSize: 2, indentSize: 4, alignment: Alignment.Left)
                                    .AppendFormatLine("{!fill}a{!fill}{!fill}");

            // Position is always pre-alignment...
            Assert.AreEqual("  --------\r\n  a\r\n  --------\r\n  --------\r\n\r\n", builder.ToString(rwt));
        }
Exemplo n.º 31
0
        public void TestResolableRespectsAlignmentOnDefault()
        {
            var           rwt      = new RWTest("key", "value");
            FormatBuilder builder  = new FormatBuilder(12, alignment: Alignment.Centre).AppendFormatLine("{0}", rwt);
            FormatBuilder builder2 = new FormatBuilder(12, alignment: Alignment.Centre).AppendFormatLine("{0:{Verbose}}", rwt);

            Assert.AreEqual("  keyvalue\r\n", builder.ToString());
            Assert.AreEqual("  keyvalue\r\n", builder2.ToString());
        }
        public void TestLayoutAfterControl()
        {
            FormatBuilder builder = new FormatBuilder(7, alignment: Alignment.Left)
                                    .AppendForegroundColor(Color.Red)
                                    .AppendLayout(alignment: Alignment.Right)
                                    .AppendLine("Right");

            Assert.AreEqual("  Right\r\n", builder.ToString());
        }
Exemplo n.º 33
0
        public void TestCloneRemovesReadonly()
        {
            FormatBuilder builder  = new FormatBuilder("Test", true);
            FormatBuilder builder2 = builder.Clone();

            Assert.IsTrue(builder.IsReadOnly);
            Assert.IsFalse(builder2.IsReadOnly);
            builder2.AppendLine();
        }
Exemplo n.º 34
0
 public Task WriteAsync([CanBeNull] FormatBuilder builder)
 {
     if (!_isOpen)
     {
         throw new InvalidOperationException(Resources.FormatWriter_IsClosed);
     }
     _builder.Append(builder);
     return(TaskResult.Completed);
 }
        public void TestNewLineFromMiddle()
        {
            FormatBuilder builder = new FormatBuilder(20, 10)
                                    .Append("Mid line\rFirst Line");

            int position = 5;

            Assert.AreEqual("Mid line\r\nFirst Line", builder.ToString(null, ref position));
            Assert.AreEqual(10, position);
        }
Exemplo n.º 36
0
        public void TestLargeEnumerable()
        {
            FormatBuilder builder = new FormatBuilder("{List:[{<Items>:0.00}{<JOIN>:, }]}");
            const int loop = 1000;
            const int items = 100;

            GC.Collect();
            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            Stopwatch sw = Stopwatch.StartNew();
            Parallel.For(0, loop, i => Enumerable.Range(0, items).ToArray());
            sw.Stop();

            GC.Collect();
            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            sw.Restart();
            Parallel.For(0, loop, i => Enumerable.Range(0, items).ToArray());
            sw.Stop();
            TimeSpan control = sw.Elapsed;

            GC.Collect();
            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            sw.Restart();
            Parallel.For(0, loop, i =>
            {
                string s = builder.ToString(
                    (w, c) => string.Equals(c.Tag, "list", StringComparison.CurrentCultureIgnoreCase)
                        ? Enumerable.Range(0, items)
                        : Resolution.Unknown);
            });
            sw.Stop();
            double builderTime = ((sw.Elapsed - control).TotalMilliseconds / loop);
            
            GC.Collect();
            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            sw.Restart();
            Parallel.For(0, loop, i => { var s = '[' + string.Join(", ", Enumerable.Range(0, items).Select(j => j.ToString("0.00"))) + ']'; });
            sw.Stop();
            double simpleTime = ((sw.Elapsed - control).TotalMilliseconds / loop);

            Trace.WriteLine(string.Format("Builder: {0:0.000}ms per item.", builderTime));
            Trace.WriteLine(string.Format("Simple: {0:0.000}ms per item.", simpleTime));
            Trace.WriteLine(string.Format("Simple takes {0:0.000}% of builder time.", (simpleTime / builderTime) * 100));
            Trace.WriteLine(string.Format("Builder takes {0:0.000}x longer than simple.", (builderTime / simpleTime)));
        }
Exemplo n.º 37
0
        public void TestColoredWriter()
        {
            FormatBuilder builder = new FormatBuilder()
                .Append("Some normal text, ")
                .AppendForegroundColor(Color.Red)
                .Append("some red text, ")
                .AppendResetForegroundColor()
                .Append("some more normal text, ")
                .AppendForegroundColor(Color.Green)
                .Append("some green ")
                .AppendBackgroundColor(Color.Blue)
                .Append("and some blue ")
                .AppendResetBackgroundColor()
                .AppendLine("and back to green.");

            using (TestColoredTextWriter writer = new TestColoredTextWriter(true))
            {
                builder.WriteTo(writer);

                Assert.AreEqual(
                    "Some normal text, {fg:Red}some red text, {/fg}some more normal text, {fg:Green}some green {bg:Blue}and some blue {/bg}and back to green.\r\n",
                    writer.ToString());
            }
        }
Exemplo n.º 38
0
 public void TestEnumerationsWithItemIndex()
 {
     FormatBuilder builder = new FormatBuilder().AppendFormat(
         "{0:[{<items>:{<Index>}-{<Item>:0.00}}{<JOIN>:, }]}",
         new[] { 1, 2, 3, 4 });
     Assert.AreEqual("[0-1.00, 1-2.00, 2-3.00, 3-4.00]", builder.ToString());
 }
Exemplo n.º 39
0
 public void TestEnumerations()
 {
     FormatBuilder builder = new FormatBuilder().AppendFormat(
         "{0:[{<Items>:0.00}{<JOIN>:, }]}",
         new[] { 1, 2, 3, 4 });
     Assert.AreEqual("[1.00, 2.00, 3.00, 4.00]", builder.ToString());
 }
 public void TestResolableUsesNamedFormat()
 {
     FormatBuilder builder = new FormatBuilder().AppendFormat("{0:{Reversed}}", new RWTest("key", "value"));
     Assert.AreEqual("valuekey", builder.ToString());
 }
 public void TestResolableUsesCustomFormat()
 {
     FormatBuilder builder = new FormatBuilder().AppendFormat("{0:{Value}}", new RWTest("key", "value"));
     Assert.AreEqual("value", builder.ToString());
 }
 public void TestDynamicFill()
 {
     var rwt = new RWTest("key", "value");
     FormatBuilder builder = new FormatBuilder(10, firstLineIndentSize: 2, indentSize: 4, alignment: Alignment.Left)
         .AppendFormatLine("{!fill}a{!fill}{!fill}");
     // Position is always pre-alignment...
     Assert.AreEqual("  --------\r\n  a\r\n  --------\r\n  --------\r\n\r\n", builder.ToString(rwt));
 }
 public void TestResolableRespectsAlignmentOnDefault()
 {
     var rwt = new RWTest("key", "value");
     FormatBuilder builder = new FormatBuilder(12, alignment: Alignment.Centre).AppendFormatLine("{0}", rwt);
     FormatBuilder builder2 = new FormatBuilder(12, alignment: Alignment.Centre).AppendFormatLine("{0:{Verbose}}", rwt);
     Assert.AreEqual("  keyvalue\r\n", builder.ToString());
     Assert.AreEqual("  keyvalue\r\n", builder2.ToString());
 }
Exemplo n.º 44
0
 /// <summary>
 /// Writes this instance to a <paramref name="writer"/>.
 /// </summary>
 /// <param name="writer">The writer.</param>
 /// <param name="lineFormat">The format.</param>
 public override void WriteTo(TextWriter writer, FormatBuilder lineFormat = null)
     => WriteTo(writer, lineFormat, DifferenceExtensions.DefaultStringChunkFormat);
Exemplo n.º 45
0
        public void TestResolvableEnumeration()
        {
            DictionaryResolvable resolvable = new DictionaryResolvable
            {
                {
                    "A", new List<IResolvable>
                    {
                        new DictionaryResolvable
                        {
                            {"A", "A"},
                            {"B", "B"},
                            {"C", "C"},
                        },
                        new DictionaryResolvable
                        {
                            {"A", "D"},
                            {"B", "E"},
                            {"C", "F"},
                        },
                        new DictionaryResolvable
                        {
                            {"A", "G"},
                            {"B", "H"},
                            {"C", "J"},
                            {"<INDEX>", "I"}
                        }
                    }
                }
            };

            FormatBuilder builder =
                new FormatBuilder().AppendFormat("{0:{A:[{<ITEMS>:{<INDEX>} {A} {B} {C}}{<JOIN>:, }]}}", resolvable);
            Assert.AreEqual("[0 A B C, 1 D E F, I G H J]", builder.ToString());
        }
Exemplo n.º 46
0
        public void TestResolveObjects()
        {
            TestClass tc = new TestClass(123, true, new List<int>{1, 1, 2, 3, 5, 8});
            FormatBuilder builder = new FormatBuilder();
            builder.AppendFormat(
                "{0:({Number:N2}, {Boolean}) [{List:{<items>:{<item>}}{<join>:,}}]}",
                tc);
            Assert.AreEqual("(123.00, True) [1,1,2,3,5,8]", builder.ToString());

            builder.Clear();
            builder.AppendFormat(
                "{0:Count: {Count} \\{ {<items>:\\{{Key}: {Value}\\}}{<join>:, } \\}}",
                new Dictionary<string, int>
                {
                    {"Foo", 123},
                    {"Bar", 456},
                    {"Test", 789}
                });
            Assert.AreEqual("Count: 3 { {Foo: 123}, {Bar: 456}, {Test: 789} }", builder.ToString());

            builder.Clear();
            builder.AppendFormat(
                "Length: {0:{Length}} \"{0}\"",
                FormatResources.LoremIpsum);
            Assert.AreEqual(string.Format("Length: {0} \"{1}\"", FormatResources.LoremIpsum.Length, FormatResources.LoremIpsum), builder.ToString());
        }
Exemplo n.º 47
0
        public void TestReplaceColor()
        {
            FormatBuilder builder = new FormatBuilder()
                .Append("Some text. ")
                .AppendForegroundColor(Color.Red)
                .Append("Some red text. ")
                .AppendForegroundColor(Color.Green)
                .AppendLine("Some green text.");

            using (TestColoredTextWriter writer = new TestColoredTextWriter(true))
            {
                builder.WriteTo(writer);

                Assert.AreEqual(
                    "Some text. {fg:Red}Some red text. {fg:Green}Some green text.\r\n",
                    writer.ToString());
            }

            builder.Resolve(
                (_, c) =>
                    string.Equals(
                        c.Tag,
                        FormatBuilder.ForegroundColorTag,
                        StringComparison.CurrentCultureIgnoreCase) &&
                    string.Equals(
                        c.Format,
                        "Green",
                        StringComparison.CurrentCultureIgnoreCase)
                        ? new FormatChunk(c, Color.Blue)
                        : Resolution.UnknownYet,
                resolveControls: true);

            using (TestColoredTextWriter writer = new TestColoredTextWriter(true))
            {
                builder.WriteTo(writer);

                Assert.AreEqual(
                    "Some text. {fg:Red}Some red text. {fg:Blue}Some green text.\r\n",
                    writer.ToString());
            }
        }
Exemplo n.º 48
0
        private static FormatBuilder ValidatePathFormat(
            [NotNull] string directory,
            [NotNull] FormatBuilder fileNameFormat,
            [NotNull] ref string extension,
            [NotNull] FormatBuilder format)
        {
            if (directory == null) throw new ArgumentNullException("directory");
            if (fileNameFormat == null) throw new ArgumentNullException("fileNameFormat");
            if (extension == null) throw new ArgumentNullException("extension");
            if (format == null) throw new ArgumentNullException("format");

            if (string.IsNullOrWhiteSpace(directory))
                directory = DefaultDirectory;

            try
            {
                directory = Path.GetFullPath(directory.Trim());
                if (!System.IO.Directory.Exists(directory))
                    System.IO.Directory.CreateDirectory(directory);
            }
            catch (Exception e)
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                throw new LoggingException(
                    e,
                    LoggingLevel.Critical,
                    () => Resources.FileLogger_DirectoryAccessOrCreationError,
                    directory);
            }

            if (fileNameFormat.IsEmpty)
                // ReSharper disable once AssignNullToNotNullAttribute
                throw new LoggingException(LoggingLevel.Critical, () => Resources.FileLogger_FileNameFormatNotSpecified);


            if (string.IsNullOrWhiteSpace(extension))
                if (format == Log.XMLFormat)
                    extension = ".xml";
                else if (format == Log.JSONFormat)
                    extension = ".json";
                else
                    extension = ".log";
            else
            {
                extension = extension.Trim();
                if (extension.StartsWith("."))
                    extension = extension.Substring(1);
                if (extension.Any(c => !Char.IsLetterOrDigit(c)))
                    throw new LoggingException(
                        LoggingLevel.Critical,
                        // ReSharper disable once AssignNullToNotNullAttribute
                        () => Resources.FileLogger_Extension_Invalid_Char,
                        extension);
                if (extension.Length > 5)
                    throw new LoggingException(
                        LoggingLevel.Critical,
                        // ReSharper disable once AssignNullToNotNullAttribute
                        () => Resources.FileLogger_ExtensionLongerThanFiveCharacters,
                        extension);
                extension = "." + extension;
            }

            FormatBuilder pathBuilder = new FormatBuilder()
                .Append(directory)
                .Append('\\')
                .AppendFormat(fileNameFormat);

            // Add a dedupe tag if not already present
            // ReSharper disable once PossibleNullReferenceException
            Stack<FormatChunk> formatStack = new Stack<FormatChunk>();
            formatStack.Push(fileNameFormat.RootChunk);
            bool found = false;
            while (formatStack.Count > 0)
            {
                FormatChunk chunk = formatStack.Pop();
                // ReSharper disable once PossibleNullReferenceException
                if (string.Equals(chunk.Tag, FormatTagDedupe, StringComparison.CurrentCultureIgnoreCase))
                {
                    found = true;
                    break;
                }

                foreach (var child in chunk.Children)
                    formatStack.Push(child);
            }

            if (!found)
                pathBuilder.AppendFormat("{dedupe: ({dedupe:D})}");

            return pathBuilder
                .Append(extension)
                .MakeReadOnly();
        }
Exemplo n.º 49
0
            /// <summary>
            /// Initializes a new instance of the <see cref="LogFile" /> class.
            /// </summary>
            /// <param name="fileStream">The file stream.</param>
            /// <param name="fileName">Name of the file.</param>
            /// <param name="format">The format.</param>
            /// <param name="start">The start.</param>
            public LogFile(
                [NotNull] FileStream fileStream,
                [NotNull] string fileName,
                [NotNull] FormatBuilder format,
                DateTime start)
            {
                Format = format;
                Start = start;

                // Calculate style.
                Style = Format == Log.XMLFormat
                    ? LogFileStyle.XML
                    : (Format == Log.JSONFormat
                        ? LogFileStyle.JSON
                        : LogFileStyle.Text);

                FileName = fileName;
                _fileStream = fileStream;

                switch (Style)
                {
                    case LogFileStyle.XML:
                        WriteLine("<Logs>" + Environment.NewLine + "</Logs>").Wait();
                        break;
                    case LogFileStyle.JSON:
                        WriteLine("[" + Environment.NewLine + "]").Wait();
                        break;
                    default:
                        Write(Format.ToString("F") + Environment.NewLine + Environment.NewLine)
                            .Wait();
                        break;
                }
            }
Exemplo n.º 50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnderlyingFormatTextWriter" /> class.
 /// </summary>
 /// <param name="writer">The writer.</param>
 /// <param name="builder">The builder.</param>
 /// <param name="startPosition">The start position.</param>
 /// <exception cref="System.InvalidOperationException">Cannot wrap an ILayoutTextWriter in a FormatTextWriter as this can cause issues with position tracking.</exception>
 public UnderlyingFormatTextWriter(
     [NotNull] TextWriter writer,
     [NotNull] FormatBuilder builder,
     int startPosition)
 {
     if (writer == null) throw new ArgumentNullException("writer");
     if (builder == null) throw new ArgumentNullException("builder");
     if (writer is ILayoutTextWriter)
         throw new InvalidOperationException(
             "Cannot wrap an ILayoutTextWriter in a FormatTextWriter as this can cause issues with position tracking.");
     _writer = writer;
     Builder = builder;
     Position = startPosition;
 }
Exemplo n.º 51
0
 public void TestReplaceControl()
 {
     FormatBuilder builder = new FormatBuilder("{!control:text}");
     Assert.AreEqual("{!control:text}", builder.ToString("f"));
     Assert.AreEqual(
         "text",
         builder.ToString(
             (_, c) => c.IsControl && string.Equals(c.Tag, "!control", StringComparison.CurrentCultureIgnoreCase)
                 ? new FormatChunk(c.Format)
                 : Resolution.Unknown,
             resolveControls: true));
 }
Exemplo n.º 52
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileLogger" /> class.
        /// </summary>
        /// <param name="name">The filename.</param>
        /// <param name="directory">The directory to log to (default to entry assembly directory).</param>
        /// <param name="maxLog"><para>The maximum number of log items in a single log file.</para>
        /// <para>By default this is set to 1,000.</para></param>
        /// <param name="maxDuration">The maximum time period that a single log file can cover.</param>
        /// <param name="validLevels"><para>The valid log levels.</para>
        /// <para>By default allows <see cref="LoggingLevels">all log levels</see>.</para></param>
        /// <param name="format">The log format (default to "Verbose,Xml").</param>
        /// <param name="fileNameFormat"><para>The filename format - where {DateTime} is the creation date time.</para>
        /// <para>By default the format is "{ApplicationName}-{DateTime:yyMMddHHmmssffff}".</para></param>
        /// <param name="extension"><para>The file extension.</para>
        /// <para>By default this is set to use "log".</para></param>
        /// <param name="buffer">The buffer.</param>
        /// <param name="autoFlush">if set to <see langword="true" /> [auto flush].</param>
        /// <exception cref="LoggingException"><para>
        ///   <paramref name="maxLog" /> was less than 10, which would result in too many log files to be created.</para>
        /// <para>-or-</para>
        /// <para>
        ///   <paramref name="maxDuration" /> was less than 10 seconds, which would result in too many log files to be created.</para>
        /// <para>-or-</para>
        /// <para>
        ///   <paramref name="directory" /> was either <see cref="string.IsNullOrWhiteSpace">null or whitespace</see>.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="fileNameFormat" /> string was either <see cref="string.IsNullOrWhiteSpace">null or whitespace</see>.</para>
        /// <para>-or-</para>
        /// <para>An error occurred trying to access the <paramref name="directory" />.</para>
        /// <para>-or-</para>
        /// <para>
        ///   <paramref name="extension" /> was more than 5 characters long.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="fileNameFormat" /> led to an invalid path or created a path that references the wrong <paramref name="directory" />.</para>
        /// <para>-or-</para>
        /// <para>File path contained <see cref="Path.GetInvalidPathChars">invalid characters</see>.</para></exception>
        public FileLogger(
            [NotNull] string name,
            [CanBeNull] string directory = null,
            Int64 maxLog = 1000,
            TimeSpan maxDuration = default(TimeSpan),
            LoggingLevels validLevels = LoggingLevels.All,
            [CanBeNull] FormatBuilder format = null,
            [CanBeNull] FormatBuilder fileNameFormat = null,
            [CanBeNull] string extension = null,
            uint buffer = 65536,
            bool autoFlush = false)
            : base(name, true, validLevels)
        {
            MaxLog = maxLog;
            MaxDuration = maxDuration == default(TimeSpan) ? TimeSpan.FromDays(1) : maxDuration;
            _directory = directory ?? DefaultDirectory;
            _fileNameFormat = fileNameFormat ?? DefaultFileNameFormat;
            _extension = extension ?? string.Empty;
            if (format != null)
            {
                // If there is a single chunk with no format, children or alignment,
                // Check if it is one of the built in formats.
                FormatChunk[] formatChunks = format.RootChunk.Children.Take(2).ToArray();

                FormatChunk chunk = formatChunks.Length == 1
                    ? formatChunks[0]
                    : null;
                if ((chunk != null) &&
                    !chunk.IsResolved &&
                    !chunk.IsControl &&
                    (chunk.Tag != null) &&
                    (chunk.Alignment == 0) &&
                    (chunk.Format == null) &&
                    (!chunk.Children.Any()))
                    switch (chunk.Tag.ToLowerInvariant())
                    {
                        case "all":
                            format = Log.AllFormat;
                            break;
                        case "verbose":
                            format = Log.VerboseFormat;
                            break;
                        case "xml":
                            format = Log.XMLFormat;
                            break;
                        case "json":
                            format = Log.JSONFormat;
                            break;
                        case "short":
                            format = Log.ShortFormat;
                            break;
                    }
            }
            _format = format ?? Log.VerboseFormat;
            _pathFormat = ValidatePathFormat(_directory, _fileNameFormat, ref _extension, _format);
            Buffer = buffer;
            AutoFlush = autoFlush;
        }
Exemplo n.º 53
0
        /// <summary>
        /// Runs the specified service using the command console as a user interface.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="runMode">The run mode.</param>
        /// <param name="defaultLogFormat">The default log format.</param>
        /// <param name="defaultLoggingLevels">The default logging levels.</param>
        /// <param name="token">The token.</param>
        /// <returns>
        /// An awaitable task.
        /// </returns>
        // ReSharper disable once CodeAnnotationAnalyzer
        public static async Task RunAsync(
            [NotNull] BaseService service,
            RunMode runMode = RunMode.Default,
            [CanBeNull] FormatBuilder defaultLogFormat = null,
            LoggingLevels defaultLoggingLevels = LoggingLevels.All,
            CancellationToken token = default(CancellationToken))
        {
            if (service == null) throw new ArgumentNullException("service");

            if (!ConsoleHelper.IsConsole)
                return;
            Console.Clear();
            Log.SetTrace(validLevels: LoggingLevels.None);
            Log.SetConsole(defaultLogFormat ?? Log.ShortFormat, defaultLoggingLevels);
            await Log.Flush(token).ConfigureAwait(false);

            Impersonator impersonator = null;
            try
            {
                if (runMode.HasFlag(RunMode.Prompt))
                {
                    Debug.Assert(service.ServiceName != null);

                    // Whether we start will depend on the selected option in prompt.
                    runMode = runMode.Clear(RunMode.Start, true);

                    Console.Title = ServiceResources.ConsoleConnection_RunAsync_ConfigureTitle + service.ServiceName;
                    bool done = false;

                    do
                    {
                        if (token.IsCancellationRequested) return;

                        Dictionary<string, string> options = new Dictionary<string, string>
                        {
                            { "I", ServiceResources.ConsoleConnection_RunAsync_OptionInstall },
                            { "U", ServiceResources.ConsoleConnection_RunAsync_OptionUninstall },
                            { "S", ServiceResources.ConsoleConnection_RunAsync_OptionStart },
                            { "R", ServiceResources.ConsoleConnection_RunAsync_OptionRestart },
                            { "T", ServiceResources.ConsoleConnection_RunAsync_OptionStop },
                            { "P", ServiceResources.ConsoleConnection_RunAsync_OptionPause },
                            { "C", ServiceResources.ConsoleConnection_RunAsync_OptionContinue },
                            { "Y", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmd },
                            { "V", ServiceResources.ConsoleConnection_RunAsync_OptionStartCmd },
                            { "W", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmdNewCredentials },
                            { "Z", ServiceResources.ConsoleConnection_RunAsync_OptionRunNoInteraction },
                            { "X", ServiceResources.ConsoleConnection_RunAsync_OptionExit }
                        };

                        if (!runMode.HasFlag(RunMode.Interactive))
                        {
                            options.Remove("V");
                            options.Remove("Y");
                            options.Remove("W");
                        }

                        bool isAdmin;
                        string currentUser;
                        try
                        {
                            WindowsIdentity identity = WindowsIdentity.GetCurrent();
                            currentUser = identity.Name;
                            Debug.Assert(identity != null);
                            WindowsPrincipal principal = new WindowsPrincipal(identity);
                            isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
                        }
                        catch
                        {
                            isAdmin = false;
                            currentUser = null;
                        }

                        if (!string.IsNullOrEmpty(currentUser))
                        {
                            FormatBuilder fb = new FormatBuilder()
                                .AppendForegroundColor(ConsoleColor.Cyan)
                                .Append("Current User: "******" [Admin]");
                            fb.AppendLine().WriteToConsole();
                        }

                        if (!isAdmin)
                        {
                            options.Remove("I");
                            options.Remove("U");
                        }

                        if (Controller.ServiceIsInstalled(service.ServiceName))
                        {
                            ServiceControllerStatus state = Controller.GetServiceStatus(service.ServiceName);
                            new FormatBuilder()
                                .AppendForegroundColor(ConsoleColor.White)
                                .AppendFormatLine(
                                    ServiceResources.ConsoleConnection_RunAsync_ServiceInstalledState,
                                    service.ServiceName,
                                    state)
                                .AppendResetForegroundColor()
                                .WriteToConsole();

                            options.Remove("I");

                            switch (state)
                            {
                                case ServiceControllerStatus.StopPending:
                                case ServiceControllerStatus.Stopped:
                                    // Service is stopped or stopping.
                                    options.Remove("C");
                                    options.Remove("R");
                                    options.Remove("T");
                                    break;
                                case ServiceControllerStatus.StartPending:
                                case ServiceControllerStatus.ContinuePending:
                                case ServiceControllerStatus.Running:
                                    // Service is starting or running.
                                    options.Remove("S");
                                    options.Remove("C");
                                    break;
                                case ServiceControllerStatus.PausePending:
                                case ServiceControllerStatus.Paused:
                                    // Service is paused or pausing.
                                    options.Remove("S");
                                    options.Remove("R");
                                    options.Remove("T");
                                    options.Remove("P");
                                    break;
                                default:
                                    // Service is not installed - shouldn't happen.
                                    options.Remove("U");
                                    options.Remove("S");
                                    options.Remove("R");
                                    options.Remove("T");
                                    options.Remove("C");
                                    options.Remove("P");
                                    break;
                            }
                            options.Remove("V");
                            options.Remove("Y");
                            options.Remove("Z");
                        }
                        else
                        {
                            // No service installed.
                            options.Remove("U");
                            options.Remove("S");
                            options.Remove("R");
                            options.Remove("T");
                            options.Remove("P");
                            options.Remove("C");
                        }

                        _promptInstall.WriteToConsole(
                            null,
                            // ReSharper disable once PossibleNullReferenceException
                            (_, c) => !string.Equals(c.Tag, "options", StringComparison.CurrentCultureIgnoreCase)
                                ? Resolution.Unknown
                                : options);

                        string key;
                        do
                        {
                            key = Char.ToUpperInvariant(Console.ReadKey(true).KeyChar)
                                .ToString(CultureInfo.InvariantCulture);
                        } while (!options.ContainsKey(key));

                        try
                        {
                            string userName;
                            string password;

                            switch (key)
                            {
                                case "I":
                                    GetUserNamePassword(out userName, out password);

                                    service.Install(ConsoleTextWriter.Default, userName, password);

                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitInstall);
                                    while (!Controller.ServiceIsInstalled(service.ServiceName))
                                    {
                                        await Task.Delay(250, token).ConfigureAwait(false);
                                        Console.Write('.');
                                    }
                                    Console.WriteLine(ServiceResources.Done);
                                    Console.WriteLine();
                                    break;

                                case "U":
                                    await service.Uninstall(ConsoleTextWriter.Default, token).ConfigureAwait(false);

                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitUninstall);
                                    while (Controller.ServiceIsInstalled(service.ServiceName))
                                    {
                                        await Task.Delay(250, token).ConfigureAwait(false);
                                        Console.Write('.');
                                    }
                                    Console.WriteLine(ServiceResources.Done);
                                    Console.WriteLine();
                                    break;

                                case "R":
                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop);
                                    await Controller.StopService(service.ServiceName, token).ConfigureAwait(false);
                                    Console.WriteLine(ServiceResources.Done);
                                    Console.WriteLine();
                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart);
                                    await
                                        Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false);
                                    Console.WriteLine(ServiceResources.Done);
                                    Console.WriteLine();
                                    break;

                                case "S":
                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart);
                                    await
                                        Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false);
                                    Console.WriteLine(ServiceResources.Done);
                                    Console.WriteLine();
                                    break;

                                case "T":
                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop);
                                    await Controller.StopService(service.ServiceName, token).ConfigureAwait(false);
                                    Console.WriteLine(ServiceResources.Done);
                                    Console.WriteLine();
                                    break;

                                case "P":
                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingPause);
                                    await Controller.PauseService(service.ServiceName, token).ConfigureAwait(false);
                                    Console.WriteLine(ServiceResources.Done);
                                    break;

                                case "C":
                                    Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingContinue);
                                    await Controller.ContinueService(service.ServiceName, token).ConfigureAwait(false);
                                    Console.WriteLine(ServiceResources.Done);
                                    Console.WriteLine();
                                    break;

                                case "V":
                                    runMode = runMode.Set(RunMode.Start, true).Set(RunMode.Interactive, true);
                                    done = true;
                                    break;

                                case "Y":
                                    runMode = runMode.Set(RunMode.Interactive, true);
                                    done = true;
                                    break;

                                case "W":
                                    GetUserNamePassword(out userName, out password);
                                    if (userName == null)
                                        break;
                                    Debug.Assert(password != null);

                                    Impersonator ei = impersonator;
                                    impersonator = null;
                                    if (ei != null)
                                        ei.Dispose();
                                    // Run in new security context.
                                    impersonator = new Impersonator(userName, password);
                                    break;

                                case "Z":
                                    runMode = runMode.Set(RunMode.Start, true).Clear(RunMode.Interactive, true);
                                    done = true;
                                    Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive);
                                    Console.WriteLine(
                                        ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive2);
                                    Console.WriteLine();
                                    break;

                                default:
                                    return;
                            }
                        }
                        catch (TaskCanceledException)
                        {
                            return;
                        }
                        catch (Exception e)
                        {
                            if (!token.IsCancellationRequested)
                                Log.Add(e);
                        }
                    } while (!done);
                }
                else if (!runMode.HasFlag(RunMode.Interactive))
                    // If we don't show prompt and we're not interactive we should always start the service.
                    runMode = runMode.Set(RunMode.Start, true);

                // Create connection
                Console.Title = ServiceResources.ConsoleConnection_RunAsync_RunningTitle + service.ServiceName;
                ConsoleConnection connection = new ConsoleConnection(defaultLogFormat, defaultLoggingLevels, token);
                Guid id = service.Connect(connection);

                // Combined cancellation tokens.
                ITokenSource tSource = token.CreateLinked(connection._cancellationTokenSource.Token);
                try
                {
                    CancellationToken t = tSource.Token;

                    if (t.IsCancellationRequested) return;

                    if (runMode.HasFlag(RunMode.Start))
                    {
                        // Start the service
                        await service.StartService(ConsoleTextWriter.Default, null, t).ConfigureAwait(false);
                        if (t.IsCancellationRequested)
                            return;
                    }

                    if (!runMode.HasFlag(RunMode.Interactive))
                    {
                        // Wait to be cancelled as nothing to do.
                        await t.WaitHandle;
                        return;
                    }

                    do
                    {
                        // Flush logs
                        await Log.Flush(t).ConfigureAwait(false);

                        if (t.IsCancellationRequested) break;

                        WritePrompt(service);
                        try
                        {
                            string commandLine = await Console.In.ReadLineAsync().ConfigureAwait(false);
                            if (!string.IsNullOrWhiteSpace(commandLine))
                            {
                                bool completed = false;
                                ICancelableTokenSource commandCancellationSource = t.ToCancelable();
                                CancellationToken commandToken = commandCancellationSource.Token;

#pragma warning disable 4014
                                service.ExecuteAsync(id, commandLine, ConsoleTextWriter.Default, commandToken)
                                    .ContinueWith(
                                        task =>
                                        {
                                            Debug.Assert(task != null);

                                            completed = true;

                                            if (task.IsCompleted ||
                                                task.IsCanceled)
                                                return;

                                            if (task.IsFaulted)
                                            {
                                                Debug.Assert(task.Exception != null);
                                                _errorFormat.WriteToConsoleInstance(null, task.Exception);
                                            }
                                        },
                                        TaskContinuationOptions.ExecuteSynchronously);
#pragma warning restore 4014

                                while (!completed)
                                {
                                    if (!commandCancellationSource.IsCancellationRequested &&
                                        Console.KeyAvailable &&
                                        Console.ReadKey(true).Key == ConsoleKey.Escape)
                                    {
                                        // Cancel command
                                        Console.Write(ServiceResources.ConsoleConnection_RunAsync_Cancelling);
                                        commandCancellationSource.Cancel();
                                        break;
                                    }
                                    await Task.Delay(100, token).ConfigureAwait(false);
                                }
                            }
                        }
                        catch (TaskCanceledException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            if (!t.IsCancellationRequested)
                                _errorFormat.WriteToConsoleInstance(null, e);
                        }

                        // Let any async stuff done by the command have a bit of time, also throttle commands.
                        await Task.Delay(500, t).ConfigureAwait(false);
                    } while (!t.IsCancellationRequested);
                }
                catch (TaskCanceledException)
                {
                }
                finally
                {
                    tSource.Dispose();

                    // ReSharper disable MethodSupportsCancellation
                    Log.Flush().Wait();
                    // ReSharper restore MethodSupportsCancellation
                    service.Disconnect(id);
                    Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_PressKeyToExit);
                    Console.ReadKey(true);
                }
            }
            finally
            {
                if (impersonator != null)
                    impersonator.Dispose();
            }
        }
 public void TestResolableGetsCorrectPositionWithLayoutLeft()
 {
     var rwt = new RWTest("key", "value");
     FormatBuilder builder = new FormatBuilder(20, alignment: Alignment.Left).AppendFormatLine(" {position} {position}\r\n{position}");
     // Position is always pre-alignment...
     Assert.AreEqual("1 3\r\n0\r\n", builder.ToString(rwt));
 }
Exemplo n.º 55
0
        /// <summary>
        /// Writes this instance to a <paramref name="writer" />.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="lineFormat">The format.</param>
        /// <param name="chunkFormat">The chunk format.</param>
        public void WriteTo(TextWriter writer, FormatBuilder lineFormat, FormatBuilder chunkFormat)
        {
            if (writer == null) throw new ArgumentNullException(nameof(writer));

            if (lineFormat == null)
                lineFormat = DifferenceExtensions.DefaultLineFormat;
            if (chunkFormat == null)
                chunkFormat = DifferenceExtensions.DefaultStringChunkFormat;

            string[] aLines = A == null
                ? Array<string>.Empty
                : chunkFormat.ToString(new DictionaryResolvable() { { DifferenceExtensions.ChunkTag, A } })
                    .Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            string[] bLines = B == null
                ? Array<string>.Empty
                : chunkFormat.ToString(new DictionaryResolvable() { { DifferenceExtensions.ChunkTag, B } })
                    .Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            int maxLen = aLines.Length < bLines.Length ? bLines.Length : aLines.Length;

            string flag;
            if (AreEqual)
            {
                flag = " ";
            }
            else if (A == null)
            {
                flag = "+";
            }
            else if (B == null)
            {
                flag = "-";
            }
            else
            {
                flag = "!";
            }

            // Write out lines in chunk.
            for (int l = 0; l < maxLen; l++)
                lineFormat.WriteTo(
                    writer,
                    "G",
                    (_, c) =>
                    {
                        if (string.Equals(
                            c.Tag,
                            DifferenceExtensions.ChunkATag,
                            StringComparison.InvariantCultureIgnoreCase))
                            return l < aLines.Length ? aLines[l] : Resolution.Empty;
                        if (string.Equals(
                            c.Tag,
                            DifferenceExtensions.ChunkBTag,
                            StringComparison.InvariantCultureIgnoreCase))
                            return l < bLines.Length ? bLines[l] : Resolution.Empty;
                        if (string.Equals(
                            c.Tag,
                            DifferenceExtensions.FlagTag,
                            StringComparison.InvariantCultureIgnoreCase))
                            return flag;
                        if (string.Equals(
                            c.Tag,
                            DifferenceExtensions.SeparatorTag,
                            StringComparison.InvariantCultureIgnoreCase))
                            return " | ";

                        return Resolution.Unknown;
                    });
        }
 public void TestNestedFormat()
 {
     var rwt = new RWTest("key", "value");
     FormatBuilder builder = new FormatBuilder(10, firstLineIndentSize: 2, indentSize: 4, alignment: Alignment.Left)
         .AppendFormatLine("{key:-{position:-{value}}}");
     // Position is always pre-alignment...
     Assert.AreEqual("  --value\r\n", builder.ToString(rwt));
 }
        public void TestTabStops()
        {
            FormatBuilder builder = new FormatBuilder();
            builder
                .AppendLayout(
                    50,
                    firstLineIndentSize: 1,
                    tabStops: new[] {6, 9, 20, 30, 40})
                .Append("A\tTab Stop\tAnother");

            int position = 0;
            Assert.AreEqual(" A    Tab Stop      Another", builder.ToString(null, ref position));
            Assert.AreEqual(27, position);
            Assert.AreEqual("A  Tab Stop  Another", builder.ToString(null, ref position));
            Assert.AreEqual(47, position);
        }
 public void TestNestedResolvable()
 {
     var rwt = new RWTest("key", "value");
     FormatBuilder builder = new FormatBuilder(50)
         .AppendFormatLine("{nest}");
     // Position is always pre-alignment...
     Assert.AreEqual("UnspecKeyUnspecValue\r\n", builder.ToString(rwt));
 }
Exemplo n.º 59
0
 /// <summary>
 /// Prevents a default instance of the <see cref="ConsoleConnection"/> class from being created.
 /// </summary>
 // ReSharper disable once CodeAnnotationAnalyzer
 private ConsoleConnection(
     FormatBuilder defaultLogFormat,
     LoggingLevels defaultLoggingLevels,
     CancellationToken token)
 {
     if (!ConsoleHelper.IsConsole) throw new InvalidOperationException(CommonResources.Not_In_Console);
     _defaultLogFormat = defaultLogFormat;
     _defaultLoggingLevels = defaultLoggingLevels;
     _cancellationTokenSource = token.CanBeCanceled
         // ReSharper disable once PossiblyMistakenUseOfParamsMethod
         ? CancellationTokenSource.CreateLinkedTokenSource(token)
         : new CancellationTokenSource();
 }
 public void TestResolableGetsCorrectPositionWithLayoutNone()
 {
     var rwt = new RWTest("key", "value");
     FormatBuilder builder = new FormatBuilder(20).AppendFormatLine(" {position} {position}\r\n{position}");
     Assert.AreEqual(" 1 3\r\n0\r\n", builder.ToString(rwt));
 }