Dynamic expression parsing in localized environment

dynamic-linq lambda linq-expressions localization

Question

So I'm trying to parse a simple arithmetic dynamic expression using System.Linq.Dynamic. This runs fine when executed in an English environment where the CurrentCulture is English-US (and the decimal separator is a plain "." dot). Trying to run the code in a non English environment (e.g. Windows7x64 in Bulgarian, where the decimal separator is a "," comma), ParseLambda fails.

If I put "1.0" in my expression, ParseLambda fails in the Bulgarian environment with a PraseExpression, saying "Invalid real literal '1.0'" (but does not fail in the English environment). If I try to put "1,0" in my expression, ParseLambda fails with a ParseExpression saying "Syntax error" (this one fails in both environments).

Anyone knows a way around this?
Or am I missing something?
Or can I somehow set the culture of the parsed expression?
I need my app to run well on both environments..
My code is running on .NET v4.0 and I have System.Linq.Dynamic.dll (1.0.0.0) added as reference to the project.
Here's the code:

using System;
using System.Linq;
using System.Linq.Dynamic;

namespace DynamicExpressionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //FAIL: ParseException: Invalid real literal '1.0' (fails only in non-English environment)
            var expression1 = DynamicExpression.ParseLambda(
                new System.Linq.Expressions.ParameterExpression[] { },
                typeof(double), 
                "1.0 + 1.0");
            var result1 = expression1.Compile().DynamicInvoke();
            double resultD1 = System.Convert.ToDouble(result1);
            Console.WriteLine(resultD1);

            //FAIL: ParseException: Syntax error (fails both in English and non-English environments)
            var expression2 = DynamicExpression.ParseLambda(
                new System.Linq.Expressions.ParameterExpression[] { }, 
                typeof(double), 
                "1,0 + 1,0");
            var result2 = expression2.Compile().DynamicInvoke();
            double resultD2 = System.Convert.ToDouble(result2);
            Console.WriteLine(resultD2);
        }
    }
}

Thanks!

1
0
12/6/2012 12:46:39 PM

Accepted Answer

You can set the current culture before running that code. E.g. add this line before your code that only works with an English-style decimal separator:

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
1
12/6/2012 4:07:23 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow