Exemplo n.º 1
0
        public void CompositeFormattingEscapingMissingStartBracket()
        {
            var pool = new ManagedBufferPool<byte>(1024);
            var formatter = new StringFormatter(pool);

            Assert.Throws<Exception>(() => formatter.Format("{0}}", 1));
        }
        public void CompositeFormattingFormatStrings()
        {
            var formatter = new StringFormatter(pool);
            formatter.Format("Hello{0:x}{1:X}{2:G}", 10, 255, 3);

            Assert.Equal("HelloaFF3", formatter.ToString());
        }
        public void CompositeFormattingEscaping()
        {
            var format = "}}a {0} b {0} c {{{0}}} d {{e}} {{";
            var formatter = new StringFormatter(pool);
            formatter.Format(format, 1);

            Assert.Equal(string.Format(CultureInfo.InvariantCulture, format, 1), formatter.ToString());
        }
Exemplo n.º 4
0
        public void CompositeFormattingFormatStrings()
        {
            var pool = new ManagedBufferPool<byte>(1024);
            var formatter = new StringFormatter(pool);
            formatter.Format("Hello{0:x}{1:X}{2:G}", 10, 255, 3);

            Assert.Equal("HelloaFF3", formatter.ToString());
        }
Exemplo n.º 5
0
        public void CompositeFormattingBasics()
        {
            var time = DateTime.UtcNow;
            var pool = new ManagedBufferPool<byte>(1024);
            var formatter = new StringFormatter(pool);
            formatter.Format("{2} - Error {0}. File {1} not found.", 404, "index.html", time);

            Assert.Equal(time.ToString("G") + " - Error 404. File index.html not found.", formatter.ToString());
        }
 public void CompositeFormattingBasics()
 {
     var time = new DateTime(2016, 2, 9, 4, 1, 59, DateTimeKind.Utc);
     using (var formatter = new StringFormatter(pool))
     {
         formatter.Format("{2:G} - Error {0}. File {1} not found.", 404, "index.html", time);
         Assert.Equal("2/9/2016 4:01:59 AM - Error 404. File index.html not found.", formatter.ToString());
     }
 }
 public void CompositeFormattingBasics()
 {
     var time = DateTime.UtcNow;
     using (var formatter = new StringFormatter(pool))
     {
         formatter.Format("{2} - Error {0}. File {1} not found.", 404, "index.html", time);
         Assert.Equal(time.ToString("G") + " - Error 404. File index.html not found.", formatter.ToString());
     }
 }
Exemplo n.º 8
0
        public void Should_format_datetime_field()
        {
            var value = JsonValue.Create("2019-01-19T12:00:00Z");

            var field = Fields.DateTime(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("2019-01-19T12:00:00Z", formatted);
        }
Exemplo n.º 9
0
        public void Should_format_references_field_without_items()
        {
            var value = JsonValue.Array();

            var field = Fields.References(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("0 References", formatted);
        }
Exemplo n.º 10
0
        public void Should_format_number_field()
        {
            var value = JsonValue.Create(123);

            var field = Fields.Number(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("123", formatted);
        }
Exemplo n.º 11
0
        public void Should_format_json_field()
        {
            var value = JsonValue.Object();

            var field = Fields.Json(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("<Json />", formatted);
        }
Exemplo n.º 12
0
        public void Should_format_geolocation_field_with_invalid_type()
        {
            var value = JsonValue.Zero;

            var field = Fields.Geolocation(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Empty(formatted);
        }
Exemplo n.º 13
0
        public void Should_format_assets_field_with_multiple_items()
        {
            var value = JsonValue.Array(JsonValue.Object(), JsonValue.Object());

            var field = Fields.Assets(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("2 Assets", formatted);
        }
Exemplo n.º 14
0
        public void Should_format_geolocation_field_with_correct_data()
        {
            var value = JsonValue.Object().Add("latitude", 18.9).Add("longitude", 10.9);

            var field = Fields.Geolocation(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("18.9, 10.9", formatted);
        }
Exemplo n.º 15
0
        public void Should_format_assets_field_with_wrong_type()
        {
            var value = JsonValue.True;

            var field = Fields.Assets(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("0 Assets", formatted);
        }
Exemplo n.º 16
0
        public void Should_format_geolocation_field_with_missing_property()
        {
            var value = JsonValue.Object().Add("latitude", 18.9);

            var field = Fields.Geolocation(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Empty(formatted);
        }
Exemplo n.º 17
0
        public void Should_format_boolean_field_with_wrong_type()
        {
            var value = JsonValue.Zero;

            var field = Fields.Boolean(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("No", formatted);
        }
Exemplo n.º 18
0
        public void StringFormatter_CanFormatByteArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument((Byte)123);
            formatter.Format("this is a Byte value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Byte value: 123");
        }
Exemplo n.º 19
0
        public void StringFormatter_CanFormatInt32Argument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(12345);
            formatter.Format("this is an Int32 value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is an Int32 value: 12345");
        }
Exemplo n.º 20
0
        public void StringFormatter_CanFormatStringArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument("world");
            formatter.Format("hello {0}", buffer);

            TheResultingString(buffer).ShouldBe("hello world");
        }
Exemplo n.º 21
0
        public void StringFormatter_CanFormatDoubleArgumentWithDecimalsCommand()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(123.456789);
            formatter.Format("this is a Double value: {0:decimals:2}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Double value: 123.46");
        }
Exemplo n.º 22
0
        public void StringFormatter_CanFormatDoubleArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(123.45);
            formatter.Format("this is a Double value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Double value: 123.45000");
        }
Exemplo n.º 23
0
        public void StringFormatter_CanFormatCharArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument('Z');
            formatter.Format("this is a Char value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Char value: Z");
        }
Exemplo n.º 24
0
        public void StringFormatter_CanFormatByteArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument((Byte)123);
            formatter.Format("this is a Byte value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Byte value: 123");
        }
Exemplo n.º 25
0
        public void StringFormatter_CanFormatSingleArgumentWithDecimalsCommand()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(123.456789f);
            formatter.Format("this is a Single value: {0:decimals:2}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Single value: 123.46");
        }
Exemplo n.º 26
0
        public void StringFormatter_CanFormatSingleArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(123.45f);
            formatter.Format("this is a Single value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Single value: 123.45000");
        }
Exemplo n.º 27
0
        public void StringFormatter_CanFormatCharArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument('Z');
            formatter.Format("this is a Char value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Char value: Z");
        }
Exemplo n.º 28
0
        public void StringFormatter_CanFormatStringArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument("world");
            formatter.Format("hello {0}", buffer);

            TheResultingString(buffer).ShouldBe("hello world");
        }
Exemplo n.º 29
0
        public static void IsTrue(bool condition, string formatString, params object[] args)
        {
            if (condition)
            {
                return;
            }

            var message = StringFormatter.Format(formatString, args);

            throw new InvalidOperationException(message);
        }
Exemplo n.º 30
0
        public void CompositeFormattingFormatStrings()
        {
            var format = "Hello{0:x}{1:X}{2:G}";

            using (var formatter = new StringFormatter())
            {
                var expected = string.Format(CultureInfo.InvariantCulture, format, 10, 255, 3);

                formatter.Format(format, 10, 255, 3);
                Assert.Equal(expected, formatter.ToString());
            }
        }
Exemplo n.º 31
0
        public void CompositeFormattingEscaping()
        {
            var format = "}}a {0} b {0} c {{{0}}} d {{e}} {{";

            using (var formatter = new StringFormatter())
            {
                var expected = string.Format(CultureInfo.InvariantCulture, format, 1);

                formatter.Format(format, 1);
                Assert.Equal(expected, formatter.ToString());
            }
        }
Exemplo n.º 32
0
        public void Should_format_string_field_with_photo_editor()
        {
            var value = JsonValue.Create("hello");

            var field = Fields.String(1, "field", Partitioning.Invariant, new StringFieldProperties {
                Editor = StringFieldEditor.StockPhoto
            });

            var formatted = StringFormatter.Format(value, field);

            Assert.Equal("[Photo]", formatted);
        }
Exemplo n.º 33
0
        public void StringFormatter_CanFormatBooleanArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(true);
            formatter.AddArgument(false);
            formatter.Format("this is {0} and this is {1}", buffer);

            TheResultingString(buffer).ShouldBe("this is True and this is False");
        }
Exemplo n.º 34
0
        public void StringFormatter_CanFormatBooleanArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(true);
            formatter.AddArgument(false);
            formatter.Format("this is {0} and this is {1}", buffer);

            TheResultingString(buffer).ShouldBe("this is True and this is False");
        }
Exemplo n.º 35
0
        public void CompositeFormattingDateTimeOffset()
        {
            var format = "{0}#{1}";
            var value  = new DateTimeOffset(2016, 9, 23, 10, 53, 1, 1, TimeSpan.FromHours(1));

            using (var formatter = new StringFormatter())
            {
                var expected = string.Format(CultureInfo.InvariantCulture, format, value, value);

                formatter.Format(format, value, value);
                Assert.Equal(expected, formatter.ToString());
            }
        }
Exemplo n.º 36
0
        private void button4_Click(object sender, EventArgs e)
        {
            const string input = @"Hello, $(IF $loggedIn $username 'Unknown')!
You are $(IF $loggedIn $(IF $(ISMATCH $role '(admin)|(root)') 'a superuser' 'a normal user') 'not registered')!";

            var sf = new StringFormatter();

            sf.Variables.Add("loggedin", "false");
            sf.Variables.Add("username", "filmee24");
            sf.Variables.Add("role", "user");

            MessageBox.Show(sf.Format(input));
        }
Exemplo n.º 37
0
        public void CompositeFormattingGuid()
        {
            var format = "{0}#{1}";
            var value  = Guid.NewGuid();

            using (var formatter = new StringFormatter())
            {
                var expected = string.Format(CultureInfo.InvariantCulture, format, value, value);

                formatter.Format(format, value, value);
                Assert.Equal(expected, formatter.ToString());
            }
        }
Exemplo n.º 38
0
        private string FormatName(IEnrichedContentEntity content, string masterLanguage)
        {
            var sb = new StringBuilder();

            IJsonValue?GetValue(NamedContentData?data, RootField field)
            {
                if (data != null && data.TryGetValue(field.Name, out var fieldValue) && fieldValue != null)
                {
                    var isInvariant = field.Partitioning.Equals(Partitioning.Invariant);

                    if (isInvariant && fieldValue.TryGetValue("iv", out var value))
                    {
                        return(value);
                    }

                    if (!isInvariant && fieldValue.TryGetValue(masterLanguage, out value))
                    {
                        return(value);
                    }
                }

                return(null);
            }

            if (content.ReferenceFields != null)
            {
                foreach (var field in content.ReferenceFields)
                {
                    var value = GetValue(content.ReferenceData, field) ?? GetValue(content.Data, field);

                    var formatted = StringFormatter.Format(value, field);

                    if (!string.IsNullOrWhiteSpace(formatted))
                    {
                        if (sb.Length > 0)
                        {
                            sb.Append(", ");
                        }

                        sb.Append(formatted);
                    }
                }
            }

            if (sb.Length == 0)
            {
                return("Content");
            }

            return(sb.ToString());
        }
        /// <summary>
        ///     Run only the viewModel replacer.
        /// </summary>
        /// <param name="messageTemplate">template to parse</param>
        /// <param name="viewModel">viewModel used to fill the template.</param>
        /// <returns>HTML</returns>
        public string RunFormatterOnly(Template messageTemplate, object viewModel)
        {
            if (messageTemplate == null)
            {
                throw new ArgumentNullException("messageTemplate");
            }

            var sr   = new StreamReader(messageTemplate.Content);
            var text = sr.ReadToEnd();
            //return Smart.Format(text, viewModel);
            var formatter = new StringFormatter();

            return(formatter.Format(text, viewModel));
        }
Exemplo n.º 40
0
        public void FormatStringFormatter()
        {
            try
            {
                var f = new StringFormatter {
                    FormatStr = ""
                };
                f.Format("");
                throw new Exception("TEST FAILED.");
            }
            catch (ArgumentException se)
            {
                Assert.Equal("FormatString should not be null or empty", se.Message);
            }

            try
            {
                var f = new StringFormatter {
                    FormatStr = null
                };
                f.Format("");
                throw new Exception("TEST FAILED.");
            }
            catch (ArgumentException se)
            {
                Assert.Equal("FormatString should not be null or empty", se.Message);
            }

            try
            {
                var f = new StringFormatter {
                    FormatStr = "     "
                };
                f.Format("");
                throw new Exception("TEST FAILED.");
            }
            catch (ArgumentException se)
            {
                Assert.Equal("FormatString should not be null or empty", se.Message);
            }

            var formatter1 = new StringFormatter {
                FormatStr = "http://{0}"
            };

            Assert.Equal("http://a", formatter1.Format("a"));

            //StringFormater formatter2 = new StringFormater { Format = "http://{0}/{1}" };
            //Assert.Equal("http://a/b", formatter2.Formate(new[] { "a", "b" }));
        }
Exemplo n.º 41
0
        public void CompositeFormattingBasics()
        {
            var format   = "{2:G} - Error {0}. File {1} not found.";
            var time     = new DateTime(2016, 2, 9, 4, 1, 59, DateTimeKind.Utc);
            var code     = 404;
            var fileName = "index.html";

            using (var formatter = new StringFormatter())
            {
                var expected = string.Format(CultureInfo.InvariantCulture, format, code, fileName, time);

                formatter.Format(format, code, fileName, time);
                Assert.Equal(expected, formatter.ToString());
            }
        }
        /// <summary>
        ///     Run all formatters (replace text tokens, run markdown and finalize with a syntax highlighter)
        /// </summary>
        /// <param name="messageTemplate">template to parse</param>
        /// <param name="viewModel">viewModel used to fill the template.</param>
        /// <returns>HTML</returns>
        public string RunAll(Template messageTemplate, object viewModel)
        {
            if (messageTemplate == null)
            {
                throw new ArgumentNullException("messageTemplate");
            }

            var sr        = new StreamReader(messageTemplate.Content);
            var text      = sr.ReadToEnd();
            var formatter = new StringFormatter();

            text = formatter.Format(text, viewModel);
            text = Markdown(text);
            return(ColorizeCode(text));
        }
        public void TestSingleNoParameters()
        {
            var stringFormatter = new StringFormatter();
            var str             = stringFormatter.Format(
                "Up is %UP",
                (name, parameters) =>
            {
                if (name == "UP")
                {
                    Assert.IsNull(parameters);
                    return("down");
                }
                throw new ArgumentException(string.Format("The replacement parameter '{0}' is not supported", name));
            });

            Assert.AreEqual("Up is down", str);
        }
Exemplo n.º 44
0
        public static string __repr__(CodeContext/*!*/ context, double self) {
            if (Double.IsNaN(self)) {
                return "nan";
            }

            // first format using Python's specific formatting rules...
            StringFormatter sf = new StringFormatter(context, "%.17g", self);
            sf._TrailingZeroAfterWholeFloat = true;
            string res = sf.Format();
            if (LiteralParser.ParseFloat(res) == self) {
                return res;
            }

            // if it's not round trippable though use .NET's round-trip format
            return self.ToString("R", CultureInfo.InvariantCulture);
        }
Exemplo n.º 45
0
 public static string __str__(CodeContext/*!*/ context, double x) {
     StringFormatter sf = new StringFormatter(context, "%.12g", x);
     sf._TrailingZeroAfterWholeFloat = true;
     return sf.Format();
 }
Exemplo n.º 46
0
 public static string __str__(CodeContext/*!*/ context, float x) {
     // Python does not natively support System.Single. However, we try to provide
     // formatting consistent with System.Double.
     StringFormatter sf = new StringFormatter(context, "%.6g", x);
     sf._TrailingZeroAfterWholeFloat = true;
     return sf.Format();
 }
            public void NoPrefixSuffix()
            {
                StringFormatter stringFormatter = new StringFormatter(string.Empty, string.Empty, null);
                Application application = new Application
                                              {
                                                  OrganisationId = "MyOrg!",
                                                  ApplicationId = "4kdlsjfdlsfjldsads",
                                                  Created = new DateTime(1977, 5, 25, 0, 0, 0, DateTimeKind.Utc)
                                              };
                application.ApplicationData.Add("key1", "someval");
                application.ApplicationData.Add("key2", 456);
                application.ApplicationData.Add("key3", false);

                string replacedAppValue1 = stringFormatter.Format(@"key1", application, new ControlList());
                Assert.AreEqual("someval", replacedAppValue1);

                string replacedAppValue2 = stringFormatter.Format(@"key3", application, new ControlList());
                Assert.AreEqual("False", replacedAppValue2);
            }
Exemplo n.º 48
0
 public void CompositeFormattingEscapingMissingStartBracket()
 {
     var formatter = new StringFormatter(pool);
     Assert.Throws<Exception>(() => formatter.Format("{0}}", 1));
 }
Exemplo n.º 49
0
        public void Localization_LocalizedTextFormatting()
        {
            LoadTestLocalizationDatabaseFromXml();

            UsingCulture("fr-FR", () =>
            {
                var formatter = new StringFormatter();
                var buffer = new StringBuilder();

                formatter.Reset();
                formatter.AddArgument(Localization.Get("SWORD").GetPluralVariant(1));
                formatter.AddArgument(Localization.Get("GLOWING"));
                formatter.Format("test: {?:match:0:def_art}{0} {1:match:0:adj}", buffer);

                TheResultingString(buffer)
                    .ShouldBe("test: l'epée rougeoyante");

                formatter.Reset();
                formatter.AddArgument(Localization.Get("SWORD").GetPluralVariant(2));
                formatter.AddArgument(Localization.Get("GLOWING"));
                formatter.Format("test: {?:match:0:def_art}{0} {1:match:0:adj}", buffer);

                TheResultingString(buffer)
                    .ShouldBe("test: les epées rougeoyantes");
            });
        }