public void HtmlLocalizerDoesNotFormatTwiceIfFormattedTranslationContainsCurlyBraces()
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("The page (ID:{0}) was deleted.", "Stránka (ID:{0}) byla smazána.")
            });
            var localizer = new PortableObjectStringLocalizer("small", _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs"))
            {
                var htmlLocalizer = new PortableObjectHtmlLocalizer(localizer);
                var unformatted   = htmlLocalizer["The page (ID:{0}) was deleted.", "{1}"];
                var memStream     = new MemoryStream();
                var textWriter    = new StreamWriter(memStream);
                var textReader    = new StreamReader(memStream);

                unformatted.WriteTo(textWriter, HtmlEncoder.Default);

                textWriter.Flush();
                memStream.Seek(0, SeekOrigin.Begin);
                var formatted = textReader.ReadToEnd();

                textWriter.Dispose();
                textReader.Dispose();
                memStream.Dispose();

                Assert.Equal("Stránka (ID:{1}) byla smazána.", formatted);
            }
        }
        public void LocalizerReturnsOriginalValuesIfTranslationDoesntExistAndMultiplePluraflFormsAreSpecified(string expected, int count)
        {
            SetupDictionary("en", new CultureDictionaryRecord[] { });
            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("en"))
            {
                var translation = localizer.Plural(count, new[] { "míč", "{0} míče", "{0} míčů" }, count);

                Assert.Equal(expected, translation);
            }
        }
Esempio n. 3
0
        public void CultureScopeSetUICultureAutomaticallyIfNotSet()
        {
            // Arrange
            var culture = "ar-YE";

            // Act
            using (var cultureScope = CultureScope.Create(culture))
            {
                // Assert
                Assert.Equal(culture, cultureScope.Culture.Name);
                Assert.Equal(culture, cultureScope.UICulture.Name);
            }
        }
        public void LocalizerReturnsOriginalTextIfDictionaryIsEmpty()
        {
            SetupDictionary("cs", new CultureDictionaryRecord[] { });

            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs"))
            {
                var translation = localizer["car"];

                Assert.Equal("car", translation);
            }
        }
Esempio n. 5
0
        public void CultureScopeRetrievesBothCultureAndUICulture()
        {
            // Arrange
            var culture   = "ar";
            var uiCulture = "ar-YE";

            // Act
            using (var cultureScope = CultureScope.Create(culture, uiCulture))
            {
                // Assert
                Assert.Equal(culture, cultureScope.Culture.Name);
                Assert.Equal(uiCulture, cultureScope.UICulture.Name);
            }
        }
        public void LocalizerReturnsCorrectPluralFormIfMultiplePluraflFormsAreSpecified(string expected, int count)
        {
            SetupDictionary("en", new CultureDictionaryRecord[] {
                new CultureDictionaryRecord("míč", "ball", "{0} balls")
            }, _enPluralRule);
            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("en"))
            {
                var translation = localizer.Plural(count, new[] { "míč", "{0} míče", "{0} míčů" }, count);

                Assert.Equal(expected, translation);
            }
        }
        public void LocalizerReturnsOriginalTextForPluralIfTranslationDoesntExist(string expected, int count)
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("ball", "míč", "míče", "míčů"),
            });

            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs"))
            {
                var translation = localizer.Plural(count, "car", "cars");
                Assert.Equal(expected, translation);
            }
        }
        public void LocalizerReturnsFormattedTranslation()
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("The page (ID:{0}) was deleted.", "Stránka (ID:{0}) byla smazána.")
            });
            var localizer = new PortableObjectStringLocalizer("small", _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs"))
            {
                var translation = localizer["The page (ID:{0}) was deleted.", 1];

                Assert.Equal("Stránka (ID:1) byla smazána.", translation);
            }
        }
Esempio n. 9
0
        public void CultureScopeRetrievesTheOrginalCulturesAfterScopeEnded()
        {
            // Arrange
            var culture   = CultureInfo.CurrentCulture;
            var uiCulture = CultureInfo.CurrentUICulture;

            // Act
            using (var cultureScope = CultureScope.Create("FR"))
            {
            }

            // Assert
            Assert.Equal(culture, CultureInfo.CurrentCulture);
            Assert.Equal(uiCulture, CultureInfo.CurrentUICulture);
        }
        public void LocalizerReturnsOriginalTextIfTranslationsDoesntExistInProvidedDictionary()
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("ball", "míč", "míče", "míčů")
            });

            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs"))
            {
                var translation = localizer["car"];

                Assert.Equal("car", translation);
            }
        }
        public void LocalizerReturnsTranslationWithoutContextIfTranslationWithContextDoesntExist()
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("ball", "míč", "míče", "míčů"),
                new CultureDictionaryRecord("ball", "big", new [] { "míček", "míčky", "míčků" })
            });
            var localizer = new PortableObjectStringLocalizer("small", _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs"))
            {
                var translation = localizer["ball"];

                Assert.Equal("míč", translation);
            }
        }
        public void LocalizerFallBackToParentCultureIfFallBackToParentUICulturesIsTrue(bool fallBackToParentCulture, string resourceKey, string expected)
        {
            SetupDictionary("ar", new CultureDictionaryRecord[] {
                new CultureDictionaryRecord("hello", "مرحبا")
            }, _arPluralRule);
            SetupDictionary("ar-YE", new CultureDictionaryRecord[] { }, _arPluralRule);
            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, fallBackToParentCulture, _logger.Object);

            using (CultureScope.Create("ar-YE"))
            {
                var translation = localizer[resourceKey];

                Assert.Equal(expected, translation);
            }
        }
        public void LocalizerReturnsTranslationInCorrectPluralForm(string expected, int count)
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("ball", "míč", "{0} míče", "{0} míčů"),
            });

            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs"))
            {
                var translation = localizer.Plural(count, "ball", "{0} balls", count);

                Assert.Equal(expected, translation);
            }
        }
        public void LocalizerReturnsCorrectTranslationForPluralIfNoPluralFormsSpecified(string culture, string expected, int count, string[] translations)
        {
            using (var cultureScope = CultureScope.Create(culture))
            {
                // using DefaultPluralRuleProvider to test it returns correct rule
                TryGetRuleFromDefaultPluralRuleProvider(cultureScope.UICulture, out var rule);
                Assert.NotNull(rule);

                SetupDictionary(culture, new[] { new CultureDictionaryRecord("ball", translations), }, rule);
                var localizer   = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);
                var translation = localizer.Plural(count, "ball", "{0} balls", count);

                Assert.Equal(expected, translation);
            }
        }
Esempio n. 15
0
        /// <inheritdocs />
        public override async Task <IDisplayResult> UpdateAsync(LocalizationSettings section, BuildEditorContext context)
        {
            var user = _httpContextAccessor.HttpContext?.User;

            if (!await _authorizationService.AuthorizeAsync(user, Permissions.ManageCultures))
            {
                return(null);
            }

            if (context.GroupId == GroupId)
            {
                var model = new LocalizationSettingsViewModel();

                await context.Updater.TryUpdateModelAsync(model, Prefix);

                var supportedCulture = JsonConvert.DeserializeObject <string[]>(model.SupportedCultures);

                if (!supportedCulture.Any())
                {
                    context.Updater.ModelState.AddModelError("SupportedCultures", S["A culture is required"]);
                }

                if (context.Updater.ModelState.IsValid)
                {
                    // Invariant culture name is empty so a null value is bound.
                    section.DefaultCulture    = model.DefaultCulture ?? "";
                    section.SupportedCultures = supportedCulture;

                    if (!section.SupportedCultures.Contains(section.DefaultCulture))
                    {
                        section.DefaultCulture = section.SupportedCultures[0];
                    }

                    // We always release the tenant for the default culture and also supported cultures to take effect
                    await _shellHost.ReleaseShellContextAsync(_shellSettings);

                    // We create a transient scope with the newly selected culture to create a notification that will use it instead of the previous culture
                    using (CultureScope.Create(section.DefaultCulture))
                    {
                        await _notifier.WarningAsync(H["The site has been restarted for the settings to take effect."]);
                    }
                }
            }

            return(await EditAsync(section, context));
        }
Esempio n. 16
0
        public void CultureScopeRetrievesTheOrginalCulturesIfExceptionOccurs()
        {
            // Arrange
            var culture   = CultureInfo.CurrentCulture;
            var uiCulture = CultureInfo.CurrentUICulture;

            // Act & Assert
            Assert.ThrowsAsync <Exception>(() =>
            {
                using (var cultureScope = CultureScope.Create("FR"))
                {
                    throw new Exception("Something goes wrong!!");
                }
            });
            Assert.Equal(culture, CultureInfo.CurrentCulture);
            Assert.Equal(uiCulture, CultureInfo.CurrentUICulture);
        }
        public void LocalizerReturnsTranslationFromSpecificCultureIfItExists()
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("ball", "míč", "míče", "míčů")
            });
            SetupDictionary("cs-CZ", new[] {
                new CultureDictionaryRecord("ball", "balón", "balóny", "balónů")
            });
            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs-CZ"))
            {
                var translation = localizer["ball"];

                Assert.Equal("balón", translation);
            }
        }
        public void LocalizerFallbacksToParentCultureIfTranslationDoesntExistInSpecificCulture()
        {
            SetupDictionary("cs", new[] {
                new CultureDictionaryRecord("ball", "míč", "míče", "míčů")
            });
            SetupDictionary("cs-CZ", new[] {
                new CultureDictionaryRecord("car", "auto", "auta", "aut")
            });

            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, true, _logger.Object);

            using (CultureScope.Create("cs-cz"))
            {
                var translation = localizer["ball"];

                Assert.Equal("míč", translation);
            }
        }
Esempio n. 19
0
        private async Task GenerateContainerPathFromPattern(AutoroutePart part)
        {
            // Compute the Path only if it's empty
            if (!String.IsNullOrWhiteSpace(part.Path))
            {
                return;
            }

            var pattern = GetPattern(part);

            if (!String.IsNullOrEmpty(pattern))
            {
                var model = new AutoroutePartViewModel()
                {
                    Path          = part.Path,
                    AutoroutePart = part,
                    ContentItem   = part.ContentItem
                };

                _contentManager ??= _serviceProvider.GetRequiredService <IContentManager>();

                var cultureAspect = await _contentManager.PopulateAspectAsync(part.ContentItem, new CultureAspect());

                using (CultureScope.Create(cultureAspect.Culture))
                {
                    part.Path = await _liquidTemplateManager.RenderAsync(pattern, NullEncoder.Default, model,
                                                                         scope => scope.SetValue(nameof(ContentItem), model.ContentItem));
                }

                part.Path = part.Path.Replace("\r", String.Empty).Replace("\n", String.Empty);

                if (part.Path?.Length > AutoroutePart.MaxPathLength)
                {
                    part.Path = part.Path.Substring(0, AutoroutePart.MaxPathLength);
                }

                if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId))
                {
                    part.Path = await GenerateUniqueAbsolutePathAsync(part.Path, part.ContentItem.ContentItemId);
                }

                part.Apply();
            }
        }
        public void LocalizerReturnsGetAllStrings(bool includeParentCultures, string[] expected)
        {
            SetupDictionary("ar", new CultureDictionaryRecord[] {
                new CultureDictionaryRecord("Blog", "مدونة"),
                new CultureDictionaryRecord("Menu", "قائمة"),
                new CultureDictionaryRecord("Page", "صفحة"),
                new CultureDictionaryRecord("Article", "مقالة")
            }, _arPluralRule);
            SetupDictionary("ar-YE", new CultureDictionaryRecord[] {
                new CultureDictionaryRecord("Blog", "مدونة"),
                new CultureDictionaryRecord("Product", "منتج")
            }, _arPluralRule);

            var localizer = new PortableObjectStringLocalizer(null, _localizationManager.Object, false, _logger.Object);

            using (CultureScope.Create("ar-YE"))
            {
                var translations = localizer.GetAllStrings(includeParentCultures).Select(l => l.Value).ToArray();

                Assert.Equal(expected.Count(), translations.Count());
            }
        }
Esempio n. 21
0
        public async Task <IActionResult> IndexPost(string groupId)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageGroupSettings, (object)groupId))
            {
                return(Forbid());
            }

            var site = await _siteService.LoadSiteSettingsAsync();

            var viewModel = new AdminIndexViewModel
            {
                GroupId = groupId,
                Shape   = await _siteSettingsDisplayManager.UpdateEditorAsync(site, _updateModelAccessor.ModelUpdater, false, groupId)
            };

            if (ModelState.IsValid)
            {
                await _siteService.UpdateSiteSettingsAsync(site);

                string culture = null;
                if (site.Properties.TryGetValue("LocalizationSettings", out var settings))
                {
                    culture = settings.Value <string>("DefaultCulture");
                }

                // We create a transient scope with the newly selected culture to create a notification that will use it instead of the previous culture
                using (culture != null ? CultureScope.Create(culture) : null)
                {
                    _notifier.Success(H["Site settings updated successfully."]);
                }

                return(RedirectToAction(nameof(Index), new { groupId }));
            }

            return(View(viewModel));
        }