private void PollCustomCommand() { CultureInfoHelper.SetDateTimeFormat(); while (!_cts.IsCancellationRequested) { try { var now = DateTime.Now; var customCommandList = DasConfig.Repo.GetLastCustomCommand(now); if (customCommandList == null || !customCommandList.Any()) { Thread.Sleep(1000); continue; //没有命令 } foreach (var item in customCommandList) { // 接触命令, 准备执行. item.Accept(); Task.Factory.StartNew(() => HandleCustomCommand(item)); } } catch (Exception e) { Console.WriteLine(e); Thread.Sleep(10 * 1000); // 保证线程持续进行 } Thread.Sleep(1000); } }
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 }
public void SplitCultureCodePartsTest(string value, string expectedLanguageCode, string expectedLocaleCode) { var actual = CultureInfoHelper.SplitCultureCodeParts(value); Assert.Equal(expectedLanguageCode, actual.languageCode); Assert.Equal(expectedLocaleCode, actual.localeCode); }
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); } }
/// <summary> /// Gets property expression for some property in type. If property type is Enum or DateTime will be converted to string. /// It could looks like: /// c.SomeString, Convert.ToString(c.SomeDate, polishCulture), EnumHelper.GetDisplayName(typeof(SomeEnum), c.SomeEnum) /// </summary> /// <param name="propertyInfo">Reflection information about property in type.</param> /// <param name="sourceObjectParameter">Type parameter required for property expression.</param> /// <returns>Property expression for requested property.</returns> private static Expression GetPropertyExpressionForProperty(PropertyInfo propertyInfo, ParameterExpression sourceObjectParameter) { Expression propertyExpression = null; if (propertyInfo == null) { propertyExpression = Expression.Constant(null); } else { propertyExpression = Expression.Property(sourceObjectParameter, propertyInfo); var propertyType = propertyInfo.PropertyType.GetRealType(); if (propertyType.IsEnum) { // Calling EnumHelper.GetDisplayName(Type enumType, object enumValue) var propertyTypeExpression = Expression.Constant(propertyType); var enumValueExpression = Expression.Convert(propertyExpression, typeof(object)); propertyExpression = Expression.Call(getEnumDisplayNameMethodInfo, propertyTypeExpression, enumValueExpression); } else if (propertyType.IsValueType) { // Calling Convert.ToString(property type, IFormatProvider) var methodParmetersTypes = new[] { propertyType, typeof(IFormatProvider) }; MethodInfo convertToStringMethod = typeof(Convert).GetMethod("ToString", methodParmetersTypes); var cultureInfo = CultureInfoHelper.GetCultureInfoForType(propertyType); var cultureExpression = Expression.Constant(cultureInfo); propertyExpression = Expression.Call(convertToStringMethod, propertyExpression, cultureExpression); } } return(propertyExpression); }
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); } }
// Same as AddDirectory, but only look at files that don't have a culture internal void AddResourcesDirectory([NotNull] string directoryName) { DirectoryInfo directory = new DirectoryInfo(directoryName); if (!directory.Exists) { return; } AddObject(directoryName); // Go through all the files in the directory foreach (DirectoryInfo directoryInfo in directory.GetDirectories()) { AddResourcesDirectory(directoryInfo.FullName); } foreach (FileInfo fileInfo in directory.GetFiles()) { // Ignore the file if it has a culture, since only neutral files // need to re-trigger compilation (VSWhidbey 359029) string fullPath = fileInfo.FullName; if (CultureInfoHelper.GetNameFromFileName(fullPath) == null) { AddExistingFile(fullPath); } } AddDateTime(directory.CreationTimeUtc); }
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); } }
public void Start() { Task.Factory.StartNew(() => { CultureInfoHelper.SetDateTimeFormat(); while (!_cts.IsCancellationRequested) { // das 循环发送命令, 并接受报文. try { //if (Comm == null || !Comm.IsConnect) //{ // Log($"网络断开,{Comm}重新连接."); // Comm?.Start(); // Thread.Sleep(3000); // continue; //} GatherData(); } catch (Exception e) { LogD.Error("轮询中出现错误:" + e); } finally { Thread.Sleep(50); } } }, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
private void SetThreadCulture(Site site) { if (!string.IsNullOrEmpty(site.Culture)) { var culture = CultureInfoHelper.CreateCultureInfo(site.Culture); Thread.CurrentThread.CurrentCulture = culture; } }
//[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(); }
public void OnFeatureStart_DefersToInnerSynchronousTestRunner() { var featureInfo = new FeatureInfo(CultureInfoHelper.GetCultureInfo("en-us"), "title", "description"); asyncTestRunner.OnFeatureStart(featureInfo); testExecutionEngineStub.Verify(m => m.OnFeatureStart(featureInfo)); }
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 }
//private Thread _loadThread; public BasePlugin() { CultureInfoHelper.SetDateTimeFormat(); LogDogCollar = new LogDogCollar(); LogDogRoot = RegisterLogDog(Title); BaseDirectory = Path.GetDirectoryName(Assembly.GetAssembly(this.GetType()).Location); _pluginMonitors = InitMonitors(); _pluginKVs = InitKvs(); }
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}'."); }
public void Should_Localize_AbpWebCommon_Texts() { using (CultureInfoHelper.Use("en")) { _localizationManager .GetSource(AbpWebConsts.LocalizaionSourceName) .GetString("ValidationError") .ShouldBe("Your request is not valid!"); } }
///<inheritdoc/> public async ValueTask <IReadOnlyDictionary <string, string>?> TryLoadAsync( HttpHostedJsonLocalizationOptions options, Assembly assembly, string baseName, CultureInfo cultureInfo) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var assemblyName = assembly.GetName().Name; var rootPath = (options.ApplicationAssembly == assembly) ? string.Empty : $"_content/{assemblyName}/"; if (!string.IsNullOrEmpty(options.ResourcesPath)) { rootPath = $"{rootPath}{options.ResourcesPath}/"; } var basePath = $"{rootPath}{ResourcePathHelper.ComputeBasePath(assembly, baseName)}"; return(await CultureInfoHelper.WalkThoughCultureInfoParentsAsync(cultureInfo, cultureName => { var uri = string.IsNullOrEmpty(cultureName) ? new Uri($"{basePath}.json", UriKind.Relative) : new Uri($"{basePath}{options.CultureSeparator}{cultureName}.json", UriKind.Relative); this.logger.LogDebug($"Loading static assets data from {uri}"); lock (Cache) { if (!Cache.TryGetValue(uri, out var loadingTask)) { loadingTask = TryLoadFromUriAsync(uri, options.JsonSerializerOptions); Cache.Add(uri, loadingTask); } else if (loadingTask.IsFaulted) { loadingTask = TryLoadFromUriAsync(uri, options.JsonSerializerOptions); Cache[uri] = loadingTask; } return loadingTask; } }) .ConfigureAwait(false)); }
/// <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); } }
public IActionResult Index() { var hello = LocalizationManager.GetSource("MySource").GetStringOrNull("hello"); using (CultureInfoHelper.Use("tr", "tr")) { var hellotr = LocalizationManager.GetSource("MySource").GetStringOrNull("hello"); } return(Redirect("/swagger")); }
public void ToSentenceCase_Test() { (null as string).ToSentenceCase().ShouldBe(null); "HelloWorld".ToSentenceCase().ShouldBe("Hello world"); using (CultureInfoHelper.Use("en-US")) { "HelloIsparta".ToSentenceCase().ShouldBe("Hello isparta"); } "HelloIsparta".ToSentenceCase(new CultureInfo("tr-TR")).ShouldBe("Hello ısparta"); }
/// <summary> /// Initializes a new instance of the <see cref="PlatformCultureInfo"/> class. /// Container for culture info parts /// </summary> /// <param name="cultureCode"> /// </param> /// <exception cref="ArgumentException"> /// If /// <exception cref="cultureCode"> /// is null or string.Empty /// </exception> /// </exception> public PlatformCultureInfo(string cultureCode) { if (string.IsNullOrEmpty(cultureCode)) { throw new ArgumentException("Expected culture identifier", nameof(cultureCode)); } var(languageCode, localeCode) = CultureInfoHelper.SplitCultureCodeParts(cultureCode); LanguageCode = languageCode; LocaleCode = localeCode; }
public ActionResult Index(FrontEndCmsPage page, string k) { FrontEndSubscriptionRegister frontEndSubscriptionRegister = new FrontEndSubscriptionRegister() { LangugeCode = page.LanguageCode }; ViewBag.IsActivationPage = false; if (k.IsNotEmptyOrWhiteSpace()) { ViewBag.IsActivationPage = true; Subscriptions subscriptions = new Subscriptions(); int? result = subscriptions.ActivativateSubscription(k); switch (result) { case 0: Subscription subscription = subscriptions.GetSubscriptionByActivationKey(k); GlobalConfiguration globalConfiguration = new GlobalConfigurations().GetGlobalConfiguration(); CultureInfoHelper.ForceBackEndLanguage(); string subject = Resources.Strings_Subscription.EmailSubscriptionAddedSubject.Replace("{$Url}", globalConfiguration.DomainName.ToUrl()); string body = Resources.Strings_Subscription.EmailSubscriptionAddedBody .Replace("{$Url}", globalConfiguration.DomainName.ToUrl()) .Replace("{$subscriptionEmail}", subscription.Email) .Replace("{$ipAddress}", Request.UserHostAddress); CultureInfoHelper.RestoreFrontEndLanguage(); EmailHelper email = new EmailHelper(globalConfiguration.NotificationEmail, globalConfiguration.NotificationEmail, subject, body); email.Send(); ViewBag.ActivationResult = Resources.Strings_Subscription.ActivationKeySuccess; break; case 2: ViewBag.ActivationResult = Resources.Strings_Subscription.ActivationKeyInvalid; break; case 3: ViewBag.ActivationResult = Resources.Strings_Subscription.ActivationKeyAlreadyUsed; break; default: ViewBag.ActivationResult = Resources.Strings.UnexpectedError; break; } } return(View(frontEndSubscriptionRegister)); }
internal void ResetContext() { if (!string.IsNullOrEmpty(this.PathInfo)) { appRelativeCurrentExecutionFilePath = appRelativeCurrentExecutionFilePath.TrimEnd('/') + "/" + PathInfo; } if (SiteMappedContext != null) { //trim "~/" var trimedPath = appRelativeCurrentExecutionFilePath.Substring(2); this.Site = SiteMappedContext.Site; if (SiteMappedContext.RequestChannel == FrontRequestChannel.Preview) { //preview url #region dev~ //dev~site1/index var paths = trimedPath.Split('/'); RequestUrl = Kooboo.Common.Web.UrlUtility.Combine(new[] { "/" }.Concat(paths.Skip(1)).ToArray()); if (this.Path.EndsWith("/") && !this.RequestUrl.EndsWith("/")) { RequestUrl = RequestUrl + "/"; } appRelativeCurrentExecutionFilePath = "~" + RequestUrl; #endregion } else { var sitePathLength = 0; var path = trimedPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); RequestUrl = UrlUtility.Combine(new[] { "/" }.Concat(path.Skip(sitePathLength)).ToArray()); if (this.Path.EndsWith("/") && !this.RequestUrl.EndsWith("/")) { RequestUrl = RequestUrl + "/"; } appRelativeCurrentExecutionFilePath = "~" + RequestUrl; } if (!string.IsNullOrEmpty(Site.Culture)) { var culture = CultureInfoHelper.CreateCultureInfo(Site.Culture); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } } //decode the request url. for chinese character this.RequestUrl = HttpUtility.UrlDecode(this.RequestUrl); }
/// <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); }
private static object GetValue(Type propertyType, string valueAsString) { var realType = propertyType.GetRealType(); if (realType.IsEnum) { return(Enum.Parse(realType, valueAsString)); } var cultureInfo = CultureInfoHelper.GetCultureInfoForType(realType); return(Convert.ChangeType(valueAsString, propertyType, cultureInfo)); }
public void Test_Json_Override() { var mananger = LocalIocManager.Resolve <ILocalizationManager>(); using (CultureInfoHelper.Use("en")) { var abpSource = mananger.GetSource(AbpConsts.LocalizationSourceName); abpSource.GetString("TimeZone").ShouldBe("Time-zone"); var abpZeroSource = mananger.GetSource(AbpZeroConsts.LocalizationSourceName); abpZeroSource.GetString("Email").ShouldBe("Email address"); } }
public void Should_Localize_AbpWebCommon_Texts() { using (CultureInfoHelper.Use("en")) { var texts = _localizationManager .GetSource(AbpWebConsts.LocalizaionSourceName) .GetStrings(new List <string> { "ValidationError", "InternalServerError" }); texts.ShouldContain(x => x == "Your request is not valid!"); texts.ShouldContain(x => x == "An internal error occurred during your request!"); } }
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)); }
public async Task ItShouldCallTheDataLoaderWithTheCultureInfoNameAsync() { var cultureName = "fr-FR"; var cultureInfo = CultureInfo.GetCultureInfo(cultureName); var data = await CultureInfoHelper.WalkThoughCultureInfoParentsAsync <string>( cultureInfo, name => { return(Task.FromResult <string?>(name)); }).ConfigureAwait(false); Assert.Equal(cultureName, data); }