Dynamic expression parsing in localized environment

dynamic-linq lambda linq-expressions localization

Question

So I'm attempting to use System.Linq.Dynamic to parse a straightforward arithmetic dynamic expression. This works well when run in an English environment with the English-US CurrentCulture (and the decimal separator is a plain "." dot). ParseLambda fails when attempting to execute the code in a non-English environment (for instance, Windows 7x64 in Bulgarian, where the decimal separator is a "," comma).

In the Bulgarian environment, ParseLambda fails with the PraseExpression error message "Invalid real literal '1.0'" if I enter "1.0" in my expression (but does not fail in the English environment). ParseLambda fails with a ParseExpression stating "Syntax error" if I attempt to include "1,0" in my expression (this one fails in both environments).

Anyone has a solution for this?
Or have I overlooked something?
Or is it possible for me to modify the parsed expression's culture?
My application must function properly in both settings.
My code is running on.NET v4.0, and I've added a reference to the project for System.Linq.Dynamic.dll (1.0.0.0).
Here is the key:

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

Before executing that code, you may change the current culture. For instance, put the following line before your code, which only works with a decimal separator that is English-style:

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