public static void Sanitize() { var currentCulture = CultureInfo.CurrentCulture; // at the top of any culture should be the invariant culture, // find it doing an .Equals comparison ensure that we will // find it and not loop endlessly var invariantCulture = currentCulture; while (invariantCulture.Equals(CultureInfo.InvariantCulture) == false) { invariantCulture = invariantCulture.Parent; } if (ReferenceEquals(invariantCulture, CultureInfo.InvariantCulture)) { return; } #if NET46 var thread = Thread.CurrentThread; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(thread.CurrentCulture.Name); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(thread.CurrentUICulture.Name); #else CultureInfo.CurrentCulture = CultureInfoHelper.Get(CultureInfo.CurrentCulture.Name); CultureInfo.CurrentUICulture = CultureInfoHelper.Get(CultureInfo.CurrentUICulture.Name); #endif }
private static void ConfigureRequestLocalization(IApplicationBuilder app) { var iocResolver = app.ApplicationServices.GetRequiredService <IIocResolver>(); using (var languageManager = iocResolver.ResolveAsDisposable <ILanguageManager>()) { var defaultLanguage = languageManager.Object .GetLanguages() .FirstOrDefault(l => l.IsDefault); if (defaultLanguage == null) { return; } var supportedCultures = languageManager.Object .GetLanguages() .Select(l => CultureInfoHelper.Get(l.Name)) .ToArray(); var defaultCulture = new RequestCulture(defaultLanguage.Name); var options = new RequestLocalizationOptions { DefaultRequestCulture = defaultCulture, SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }; options.RequestCultureProviders.Insert(0, new AbpLocalizationHeaderRequestCultureProvider()); app.UseRequestLocalization(options); } }
public static void UseAbpRequestLocalization(this IApplicationBuilder app, Action <RequestLocalizationOptions> optionsAction = null) { var iocResolver = app.ApplicationServices.GetRequiredService <IIocResolver>(); using (var languageManager = iocResolver.ResolveAsDisposable <ILanguageManager>()) { var supportedCultures = languageManager.Object .GetLanguages() .Select(l => CultureInfoHelper.Get(l.Name)) .ToArray(); var options = new RequestLocalizationOptions { SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }; var userProvider = new AbpUserRequestCultureProvider(); //0: QueryStringRequestCultureProvider options.RequestCultureProviders.Insert(1, userProvider); options.RequestCultureProviders.Insert(2, new AbpLocalizationHeaderRequestCultureProvider()); //3: CookieRequestCultureProvider options.RequestCultureProviders.Insert(4, new AbpDefaultRequestCultureProvider()); //5: AcceptLanguageHeaderRequestCultureProvider optionsAction?.Invoke(options); userProvider.CookieProvider = options.RequestCultureProviders.OfType <CookieRequestCultureProvider>().FirstOrDefault(); userProvider.HeaderProvider = options.RequestCultureProviders.OfType <AbpLocalizationHeaderRequestCultureProvider>().FirstOrDefault(); app.UseRequestLocalization(options); } }
public static void UseAbpRequestLocalization(this IApplicationBuilder app, Action <RequestLocalizationOptions> optionsAction = null) { var iocResolver = app.ApplicationServices.GetRequiredService <IIocResolver>(); using (var languageManager = iocResolver.ResolveAsDisposable <ILanguageManager>()) { var supportedCultures = languageManager.Object .GetLanguages() .Select(l => CultureInfoHelper.Get(l.Name)) .ToArray(); var options = new RequestLocalizationOptions { SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }; var userProvider = new UserRequestCultureProvider(); options.RequestCultureProviders.Insert(0, new AbpLocalizationHeaderRequestCultureProvider()); options.RequestCultureProviders.Insert(2, userProvider); options.RequestCultureProviders.Insert(4, new DefaultRequestCultureProvider()); optionsAction?.Invoke(options); //TODO: Find cookie provider, set to UserRequestCultureProvider to set user's setting!!! userProvider.CookieProvider = options.RequestCultureProviders.FirstOrDefault(p => p is CookieRequestCultureProvider); app.UseRequestLocalization(options); } }
//[Fact] public void TestGetAllStrings() { var allStrings = resourceFileLocalizationSource.GetAllStrings(CultureInfoHelper.Get("en")); allStrings.Count.ShouldBe(2); allStrings.Any(s => s.Name == "Hello" && s.Value == "Hello!").ShouldBeTrue(); allStrings.Any(s => s.Name == "World" && s.Value == "World!").ShouldBeTrue(); }
protected virtual void SetCurrentCulture(string language) { #pragma warning disable CS0618 // Type or member is obsolete Thread.CurrentThread.CurrentCulture = CultureInfoHelper.Get(language); #pragma warning restore CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete Thread.CurrentThread.CurrentUICulture = CultureInfoHelper.Get(language); #pragma warning restore CS0618 // Type or member is obsolete }
public void Simple_Localization_Test(string cultureName) { CultureInfo.CurrentUICulture = CultureInfoHelper.Get(cultureName); Resolve <ILanguageManager>().CurrentLanguage.Name.ShouldBe("en"); Resolve <ILocalizationManager>() .GetString(AbpZeroConsts.LocalizationSourceName, "Identity.UserNotInRole") .ShouldBe("User is not in role '{0}'."); }
/// <summary> /// Builds an <see cref="XmlLocalizationDictionary" /> from given xml string. /// </summary> /// <param name="xmlString">XML string</param> public static XmlLocalizationDictionary BuildFomXmlString(string xmlString) { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xmlString); var localizationDictionaryNode = xmlDocument.SelectNodes("/localizationDictionary"); if (localizationDictionaryNode == null || localizationDictionaryNode.Count <= 0) { throw new StudioXException("A Localization Xml must include localizationDictionary as root node."); } var cultureName = localizationDictionaryNode[0].GetAttributeValueOrNull("culture"); if (string.IsNullOrEmpty(cultureName)) { throw new StudioXException("culture is not defined in language XML file!"); } var dictionary = new XmlLocalizationDictionary(CultureInfoHelper.Get(cultureName)); var dublicateNames = new List <string>(); var textNodes = xmlDocument.SelectNodes("/localizationDictionary/texts/text"); if (textNodes != null) { foreach (XmlNode node in textNodes) { var name = node.GetAttributeValueOrNull("name"); if (string.IsNullOrEmpty(name)) { throw new StudioXException("name attribute of a text is empty in given xml string."); } if (dictionary.Contains(name)) { dublicateNames.Add(name); } dictionary[name] = (node.GetAttributeValueOrNull("value") ?? node.InnerText).NormalizeLineEndings(); } } if (dublicateNames.Count > 0) { throw new StudioXException( "A dictionary can not contain same key twice. There are some duplicated names: " + dublicateNames.JoinAsString(", ")); } return(dictionary); }
public static CultureInfo GetCultureInfoByChecking(string name) { try { return(CultureInfoHelper.Get(name)); } catch (CultureNotFoundException) { return(CultureInfo.CurrentCulture); } }
/// <summary> /// Builds an <see cref="JsonLocalizationDictionary" /> from given json string. /// </summary> /// <param name="jsonString">Json string</param> public static JsonLocalizationDictionary BuildFromJsonString(string jsonString) { JsonLocalizationFile jsonFile; try { jsonFile = JsonConvert.DeserializeObject <JsonLocalizationFile>( jsonString, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } catch (JsonException ex) { throw new AbpException("Can not parse json string. " + ex.Message); } var cultureCode = jsonFile.Culture; if (string.IsNullOrEmpty(cultureCode)) { throw new AbpException("Culture is empty in language json file."); } var dictionary = new JsonLocalizationDictionary(CultureInfoHelper.Get(cultureCode)); var dublicateNames = new List <string>(); foreach (var item in jsonFile.Texts) { if (string.IsNullOrEmpty(item.Key)) { throw new AbpException("The key is empty in given json string."); } if (dictionary.Contains(item.Key)) { dublicateNames.Add(item.Key); } dictionary[item.Key] = item.Value.NormalizeLineEndings(); } if (dublicateNames.Count > 0) { throw new AbpException( "A dictionary can not contain same key twice. There are some duplicated names: " + dublicateNames.JoinAsString(", ")); } return(dictionary); }
public PartialViewResult EditTextModal( string sourceName, string baseLanguageName, string languageName, string key) { var languages = _languageManager.GetLanguages(); var baselanguage = languages.FirstOrDefault(l => l.Name == baseLanguageName); if (baselanguage == null) { throw new Exception("Could not find language: " + baseLanguageName); } var targetLanguage = languages.FirstOrDefault(l => l.Name == languageName); if (targetLanguage == null) { throw new Exception("Could not find language: " + languageName); } var baseText = _applicationLanguageTextManager.GetStringOrNull( AbpSession.TenantId, sourceName, CultureInfoHelper.Get(baseLanguageName), key ); var targetText = _applicationLanguageTextManager.GetStringOrNull( AbpSession.TenantId, sourceName, CultureInfoHelper.Get(languageName), key, false ); var viewModel = new EditTextModalViewModel { SourceName = sourceName, BaseLanguage = baselanguage, TargetLanguage = targetLanguage, BaseText = baseText, TargetText = targetText, Key = key }; return(PartialView("_EditTextModal", viewModel)); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) { if (token.IsCancellationRequested) { return(Task.FromCanceled <HttpResponseMessage>(token)); } // here you can chose to get the lang from database, cookie or from the request if the culture is stored on local storage. CultureInfo ci = null; if (!string.IsNullOrEmpty(request.RequestUri.Query)) { NameValueCollection queryString = HttpUtility.ParseQueryString(request.RequestUri.Query); string name = queryString[_parameterName]?.Trim(); if (!string.IsNullOrEmpty(name)) { ci = CultureInfoHelper.Get(name); } } if (ci == null && request.Headers.AcceptLanguage.Count > 0) { foreach (StringWithQualityHeaderValue headerValue in request.Headers.AcceptLanguage) { if (string.IsNullOrEmpty(headerValue.Value) || headerValue.Value.Length < 2) { continue; } string name = headerValue.Value.Substring(0, 2); if (!CultureInfoHelper.IsCultureName(name)) { continue; } ci = CultureInfoHelper.Get(name); } } if (ci != null) { request.Headers.AcceptLanguage.Clear(); request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(ci.Name)); Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; } return(base.SendAsync(request, token)); }
public async Task UpdateLanguageText() { await _languageAppService.UpdateLanguageText( new UpdateLanguageTextInput { SourceName = WebPortalConsts.LocalizationSourceName, LanguageName = "en", Key = "Save", Value = "save-new-value" }); var newValue = Resolve <ILocalizationManager>() .GetString( WebPortalConsts.LocalizationSourceName, "Save", CultureInfoHelper.Get("en") ); newValue.ShouldBe("save-new-value"); }
public async Task <ActionResult> GetScripts(string culture = "", bool minify = false) { if (!culture.IsNullOrEmpty()) { Thread.CurrentThread.CurrentUICulture = CultureInfoHelper.Get(culture); } var sb = new StringBuilder(); sb.AppendLine(_multiTenancyScriptManager.GetScript()); sb.AppendLine(); sb.AppendLine(_sessionScriptManager.GetScript()); sb.AppendLine(); sb.AppendLine(_localizationScriptManager.GetScript()); sb.AppendLine(); sb.AppendLine(await _featuresScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await _authorizationScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await _navigationScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await _settingScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await _timingScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(_securityScriptManager.GetScript()); sb.AppendLine(); sb.AppendLine(GetTriggerScript()); return(Content(minify ? _javaScriptMinifier.Minify(sb.ToString()) : sb.ToString(), "application/x-javascript", Encoding.UTF8)); }
public override Task Invoke([NotNull] HttpContext context) { if (context.RequestAborted.IsCancellationRequested) { return(Task.FromCanceled(context.RequestAborted)); } // here you can chose to get the lang from database, cookie or from the request if the culture is stored on local storage. CultureInfo ci = null; HttpRequest request = context.Request; if (request.Query.TryGetValue(ParameterName, out StringValues queryValues) && queryValues.Count > 0) { string name = queryValues.SkipNullOrWhitespace().FirstOrDefault(); if (!string.IsNullOrEmpty(name)) { ci = CultureInfoHelper.Get(name); } } if (ci == null && request.Headers.TryGetValue(MSHeaderNames.AcceptLanguage, out StringValues headerValues) && headerValues.Count > 0) { string name = queryValues.SkipNullOrWhitespace() .FirstOrDefault(e => e.Length > 1) ?.Substring(0, 2); if (!string.IsNullOrEmpty(name)) { ci = CultureInfoHelper.Get(name); } } if (ci != null) { request.Headers[MSHeaderNames.AcceptLanguage] = ci.Name; Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; } return(Next.Invoke(context)); }
public void Test_GetString() { //Defined in English _resourceFileLocalizationSource.GetString("Hello", CultureInfoHelper.Get("en")).ShouldBe("Hello!"); //en-US and en-GB fallbacks to en _resourceFileLocalizationSource.GetString("Hello", CultureInfoHelper.Get("en-US")).ShouldBe("Hello!"); _resourceFileLocalizationSource.GetString("World", CultureInfoHelper.Get("en-US")).ShouldBe("World!"); _resourceFileLocalizationSource.GetString("Hello", CultureInfoHelper.Get("en-GB")).ShouldBe("Hello!"); //Defined in Turkish _resourceFileLocalizationSource.GetString("Hello", CultureInfoHelper.Get("tr")).ShouldBe("Merhaba!"); //tr-TR fallbacks to tr _resourceFileLocalizationSource.GetString("Hello", CultureInfoHelper.Get("tr-TR")).ShouldBe("Merhaba!"); //Undefined for Turkish, fallbacks to default language _resourceFileLocalizationSource.GetString("World", CultureInfoHelper.Get("tr-TR")).ShouldBe("World!"); //Undefined at all, fallback to given text _resourceFileLocalizationSource.GetString("Apple", CultureInfoHelper.Get("en-US")).ShouldBe("[Apple]"); }
public void TestGetStringOrNull() { //Defined in English resourceFileLocalizationSource.GetStringOrNull("Hello", CultureInfoHelper.Get("en")).ShouldBe("Hello!"); //en-US and en-GB fallbacks to en resourceFileLocalizationSource.GetStringOrNull("Hello", CultureInfoHelper.Get("en-US")).ShouldBe("Hello!"); resourceFileLocalizationSource.GetStringOrNull("World", CultureInfoHelper.Get("en-US")).ShouldBe("World!"); resourceFileLocalizationSource.GetStringOrNull("Hello", CultureInfoHelper.Get("en-GB")).ShouldBe("Hello!"); //Defined in Turkish resourceFileLocalizationSource.GetStringOrNull("Hello", CultureInfoHelper.Get("tr")).ShouldBe("Merhaba!"); //tr-TR fallbacks to tr resourceFileLocalizationSource.GetStringOrNull("Hello", CultureInfoHelper.Get("tr-TR")).ShouldBe("Merhaba!"); //Undefined for Turkish, fallbacks to default language resourceFileLocalizationSource.GetStringOrNull("World", CultureInfoHelper.Get("tr-TR")).ShouldBe("World!"); //Undefined at all, returns null resourceFileLocalizationSource.GetStringOrNull("Apple", CultureInfoHelper.Get("en-US")).ShouldBeNull(); }
public async Task <ActionResult> GetScripts(string culture = "") { if (!culture.IsNullOrEmpty()) { CultureInfo.CurrentCulture = CultureInfoHelper.Get(culture); CultureInfo.CurrentUICulture = CultureInfoHelper.Get(culture); } var sb = new StringBuilder(); sb.AppendLine(multiTenancyScriptManager.GetScript()); sb.AppendLine(); sb.AppendLine(sessionScriptManager.GetScript()); sb.AppendLine(); sb.AppendLine(localizationScriptManager.GetScript()); sb.AppendLine(); sb.AppendLine(await featuresScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await authorizationScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await navigationScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await settingScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(await timingScriptManager.GetScriptAsync()); sb.AppendLine(); sb.AppendLine(GetTriggerScript()); return(Content(sb.ToString(), "application/x-javascript", Encoding.UTF8)); }
public async Task <PagedResultDto <LanguageTextListDto> > GetLanguageTexts(GetLanguageTextsInput input) { /* Note: This method is used by SPA without paging, MPA with paging. * So, it can both usable with paging or not */ //Normalize base language name if (input.BaseLanguageName.IsNullOrEmpty()) { var defaultLanguage = await _applicationLanguageManager.GetDefaultLanguageOrNullAsync(AbpSession.TenantId); if (defaultLanguage == null) { defaultLanguage = (await _applicationLanguageManager.GetLanguagesAsync(AbpSession.TenantId)).FirstOrDefault(); if (defaultLanguage == null) { throw new Exception("No language found in the application!"); } } input.BaseLanguageName = defaultLanguage.Name; } var source = LocalizationManager.GetSource(input.SourceName); var baseCulture = CultureInfoHelper.Get(input.BaseLanguageName); var targetCulture = CultureInfoHelper.Get(input.TargetLanguageName); var languageTexts = source .GetAllStrings() .Select(localizedString => new LanguageTextListDto { Key = localizedString.Name, BaseValue = _applicationLanguageTextManager.GetStringOrNull(AbpSession.TenantId, source.Name, baseCulture, localizedString.Name), TargetValue = _applicationLanguageTextManager.GetStringOrNull(AbpSession.TenantId, source.Name, targetCulture, localizedString.Name, false) }) .AsQueryable(); //Filters if (input.TargetValueFilter == "EMPTY") { languageTexts = languageTexts.Where(s => s.TargetValue.IsNullOrEmpty()); } if (!input.FilterText.IsNullOrEmpty()) { languageTexts = languageTexts.Where( l => (l.Key != null && l.Key.IndexOf(input.FilterText, StringComparison.CurrentCultureIgnoreCase) >= 0) || (l.BaseValue != null && l.BaseValue.IndexOf(input.FilterText, StringComparison.CurrentCultureIgnoreCase) >= 0) || (l.TargetValue != null && l.TargetValue.IndexOf(input.FilterText, StringComparison.CurrentCultureIgnoreCase) >= 0) ); } var totalCount = languageTexts.Count(); //Ordering if (!input.Sorting.IsNullOrEmpty()) { languageTexts = languageTexts.OrderBy(input.Sorting); } //Paging if (input.SkipCount > 0) { languageTexts = languageTexts.Skip(input.SkipCount); } if (input.MaxResultCount > 0) { languageTexts = languageTexts.Take(input.MaxResultCount); } return(new PagedResultDto <LanguageTextListDto>( totalCount, languageTexts.ToList() )); }
protected virtual void SetCurrentCulture(string language) { Thread.CurrentThread.CurrentCulture = CultureInfoHelper.Get(language); Thread.CurrentThread.CurrentUICulture = CultureInfoHelper.Get(language); }
public static IEnumerable <CountryInfo> GetCountriesByCulture(string culture = null) { return(GetCountriesByCulture(CultureInfoHelper.Get(culture))); }