public void Test_BracesAreEscaped()
        {
            var values1 = new object[] { "World" };
            var values2 = new { Name = "World" };

            string s = StringTemplate.Format("Hello {{Name}} !", values2);

            Assert.Equal("Hello {Name} !", s);

            var s1 = String.Format("Hello {{{0}}} !", values1);
            var s2 = StringTemplate.Format("Hello {{{Name}}} !", values2);

            Assert.Equal(s1, s2);

            s1 = String.Format("Hello {{{0} !", values1);
            s2 = StringTemplate.Format("Hello {{{Name} !", values2);
            Assert.Equal(s1, s2);

            s1 = String.Format("Hello {0}}} !", values1);
            s2 = StringTemplate.Format("Hello {Name}}} !", values2);
            Assert.Equal(s1, s2);

            Assert.Throws <FormatException>(
                () => s2 = StringTemplate.Format("Hello {{{Name}} !", values2));
        }
Example #2
0
        private void mnuPasteSpecial_Click(object sender, EventArgs e)
        {
            StringTemplate stringtemplate = new StringTemplate();
            string         result         = stringtemplate.Format(Clipboard.GetText(), _textboxHelper.SelectedText);

            _textboxHelper.SelectedText = result;
        }
        public void Check_Format()
        {
            string   name = "FooBar";
            DateTime date = DateTime.Now;

            string format         = "Bonjour {0}. Nous sommes le {1:D}, et il est {1:T}.";
            string templateFormat = "Bonjour {Name}. Nous sommes le {Date:D}, et il est {Date:T}.";

            var values1 = new Dictionary <string, object>
            {
                { "Name", name },
                { "Date", date }
            };

            var values2 = new
            {
                Name = name,
                Date = date
            };

            string expected = String.Format(format, name, date);
            string result1  = StringTemplate.Format(templateFormat, values1);
            string result2  = StringTemplate.Format(templateFormat, values2);

            Assert.Equal(expected, result1);
            Assert.Equal(expected, result2);
        }
Example #4
0
        public override void Parse(DecodedMetar decodedMetar)
        {
            var visibility = new StringBuilder();

            if (decodedMetar.Cavok)
            {
                visibility.Append($"{strings.VisibilityCAVOK}");
            }
            else if (decodedMetar.Visibility?.PrevailingVisibility != null)
            {
                if (Math.Round(decodedMetar.Visibility.PrevailingVisibility.GetConvertedValue(Value.Unit.Meter)) == 9999)
                {
                    visibility.Append($"{strings.Visibility10KmOrMore}");
                }
                else
                {
                    visibility.Append(
                        StringTemplate.Format(
                            strings.PrevailingVisibility,
                            new
                    {
                        prevailingVisibility = decodedMetar.Visibility.PrevailingVisibility.GetConvertedValue(Value.Unit.Meter)
                    }, false));
                }
            }
            Label = strings.VisibilityLabel; Message = visibility.ToString();
        }
Example #5
0
        /// <inheritdoc/>
        public override void Parse(DecodedMetar decodedMetar)
        {
            var clouds = new StringBuilder();
            var subWeatherMessageSb = new StringBuilder();

            if (decodedMetar.Clouds?.Count > 0)
            {
                clouds.Append(string.Join(", ", decodedMetar.Clouds.Select(cloud =>
                {
                    subWeatherMessageSb.Clear();

                    var cloudAmount = CloudsAmount.ContainsKey(cloud.Amount.ToString()) ? CloudsAmount[cloud.Amount.ToString()] : string.Empty;
                    var cloudType   = CloudsType.ContainsKey(cloud.Type.ToString()) ? CloudsType[cloud.Type.ToString()] : string.Empty;
                    subWeatherMessageSb.Append($"{cloudAmount}{(cloud.Type != CloudLayer.CloudType.NULL ? string.Concat(" ", cloudType) : string.Empty)} ");

                    if (cloud.BaseHeight != null)
                    {
                        subWeatherMessageSb.Append(
                            StringTemplate.Format(
                                strings.CloudsDetails,
                                new
                        {
                            feet   = Math.Round(cloud.BaseHeight.GetConvertedValue(Value.Unit.Feet)),
                            meters = Math.Round(cloud.BaseHeight.GetConvertedValue(Value.Unit.Meter))
                        }, false));
                    }

                    return(subWeatherMessageSb);
                })));
            }
            Label   = strings.CloudsLabel;
            Message = clouds.ToString();
        }
Example #6
0
        public void StringTemplateValueConverter_Caches_And_Reuses_Converters_And_Behaves_Properly_When_Caches_Are_Cleared()
        {
            StringTemplate.ClearCache(); // Make sure we don't use instances from other tests...

            var values = new ValuesWithMiscConverters {
                AttributedWithStateMutatorConverter = 0
            };
            var otherValues = new OtherValuesWithMiscConverters {
                AttributedWithStateMutatorConverter2 = 0
            };

            string actual1 = StringTemplate.Format("{AttributedWithStateMutatorConverter}", values);
            string actual2 = StringTemplate.Format("{AttributedWithStateMutatorConverter}", values);

            // Clear the cached getters and converters.
            // This test will fail if the getters cache is cleared, but not the converters cache.
            StringTemplate.ClearCache();

            string actual3 = StringTemplate.Format("{AttributedWithStateMutatorConverter}", values);
            string actual4 = StringTemplate.Format("{AttributedWithStateMutatorConverter2}", otherValues);

            // The converter instance should be reused, so its state is preserved and incremented between calls
            Assert.Equal("1", actual1);
            Assert.Equal("2", actual2);
            Assert.Equal("1", actual3);
            Assert.Equal("2", actual4); // tests caching across types and members
        }
Example #7
0
        public void Should_Throw_When_Attribute_Has_Null_Converter_Type()
        {
            var values = new ValuesWithMiscConverters {
                AttributedWithNullConverterType = 0
            };

            Assert.Throws <InvalidOperationException>(() => StringTemplate.Format("{AttributedWithNullConverterType}", values));
        }
Example #8
0
        public void Should_Throw_When_Converter_CanConvert_Is_False()
        {
            var values = new ValuesWithMiscConverters {
                AttributedWithConverterHavingCanConvertAlwaysFalse = 0
            };

            Assert.Throws <NotSupportedException>(() => StringTemplate.Format("{AttributedWithConverterHavingCanConvertAlwaysFalse}", values));
        }
        public void DateFormatTest()
        {
            var template = new StringTemplate("Test date: {date:d}");
            var dt       = new DateTime(2000, 1, 1, 12, 0, 0);
            var actual   = template.Format(new { date = dt });

            Assert.AreEqual(string.Format("Test date: {0:d}", dt), actual);
        }
        public void NullDelegateException()
        {
            var template = "x";

            var actual = StringTemplate.Format(template, (StringTemplate.GetValue)null);

            Assert.Fail("Should have thrown exception.");
        }
        public void NullArgumentsException()
        {
            var template = "x";

            var actual = StringTemplate.Format(template, (IDictionary <string, object>)null);

            Assert.Fail("Should have thrown exception.");
        }
        public void NullTemplateException()
        {
            var arguments = new Dictionary <string, object>();

            var actual = StringTemplate.Format(null, arguments);

            Assert.Fail("Should have thrown exception.");
        }
        private string GetCurrentFilePath(TraceEventCache eventCache)
        {
            var result = StringTemplate.Format(CultureInfo.CurrentCulture, FilePathTemplate,
                                               delegate(string name, out object value)
            {
                switch (name.ToUpperInvariant())
                {
                case "ACTIVITYID":
                    value = Trace.CorrelationManager.ActivityId;
                    break;

                case "APPDATA":
                    value = traceFormatter.HttpTraceContext.AppDataPath;
                    break;

                case "APPDOMAIN":
                    value = AppDomain.CurrentDomain.FriendlyName;
                    break;

                case "APPLICATIONNAME":
                    value = traceFormatter.FormatApplicationName();
                    break;

                case "DATETIME":
                case "UTCDATETIME":
                    value = TraceFormatter.FormatUniversalTime(eventCache);
                    break;

                case "LOCALDATETIME":
                    value = TraceFormatter.FormatLocalTime(eventCache);
                    break;

                case "MACHINENAME":
                    value = Environment.MachineName;
                    break;

                case "PROCESSID":
                    value = traceFormatter.FormatProcessId(eventCache);
                    break;

                case "PROCESSNAME":
                    value = traceFormatter.FormatProcessName();
                    break;

                case "USER":
                    value = Environment.UserDomainName + "-" + Environment.UserName;
                    break;

                default:
                    value = "{" + name + "}";
                    return(true);
                }
                return(true);
            });

            return(result);
        }
 public IList <string> GetKeys()
 {
     if (_keys == null)
     {
         _keys = new List <string>();
         var dummy = StringTemplate.Format(_messageTemplate, GetValue);
     }
     return(_keys);
 }
        public void MissingFormatStartException()
        {
            var template  = "}";
            var arguments = new Dictionary <string, object>();

            var actual = StringTemplate.Format(template, arguments);

            Assert.Fail("Should have thrown exception.");
        }
Example #16
0
        public void StringTemplateValueConverter_Can_Convert_Value_Type()
        {
            var values = new BasicTestValues {
                ValueTypeProperty = new DateTime(ticks: 42)
            };

            string actual = StringTemplate.Format("{ValueTypeProperty}", values);

            Assert.Equal("42", actual);
        }
Example #17
0
        public void Generic_Converter_CanConvert_Allows_Derived_Type()
        {
            var values = new ValuesWithMiscConverters {
                StringArrayWithReadOnlyCollectionConverter = StringCollectionValues
            };

            string actual = StringTemplate.Format("{StringArrayWithReadOnlyCollectionConverter}", values);

            Assert.Equal(ExpectedStringCollectionConcatenation, actual);
        }
Example #18
0
        public void StringTemplateValueConverter_Can_Convert_Field()
        {
            var values = new BasicTestValues {
                StringCollectionField = StringCollectionValues
            };

            string actual = StringTemplate.Format("{StringCollectionField}", values);

            Assert.Equal(ExpectedStringCollectionConcatenation, actual);
        }
Example #19
0
        public void Generic_Converter_Allows_Null_Values(object input, bool expectedResult)
        {
            var values = new ValuesWithMiscConverters {
                AttributedWithNullToBoolConverter = input
            };

            string actual = StringTemplate.Format("{AttributedWithNullToBoolConverter}", values);

            Assert.Equal(expectedResult, bool.Parse(actual));
        }
Example #20
0
        public void Test_WithFields()
        {
            int    x    = 42;
            string text = "Hello world";

            string expected = $"{text} {x}";
            string actual   = StringTemplate.Format("{text} {x}", new FieldValues {
                x = x, text = text
            });

            Assert.Equal(expected, actual);
        }
        public void RepeatFormat()
        {
            var template  = "x{a}{a}y";
            var arguments = new Dictionary <string, object>()
            {
                { "a", "A" }
            };

            var actual = StringTemplate.Format(template, arguments);

            Assert.AreEqual("xAAy", actual);
        }
        public void MultipleFormat()
        {
            var template  = "x{a}{b}y";
            var arguments = new Dictionary <string, object>()
            {
                { "a", "A" }, { "b", "B" }
            };

            var actual = StringTemplate.Format(template, arguments);

            Assert.AreEqual("xABy", actual);
        }
        public void SpecificFormatProvider()
        {
            var template  = "{a:f1}";
            var arguments = new Dictionary <string, object>()
            {
                { "a", 1.0 }
            };

            var actual = StringTemplate.Format(CultureInfo.CreateSpecificCulture("de-DE"), template, arguments);

            Assert.AreEqual("1,0", actual);
        }
        public void EscapedCharacters()
        {
            var template  = "{{{a}}}";
            var arguments = new Dictionary <string, object>()
            {
                { "a", "A" }
            };

            var actual = StringTemplate.Format(template, arguments);

            Assert.AreEqual("{A}", actual);
        }
Example #25
0
        public void StringTemplateValueConverter_Works_With_Alignment_In_PlaceHolder()
        {
            var values = new ValuesForFormatProvider
            {
                DateTimeConvertedToTicks   = new DateTime(42),
                DateTimeConvertedToDayName = DateTime.Today
            };

            string expected = $"{values.DateTimeConvertedToDayName.DayOfWeek,-30}: {values.DateTimeConvertedToTicks.Ticks,30}";
            string actual   = StringTemplate.Format("{DateTimeConvertedToDayName,-30}: {DateTimeConvertedToTicks,30}", values);

            Assert.Equal(expected, actual);
        }
Example #26
0
        public void Format_Should_Accept_Alignment_In_PlaceHolder()
        {
            var x = new
            {
                Name  = "FooBar",
                Value = 42
            };

            string expected = $"{x.Name,-10}: {x.Value,10}";
            string actual   = StringTemplate.Format("{Name,-10}: {Value,10}", x);

            Assert.Equal(expected, actual);
        }
Example #27
0
        public void Test_WithFormatProvider()
        {
            var date = DateTime.Today;

            var cultures = new[] { CultureInfo.InvariantCulture, null, new CultureInfo("fr-FR") };

            foreach (var culture in cultures)
            {
                string expected = date.ToString("D", culture);
                string actual   = StringTemplate.Format("{date:D}", new { date }, true, culture);
                Assert.Equal(expected, actual);
            }
        }
Example #28
0
        public void Test_HiddenMembers()
        {
            DerivedValues values = new DerivedValues {
                X = "hello", Y = 42
            };
            BaseValues bValues = values;

            bValues.X = 42;

            string expected = $"{values.X} {values.Y}";
            string actual   = StringTemplate.Format("{X} {Y}", values);

            Assert.Equal(expected, actual);
        }
        public override void Parse(DecodedMetar decodedMetar)
        {
            var wind = new StringBuilder();

            if (decodedMetar.SurfaceWind != null)
            {
                if (decodedMetar.SurfaceWind.MeanDirection != null)
                {
                    wind.Append(StringTemplate.Format(strings.WindDetails,
                                                      new
                    {
                        meanDirectionDegrees  = decodedMetar.SurfaceWind.MeanDirection.ActualValue,
                        meanDirectionCardinal = decodedMetar.SurfaceWind.MeanDirection.ActualValue.ConvertDegreesToCardinal(false).ToLowerInvariant(),
                        speedKnot             = Math.Round(decodedMetar.SurfaceWind.MeanSpeed.GetConvertedValue(Value.Unit.Knot)),
                    }));
                }

                // SurfaceWind.SpeedVariations property contains gust wind speed
                if (decodedMetar.SurfaceWind.SpeedVariations != null)
                {
                    if (decodedMetar.SurfaceWind.MeanDirection != null)
                    {
                        wind.Append(", ");
                        wind.Append($"{strings.WindWith} ");
                    }
                    wind.Append(StringTemplate.Format(strings.WindGusts,
                                                      new { windGustsKnot = Math.Round(decodedMetar.SurfaceWind.SpeedVariations.GetConvertedValue(Value.Unit.Knot)) },
                                                      false));
                }

                // SurfaceWind.VariableDirection property contains variable wind direction flag information (VRB)
                if (decodedMetar.SurfaceWind.VariableDirection)
                {
                    wind.Append($" ({strings.WindVariableDirection})");
                }
                else if (decodedMetar.SurfaceWind.DirectionVariations?.Length > 1 && decodedMetar.SurfaceWind.DirectionVariations[0] != null && decodedMetar.SurfaceWind.DirectionVariations[1] != null)
                {
                    wind.Append(StringTemplate.Format(strings.WindDirectionVariations,
                                                      new
                    {
                        windDirectionVariationMinDegrees  = decodedMetar.SurfaceWind.DirectionVariations[0].ActualValue,
                        windDirectionVariationMinCardinal = decodedMetar.SurfaceWind.DirectionVariations[0].ActualValue.ConvertDegreesToCardinal(false).ToLowerInvariant(),
                        windDirectionVariationMaxDegrees  = decodedMetar.SurfaceWind.DirectionVariations[1].ActualValue,
                        windDirectionVariationMaxCardinal = decodedMetar.SurfaceWind.DirectionVariations[1].ActualValue.ConvertDegreesToCardinal(false).ToLowerInvariant(),
                    }, false));
                }
            }
            Label   = strings.WindLabel;
            Message = wind.ToString();
        }
Example #30
0
        public void StringTemplateValueConverter_Works_With_Enum()
        {
            foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
            {
                var values = new EnumValues {
                    Day = day
                };

                string expected = EnumValues.GetCustomDayString(day);
                string actual   = StringTemplate.Format("{Day}", values);

                Assert.Equal(expected, actual);
            }
        }