StockQuote sample System.FormatException

Aug 4, 2013 at 5:36 AM
Hello,

If you compile and run the stock quote example in certain countries (such as Sweden) you may see System.FormatException when attempting to retrieve (a single or all) stock quotes.
This is because the actual stock quotes are retrieved in US format, where decimal points are points ('.'). In Sweden, decimal points are commas (',').

A simple fix is to set the culture in WebApiConfig. This code was copied from intninety and should work for all .NET versions. (The example targets .NET 4; in 4.5 this can be achieved without having to resort to reflection.)

Cheers,

/Uffe
        public static void SetDefaultCulture(CultureInfo culture)
        {
            Type type = typeof(CultureInfo);
            try
            {
                type.InvokeMember("s_userDefaultCulture",
                                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                                    null,
                                    culture,
                                    new object[] { culture });
                type.InvokeMember("s_userDefaultUICulture",
                                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                                    null,
                                    culture,
                                    new object[] { culture });
            }
            catch { }
            try
            {
                type.InvokeMember("m_userDefaultCulture",
                                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                                    null,
                                    culture,
                                    new object[] { culture });
                type.InvokeMember("m_userDefaultUICulture",
                                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                                    null,
                                    culture,
                                    new object[] { culture });
            }
            catch { }
        }

        public static void Register(HttpConfiguration config)
        {
            SetDefaultCulture(new CultureInfo("en-US"));
            config.Routes.MapHttpRoute(
From the MapHttpRoute call and on, the code is unchanged.