Beispiel #1
0
 /// <summary>
 /// This is a helper method that assists with recursively building
 /// a string of the current collection and all nested collections, plus the ability
 /// to specify culture for formatting of nested numbers and dates. Note that
 /// this overload will change the culture of the current thread.
 /// </summary>
 public static string ToString(object obj, CultureInfo culture)
 {
     using (var context = new CultureContext(culture))
     {
         return(ToString(obj));
     }
 }
Beispiel #2
0
 /// <summary>
 /// This is the same implementation of ToString from Java's AbstractCollection
 /// (the default implementation for all sets and lists), plus the ability
 /// to specify culture for formatting of nested numbers and dates. Note that
 /// this overload will change the culture of the current thread.
 /// </summary>
 public static string ToString <T>(ICollection <T> collection, CultureInfo culture)
 {
     using (var context = new CultureContext(culture))
     {
         return(ToString(collection));
     }
 }
Beispiel #3
0
        public void TestCurrentCultureChange()
        {
            var map = new Dictionary <string, IDictionary <int, double> >
            {
                { "first", new Dictionary <int, double> {
                      { 1, 1.23 }, { 2, 2.23 }, { 3, 3.23 }
                  } },
                { "second", new Dictionary <int, double> {
                      { 4, 1.24 }, { 5, 2.24 }, { 6, 3.24 }
                  } },
                { "third", new Dictionary <int, double> {
                      { 7, 1.25 }, { 8, 2.25 }, { 9, 3.25 }
                  } },
            };
            var mapExpectedPortuguese = "{first={1=1,23, 2=2,23, 3=3,23}, second={4=1,24, 5=2,24, 6=3,24}, third={7=1,25, 8=2,25, 9=3,25}}";
            var mapExpectedUSEnglish  = "{first={1=1.23, 2=2.23, 3=3.23}, second={4=1.24, 5=2.24, 6=3.24}, third={7=1.25, 8=2.25, 9=3.25}}";

            var formatter = StringFormatter.CurrentCulture;

            using (var context = new CultureContext("en-US"))
            {
                Assert.AreEqual(mapExpectedUSEnglish, string.Format(formatter, "{0}", map));
            }
            using (var context = new CultureContext("pt"))
            {
                Assert.AreEqual(mapExpectedPortuguese, string.Format(formatter, "{0}", map));
            }
        }
Beispiel #4
0
        private CultureExpression ExtractLanguageFromHeader(HttpContext context, CultureContext cultureContext)
        {
            CultureOptions cultureOptions = cultureContext.Options;
            StringValues   languageValues;

            if (!context.Request.Headers.TryGetValue("Accept-Language", out languageValues))
            {
                return(null);
            }
            List <string> languageCodes = new List <string>();

            foreach (string lan in languageValues)
            {
                languageCodes.AddRange(lan.Split(';').Select(x => x.ToLower()));
            }
            CultureExpression exp;

            foreach (string lan in languageCodes)
            {
                if (CultureExpression.TryParse(lan, out exp) && cultureOptions.IsLanguageSupported(exp))
                {
                    return(exp);
                }
            }
            return(null);
        }
Beispiel #5
0
        public Task Invoke(HttpContext context, CultureContext cultureContext)
        {
            string            urlSpecifier;
            CultureExpression cultureExpression = ExtractLanguageFromUrl(context, cultureContext, out urlSpecifier);

            cultureContext.UrlCultureSpecifier = urlSpecifier;
            if (cultureExpression == null)
            {
                cultureExpression = ExtractLanguageFromHeader(context, cultureContext);
            }
            if (cultureExpression == null)
            {
                cultureExpression = cultureContext.Options.DefaultLanguage;
            }
            cultureContext.Action  = context.Request.Path.Value;
            cultureContext.Culture = cultureExpression;
            if (urlSpecifier.Length <= 0)
            {
                return(next(context));
            }
            else
            {
                return(next(context).ContinueWith(tsk =>
                {
                    if (context.Response.Headers.ContainsKey("Location"))
                    {
                        context.Response.Headers["Location"] = urlSpecifier + context.Response.Headers["Location"];
                    }
                }));
            }
        }
Beispiel #6
0
        public void Test_RegionMatches_String_Int32_String_Int32_Int32_StringComparison()
        {
            // Test for method boolean java.lang.String.regionMatches(int,
            // java.lang.String, int, int)
            String bogusString = "xxcedkedkleiorem lvvwr e''' 3r3r 23r";

            assertTrue("identical regions failed comparison", hw1.RegionMatches(2,
                                                                                hw2, 2, 5, StringComparison.Ordinal));
            assertTrue("Different regions returned true", !hw1.RegionMatches(2,
                                                                             bogusString, 2, 5, StringComparison.Ordinal));

            var input = "iiiiiiiiiiiıIiii";
            var test  = "İII"; // Turkish capital dotted I test.

            using (var context = new CultureContext("tr"))
            {
                assertTrue("Turkish captial I test failed using StringComparison.CurrentCultureIgnoreCase in tr culture",
                           input.RegionMatches(10, test, 0, 3, StringComparison.CurrentCultureIgnoreCase));
                assertFalse("Turkish captial I test failed using StringComparison.Ordinal in tr culture",
                            input.RegionMatches(10, test, 0, 3, StringComparison.Ordinal));
            }
            using (var context = new CultureContext("en"))
            {
                if (!input.RegionMatches(10, test, 0, 3, StringComparison.CurrentCultureIgnoreCase))
                {
                    assertFalse("Turkish captial I test failed using StringComparison.CurrentCultureIgnoreCase in en culture",
                                input.RegionMatches(10, test, 0, 3, StringComparison.CurrentCultureIgnoreCase));
                    assertFalse("Turkish captial I test failed using StringComparison.Ordinal in en culture",
                                input.RegionMatches(10, test, 0, 3, StringComparison.Ordinal));
                }
            }
        }
Beispiel #7
0
 /// <summary>
 /// This is the same implementation of ToString from Java's AbstractMap
 /// (the default implementation for all dictionaries), plus the ability
 /// to specify culture for formatting of nested numbers and dates. Note that
 /// this overload will change the culture of the current thread.
 /// </summary>
 public static string ToString <TKey, TValue>(IDictionary <TKey, TValue> dictionary, CultureInfo culture)
 {
     using (var context = new CultureContext(culture))
     {
         return(ToString(dictionary));
     }
 }
Beispiel #8
0
 public void TestToStringInvariant(Field field, string expected)
 {
     using (var cultureContext = new CultureContext(CultureInfo.InvariantCulture))
     {
         string actual = field.ToString();
         Assert.AreEqual(expected, actual);
     }
 }
Beispiel #9
0
 public void TestToStringFrance(Field field, string expected)
 {
     using (var cultureContext = new CultureContext(new CultureInfo("fr-FR")))
     {
         string actual = field.ToString();
         Assert.AreEqual(expected, actual);
     }
 }
 public ReservationController(ReservationDbContext dbcontext, NPOLJwtTokenService tokenservice, SMSService smsService, CultureContext cultureContext,
                              ICaptchaProtectionProvider captchaProtectionProvider, IHumanReadableIntegerProvider humanReadableIntegerProvider) : base(cultureContext)
 {
     db = dbcontext;
     this.tokenservice                 = tokenservice;
     this.smsService                   = smsService;
     this.cultureContext               = cultureContext;
     this.captchaProtectionProvider    = captchaProtectionProvider;
     this.humanReadableIntegerProvider = humanReadableIntegerProvider;
 }
Beispiel #11
0
        public void TestTurkish()
        {
            using var context = new CultureContext("tr-TR");
            String text = "<html><HEAD><TITLE>ııı</TITLE></head><body>" +
                          "<IMG SRC=\"../images/head.jpg\" WIDTH=570 HEIGHT=47 BORDER=0 ALT=\"ş\">" +
                          "<a title=\"(ııı)\"></body></html>";
            Parser parser = new Parser(new StringReader(text));

            assertEquals("ııı", parser.Title);
            assertEquals("[ş]", parser.Body);
        }
 public void Test_GetPropertyAsInt32_String_Ambient_en_US()
 {
     using (var context = new CultureContext("en-US"))
     {
         assertEquals(int.MaxValue, tProps.GetPropertyAsInt32("int32.prop.max"));
         assertEquals(int.MinValue, tProps.GetPropertyAsInt32("int32.prop.min"));
         assertEquals(-1, tProps.GetPropertyAsInt32("int32.prop.negone"));
         assertEquals(0, tProps.GetPropertyAsInt32("int32.prop.bogus"));
         assertEquals(0, tProps.GetPropertyAsInt32("int32.prop.unparsable"));
     }
 }
 public void Test_appendD()
 {
     using (var context = new CultureContext(CultureInfo.InvariantCulture))
     {
         // Test for method java.lang.StringBuffer
         // java.lang.StringBuffer.Append(double)
         StringBuffer sb = new StringBuffer();
         sb.Append(double.MaxValue);
         assertEquals("Buffer is invalid length after append", double.MaxValue.ToString().Length, sb.Length); // J2N: Exact format of string is dependent upon framework implementation, so we are testing whether the append matches the re-generated string
         assertEquals("Buffer contains invalid characters",
                      /*"1.7976931348623157E+308"*/ double.MaxValue.ToString(), sb.ToString());;
     }
 }
        public void Test_GetPropertyAsInt32_String_Int32_Ambient_Neg_Q()
        {
            var newCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone();

            newCulture.NumberFormat.NegativeSign = "Q";

            using (var context = new CultureContext(newCulture))
            {
                assertEquals(int.MaxValue, tProps.GetPropertyAsInt32("int32.prop.max", 5));
                assertEquals(5, tProps.GetPropertyAsInt32("int32.prop.min", 5));
                assertEquals(5, tProps.GetPropertyAsInt32("int32.prop.negone", 5));
                assertEquals(5, tProps.GetPropertyAsInt32("int32.prop.bogus", 5));
                assertEquals(-456, tProps.GetPropertyAsInt32("int32.prop.unparsable", 5));
            }
        }
Beispiel #15
0
        private CultureExpression ExtractLanguageFromUrl(HttpContext context, CultureContext cultureContext, out string urlSpecifier)
        {
            CultureOptions cultureOptions = cultureContext.Options;

            string path       = context.Request.Path.Value;
            int    slashIndex = 1;
            int    pathLength = path.Length;

            for (; slashIndex < pathLength; slashIndex++)
            {
                if (path[slashIndex] == '/')
                {
                    break;
                }
            }
            string lang = path.Substring(1, slashIndex - 1).ToLower();

            if (!CultureExpression.TryParse(lang, out CultureExpression cultureExpression))
            {
                urlSpecifier = "";
                return(null);
            }

            urlSpecifier = path.Substring(0, slashIndex);

            if (slashIndex < pathLength)
            {
                context.Request.Path = new PathString(path.Substring(slashIndex));
            }
            else
            {
                context.Request.Path = new PathString("/");
            }

            if (!cultureContext.Options.IsLanguageSupported(cultureExpression))
            {
                return(null);
            }

            return(cultureExpression);
        }
Beispiel #16
0
        private static object GetResourceBundleObject(string messageKey, CultureInfo locale)
        {
            // Set the UI culture to the passed in locale.
            using (var culture = new CultureContext(locale, locale))
            {
                // slow resource checking
                // need to loop thru all registered resource bundles
                for (IEnumerator <string> it = bundles.Keys.GetEnumerator(); it.MoveNext();)
                {
                    Type            clazz          = bundles[it.Current];
                    ResourceManager resourceBundle = resourceManagerFactory.Create(clazz);
                    if (resourceBundle != null)
                    {
                        try
                        {
                            object obj = resourceBundle.GetObject(messageKey);
                            if (obj != null)
                            {
                                return(obj);
                            }
                        }
#pragma warning disable 168
                        catch (MissingManifestResourceException e)
#pragma warning restore 168
                        {
                            // just continue it might be on the next resource bundle
                        }
                        finally
                        {
                            resourceManagerFactory.Release(resourceBundle);
                        }
                    }
                }
                // if resource is not found
                return(null);
            }
        }
Beispiel #17
0
 public LocalizedViewFindableController(CultureContext cultureContext)
 {
     language            = cultureContext.Culture.Language;
     this.cultureContext = cultureContext;
 }
        public override bool IncrementToken()
        {
            bool iOrAfter = false;
            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("tr");

            if (input.IncrementToken())
            {
                char[] buffer = termAtt.Buffer();
                int length = termAtt.Length;
                for (int i = 0; i < length;)
                {
                    int ch = Character.CodePointAt(buffer, i, length);

                    iOrAfter = (ch == LATIN_CAPITAL_LETTER_I || (iOrAfter && char.GetUnicodeCategory((char)ch) == UnicodeCategory.NonSpacingMark));

                    if (iOrAfter) // all the special I turkish handling happens here.
                    {
                        switch (ch)
                        {
                            // remove COMBINING_DOT_ABOVE to mimic composed lowercase
                            case COMBINING_DOT_ABOVE:
                                length = Delete(buffer, i, length);
                                continue;
                            // i itself, it depends if it is followed by COMBINING_DOT_ABOVE
                            // if it is, we will make it small i and later remove the dot
                            case LATIN_CAPITAL_LETTER_I:
                                if (IsBeforeDot(buffer, i + 1, length))
                                {
                                    buffer[i] = (char)LATIN_SMALL_LETTER_I;
                                }
                                else
                                {
                                    buffer[i] = (char)LATIN_SMALL_LETTER_DOTLESS_I;
                                    // below is an optimization. no COMBINING_DOT_ABOVE follows,
                                    // so don't waste time calculating Character.getType(), etc
                                    iOrAfter = false;
                                }
                                i++;
                                continue;
                        }
                    }

                    using (var culture = new CultureContext("tr-TR"))
                    {
                        switch (ch)
                        {
                            // LUCENENET: The .NET char.ToLower() function works correctly in 
                            // Turkish as long as the current thread is set to tr-TR (well, technically the 
                            // culture change is only required for the LATIN_CAPITAL_LETTER_I case). .NET does 
                            // not split these characters into separate letter/non-spacing mark characters,
                            // but the user might still input them that way so we still need the above
                            // block to handle that case.
                            //
                            // LUCENENET TODO: Oddly, the Character.ToLowerCase() function below does not work right
                            // for Turkish. Which begs the question, should this special case be there so Turkish works
                            // everywhere? Or should we leave it a special case here because that is the way it works in Java?
                            //
                            // References:
                            // http://haacked.com/archive/2012/07/05/turkish-i-problem-and-why-you-should-care.aspx/
                            // http://www.i18nguy.com/unicode/turkish-i18n.html
                            case LATIN_CAPITAL_LETTER_I:
                            case LATIN_CAPITAL_LETTER_DOTTED_I:
                                i += Character.ToChars(char.ToLower((char)ch), buffer, i);
                                continue;
                        }
                    }

                    i += Character.ToChars(Character.ToLowerCase(ch), buffer, i);
                }

                termAtt.Length = length;
                return true;
            }
            else
            {
                return false;
            }
        }
        private static IDisposable SetCultures(GlobalizationSection gs) {
            CultureContext c = new CultureContext();

            if (gs != null) {
                CultureInfo culture = null;
                CultureInfo uiCulture = null;

                if (gs.Culture != null && gs.Culture.Length > 0) {
                    try {
                        culture = HttpServerUtility.CreateReadOnlyCultureInfo(gs.Culture);
                    }
                    catch {
                    }
                }

                if (gs.UICulture != null && gs.UICulture.Length > 0) {
                    try {
                        uiCulture = HttpServerUtility.CreateReadOnlyCultureInfo(gs.UICulture);
                    }
                    catch {
                    }
                }

                c.SetCultures(culture, uiCulture);
            }

            return c;
        }
Beispiel #20
0
        private static object GetResourceBundleObject(string messageKey, CultureInfo locale)
        {
            // Set the UI culture to the passed in locale.
            using (var culture = new CultureContext(locale, locale))
            {
                // slow resource checking
                // need to loop thru all registered resource bundles
                for (IEnumerator<string> it = bundles.Keys.GetEnumerator(); it.MoveNext();)
                {
                    Type clazz = bundles[it.Current];
                    ResourceManager resourceBundle = resourceManagerFactory.Create(clazz);
                    if (resourceBundle != null)
                    {
                        try
                        {
                            object obj = resourceBundle.GetObject(messageKey);
                            if (obj != null)
                                return obj;
                        }
#pragma warning disable 168
                        catch (MissingManifestResourceException e)
#pragma warning restore 168
                        {
                            // just continue it might be on the next resource bundle
                        }
                        finally
                        {
                            resourceManagerFactory.Release(resourceBundle);
                        }
                    }
                }
                // if resource is not found
                return null;
            }
        }
Beispiel #21
0
        public override ViewEngineResult FindView(ActionContext actionContext, ViewResult viewResult)
        {
            string viewName = viewResult.ViewName;

            if (viewName == null)
            {
                viewName = GetActionName(actionContext);
            }
            if (viewName == null)
            {
                return(base.FindView(actionContext, viewResult));
            }

            string controllerName;

            if (!actionContext.ActionDescriptor.RouteValues.TryGetValue(ControllerNameKey, out controllerName) ||
                string.IsNullOrEmpty(controllerName))
            {
                controllerName = "";
            }
            string basePath = Path.Combine("Views", controllerName, viewName);

            IServiceProvider  services          = actionContext.HttpContext.RequestServices;
            CultureContext    cultureContext    = services.GetRequiredService <CultureContext>();
            CultureExpression cultureExpression = cultureContext.Culture;
            string            requestedLanguage = cultureExpression.Language;
            string            lang = requestedLanguage;
            string            nameResult;

            if (!cultureExpression.IsAllRegion && IsViewFileExisits(lang, out nameResult))
            {
                // exact match
                viewResult.ViewName             = nameResult;
                viewResult.ViewData["Language"] = new LanguageRequestResult(lang, lang, true);
                return(base.FindView(actionContext, viewResult));
            }
            lang = cultureExpression.LanguageName;
            if (IsViewFileExisits(lang, out nameResult))
            {
                // language name match
                viewResult.ViewName             = nameResult;
                viewResult.ViewData["Language"] = new LanguageRequestResult(requestedLanguage, lang, true);
                return(base.FindView(actionContext, viewResult));
            }
            else
            {
                // find the first availble region of one language
                IDirectoryContents directoryContents = env.ContentRootFileProvider.GetDirectoryContents(Path.Combine("Views", controllerName));
                string             startsWithFilter  = $"{viewName}.{lang}";
                IFileInfo          file = directoryContents.FirstOrDefault(x => x.Name.StartsWith(startsWithFilter) && x.Name.EndsWith(".cshtml"));
                if (file != null)
                {
                    string cultureName = file.Name.Substring(viewName.Length + 1);
                    cultureName.Substring(0, cultureName.Length - 7);
                    nameResult = file.Name.Substring(0, file.Name.Length - 7);
                    if (CultureExpression.TryParse(cultureName, out CultureExpression exp))
                    {
                        viewResult.ViewData["Language"] = new LanguageRequestResult(requestedLanguage, exp.Language, true);
                    }
                    else
                    {
                        viewResult.ViewData["Language"] = new LanguageRequestResult(requestedLanguage, null, false);
                    }
                    viewResult.ViewName = nameResult;
                    return(base.FindView(actionContext, viewResult));
                }
            }

            CultureExpression defaultLanguage = cultureContext.Options.DefaultLanguage;

            lang = defaultLanguage.Language;
            if (IsViewFileExisits(lang, out nameResult))
            {
                // default language match
                viewResult.ViewName             = nameResult;
                viewResult.ViewData["Language"] = new LanguageRequestResult(requestedLanguage, lang, false);
                return(base.FindView(actionContext, viewResult));
            }
            lang = defaultLanguage.LanguageName;
            if (IsViewFileExisits(lang, out nameResult))
            {
                // default language name match
                viewResult.ViewName             = nameResult;
                viewResult.ViewData["Language"] = new LanguageRequestResult(requestedLanguage, lang, false);
                return(base.FindView(actionContext, viewResult));
            }

            // default file match
            viewResult.ViewName             = viewName;
            viewResult.ViewData["Language"] = new LanguageRequestResult(requestedLanguage, null, false);
            return(base.FindView(actionContext, viewResult));

            bool IsViewFileExisits(string language, out string viewNameaResult)
            {
                string pathWithLang = $"{basePath}.{lang}.cshtml";

                if (env.ContentRootFileProvider.GetFileInfo(pathWithLang).Exists)
                {
                    viewNameaResult = viewName + "." + lang;
                    return(true);
                }
                viewNameaResult = null;
                return(false);
            }
        }
Beispiel #22
0
        public override bool IncrementToken()
        {
            bool iOrAfter = false;

            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("tr");

            if (input.IncrementToken())
            {
                char[] buffer = termAtt.Buffer();
                int    length = termAtt.Length;
                for (int i = 0; i < length;)
                {
                    int ch = Character.CodePointAt(buffer, i, length);

                    iOrAfter = (ch == LATIN_CAPITAL_LETTER_I || (iOrAfter && char.GetUnicodeCategory((char)ch) == UnicodeCategory.NonSpacingMark));

                    if (iOrAfter) // all the special I turkish handling happens here.
                    {
                        switch (ch)
                        {
                        // remove COMBINING_DOT_ABOVE to mimic composed lowercase
                        case COMBINING_DOT_ABOVE:
                            length = Delete(buffer, i, length);
                            continue;

                        // i itself, it depends if it is followed by COMBINING_DOT_ABOVE
                        // if it is, we will make it small i and later remove the dot
                        case LATIN_CAPITAL_LETTER_I:
                            if (IsBeforeDot(buffer, i + 1, length))
                            {
                                buffer[i] = (char)LATIN_SMALL_LETTER_I;
                            }
                            else
                            {
                                buffer[i] = (char)LATIN_SMALL_LETTER_DOTLESS_I;
                                // below is an optimization. no COMBINING_DOT_ABOVE follows,
                                // so don't waste time calculating Character.getType(), etc
                                iOrAfter = false;
                            }
                            i++;
                            continue;
                        }
                    }

                    using (var culture = new CultureContext("tr-TR"))
                    {
                        switch (ch)
                        {
                        // LUCENENET: The .NET char.ToLower() function works correctly in
                        // Turkish as long as the current thread is set to tr-TR (well, technically the
                        // culture change is only required for the LATIN_CAPITAL_LETTER_I case). .NET does
                        // not split these characters into separate letter/non-spacing mark characters,
                        // but the user might still input them that way so we still need the above
                        // block to handle that case.
                        //
                        // LUCENENET TODO: Oddly, the Character.ToLowerCase() function below does not work right
                        // for Turkish. Which begs the question, should this special case be there so Turkish works
                        // everywhere? Or should we leave it a special case here because that is the way it works in Java?
                        //
                        // References:
                        // http://haacked.com/archive/2012/07/05/turkish-i-problem-and-why-you-should-care.aspx/
                        // http://www.i18nguy.com/unicode/turkish-i18n.html
                        case LATIN_CAPITAL_LETTER_I:
                        case LATIN_CAPITAL_LETTER_DOTTED_I:
                            i += Character.ToChars(char.ToLower((char)ch), buffer, i);
                            continue;
                        }
                    }

                    i += Character.ToChars(Character.ToLowerCase(ch), buffer, i);
                }

                termAtt.Length = length;
                return(true);
            }
            else
            {
                return(false);
            }
        }