コード例 #1
0
    public void ChangeLanguage(string newLanguage)
    {
        Enum.TryParse(newLanguage, out LanguageTag language);
        currentLanguage = language;

        UpdateAllTexts();
    }
コード例 #2
0
        public void TestGrandfatheredValidation()
        {
            LanguageTag result = null;

            Assert.IsTrue(TagRegistry.TryParse("zh-xiang", out result));
            Assert.AreEqual("zh-xiang", result.Value, ignoreCase);
        }
コード例 #3
0
        public void TryParse(string text, char singleton, string[] subtags)
        {
            var pu1 = ExtensionSubtag.TryParse(text);

            Assert.IsTrue(pu1.HasValue);
            Assert.That(pu1 !.Value.Singleton, Is.EqualTo(singleton));
            Assert.That(pu1, Is.EquivalentTo(subtags));

            Assert.That(ExtensionSubtag.TryParse(text, out var pu2), Is.True);
            Assert.That(pu2.Singleton, Is.EqualTo(singleton));
            Assert.That(pu2, Is.EquivalentTo(subtags));

            Assert.That(pu1, Is.EqualTo(pu2));

            foreach (var language in TestContent.GetLanguages())
            {
                var languageTag = LanguageTag.TryParse($"{language}-{text}");
                Assert.IsNotNull(languageTag);

                if (singleton == 'x')
                {
                    Assert.AreEqual(
                        languageTag !.Value.PrivateUse,
                        new ExtensionSubtag(singleton, subtags));
                }
                else
                {
                    CollectionAssert.AreEqual(
                        languageTag !.Value.Extensions,
                        new[] { new ExtensionSubtag(singleton, subtags) });
                }
            }
        }
コード例 #4
0
        public void Constructor_Pr()
        {
            var tag      = new LanguageTag(new PrivateUseSubtags("aaa"));
            var expected = LanguageTag.Parse("x-aaa");

            Assert.That(tag, Is.EqualTo(expected));
        }
コード例 #5
0
        public void IsSubsetOf(string x, string y, bool expected)
        {
            var xTag = LanguageTag.Parse(x);
            var yTag = LanguageTag.Parse(y);

            Assert.That(xTag.IsSubsetOf(yTag), Is.EqualTo(expected));
        }
コード例 #6
0
        public void Operators(string xText, string operatorText, string yText, bool expected)
        {
            var x = LanguageTag.Parse(xText);
            var y = LanguageTag.Parse(yText);

            switch (operatorText)
            {
            case ">=":
                Assert.That(y.IsSubsetOf(x), Is.EqualTo(expected));
                break;

            case "<=":
                Assert.That(x.IsSubsetOf(y), Is.EqualTo(expected));
                break;

            case "==":
                Assert.That(x == y, Is.EqualTo(expected));
                break;

            case "!=":
                Assert.That(x != y, Is.EqualTo(expected));
                break;

            default:
                throw new ApplicationException("Invalid test case");
            }
        }
コード例 #7
0
        private void Awake()
        {
            defaultActor    = SubTag.DEFAULT;
            defaultLanguage = LanguageTag.English;

            mainTagXElement = new Dictionary <MainTag, XElement>();
        }
コード例 #8
0
        public void Playground()
        {
            var en = Language.EN;           // English language
            var zh = Language.ZH;           // Chinese language

            var latn = Script.Latn;         // Latin script
            var hans = Script.Hans;         // Han (Simplified variant)

            var tw = Region.TW;             // Taiwan, Province of China

            // tag zh-Hans-TW
            var tag1 = new LanguageTag(zh, hans, tw);

            // tag zh-Latn-TW-Pinyin
            var tag2 = new LanguageTag(zh, latn, tw, new [] { Variant.Pinyin });

            // tag en-US-x-twain
            var tag3 = new LanguageTag(en, Region.US, ExtensionSubtag.ForPrivateUse("twain"));

            // tag de-DE-u-co-phonebk
            var tag4 = new LanguageTag(Language.DE, Region.DE, new [] { new ExtensionSubtag('u', "co", "phonebk") });

            var tag5 = LanguageTag.Parse("ru");
            var tag6 = LanguageTag.Parse("zh-Hans-TW");
            var tag7 = LanguageTag.Parse("en-GB-scotland");

            Assert.True(tag1 == tag6);

            // zh-Hans-TW -> zh-Hans
            var tag8 = tag6.Take(LanguageTag.Field.Language | LanguageTag.Field.Script);

            // zh-Hans is subset of zh-Hans-TW
            Assert.True(tag8.IsSubsetOf(tag6));
        }
コード例 #9
0
ファイル: LogData.cs プロジェクト: XiupingWu/AxeMan
 private void Awake()
 {
     defaultLanguage = LanguageTag.English;
     errorMessage    = "INVALID";
     replaceActor    = "%ACTOR%";
     replaceTrap     = "%TRAP%";
 }
コード例 #10
0
        public void Constructor_Pr()
        {
            var tag      = new LanguageTag(new ExtensionSubtag('x', "aaa"));
            var expected = LanguageTag.Parse("x-aaa");

            Assert.That(tag, Is.EqualTo(expected));
        }
コード例 #11
0
        public static bool FallbackMode(LanguageTag languageTagInstance, string resourceKey,
                                        IReadOnlyDictionary <LanguageTag, ITranslateResource> resources, FallbackExperimenter experimenter)
        {
            if (resources.TryGetValue(languageTagInstance, out var resource) && resource.CanTranslate(resourceKey))
            {
                return(true);
            }

            var suitableTags = experimenter.GetSuitableTags(languageTagInstance).ToList();

            if (!suitableTags.Any())
            {
                return(false);
            }

            foreach (var tag in suitableTags)
            {
                if (resources.TryGetValue(tag, out resource) && resource.CanTranslate(resourceKey))
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #12
0
        public void CanBeCreatedFromRemoteFeedBurnerSource()
        {
            #region Constants

            var location = new Uri("http://feeds2.feedburner.com/oreilly/radar/atom");
            var document = XmlElement.Parse(location);
            Assert.IsNotNull(document);

            var          feed          = document.Root as IAtomFeed;
            const string generatorName = "Movable Type Pro 4.21-en";
            const string generatorUri  = "http://www.sixapart.com/movabletype/";

            var entry1ContentLang = LanguageTag.Parse("en");
            var entry1ContentBase = "http://radar.oreilly.com/";
            var entry1ContentType = AtomTextType.html;

            #endregion

            Assert.IsNotNull(feed);
            Assert.IsNotNull(feed.Id);
            Assert.IsNotNull(feed.Title);

            Assert.IsNotNull(feed.Generator);
            Assert.AreEqual(generatorName, feed.Generator.GeneratorName);
            Assert.AreEqual(generatorUri, feed.Generator.Uri.ToString());

            var entryCount = feed.Entries.Count();
            Assert.IsTrue(entryCount > 0);
            Assert.IsNotNull(feed.Entries.First().Content);
            Assert.AreEqual(entry1ContentLang, feed.Entries.First().Content.Lang);
            Assert.AreEqual(entry1ContentBase, feed.Entries.First().Content.BaseId.ToString());
            Assert.AreEqual(entry1ContentType, feed.Entries.First().Content.Type);
            Assert.IsTrue(feed.Links.Count() > 0);
        }
コード例 #13
0
        public void TestLanguageScriptRegionVariantValidation()
        {
            LanguageTag result = null;

            Assert.IsTrue(TagRegistry.TryParse("hy-Latn-IT-arevela", out result)); //Eastern Armenian written in Latin script, as used in Italy
            Assert.AreEqual("hy-Latn-IT-arevela", result.Value, ignoreCase);
        }
コード例 #14
0
ファイル: VariantTests.cs プロジェクト: ExM/NLanguageTag
        public void VariantCollectionCreate(string tagText)
        {
            var tag      = LanguageTag.Parse(tagText);
            var variants = VariantCollection.Create(tag.Language, tag.Script, tag.Variants);

            Assert.That(variants, Is.EqualTo(tag.Variants));
        }
コード例 #15
0
ファイル: VariantTests.cs プロジェクト: ExM/NLanguageTag
 public void VariantCollectionCreate(string tagText, Variant appendVariant)
 {
     Assert.Throws <FormatException>(() =>
     {
         var tag = LanguageTag.Parse(tagText);
         VariantCollection.Create(tag.Language, tag.Script, tag.Variants.Union(new [] { appendVariant }));
     });
 }
コード例 #16
0
 /// <summary>
 /// Equals
 /// </summary>
 /// <param name="other"></param>
 /// <returns></returns>
 public bool Equals(Text other)
 {
     return(LanguageTag != null && other.LanguageTag != null &&
            LanguageTag.Equals(other.LanguageTag) &&
            PackageKey == other.PackageKey &&
            OriginText == other.OriginText &&
            FormatingParameters.EqualsSupportsNull(other.FormatingParameters));
 }
コード例 #17
0
 /// <summary>
 /// Translate in anonymous
 /// </summary>
 /// <param name="languageTag"></param>
 /// <param name="resourceKey"></param>
 /// <param name="strategy"></param>
 /// <returns></returns>
 public virtual string AnonymousTranslate(LanguageTag languageTag, string resourceKey, AttemptStrategy strategy = AttemptStrategy.Fallback)
 {
     return(_translatePackages.TryGetValue(TranslationManager.HashOfAnonymousPackageKey, out var package)
         ? package.TryGetTranslateValue(languageTag, resourceKey, out var translateValue, strategy)
             ? translateValue
             : resourceKey
         : resourceKey);
 }
コード例 #18
0
 /// <summary>
 /// Translate
 /// </summary>
 /// <param name="languageTag"></param>
 /// <param name="packageKey"></param>
 /// <param name="resourceKey"></param>
 /// <param name="strategy"></param>
 /// <returns></returns>
 public virtual string Translate(LanguageTag languageTag, string packageKey, string resourceKey, AttemptStrategy strategy = AttemptStrategy.Fallback)
 {
     return(_translatePackages.TryGetValue(packageKey.GetHashCode(), out var package)
         ? package.TryGetTranslateValue(languageTag, resourceKey, out var translateValue, strategy)
             ? translateValue
             : string.Empty
         : string.Empty);
 }
コード例 #19
0
ファイル: Element.cs プロジェクト: windygu/alexandrialibrary
        protected ILanguageTag GetAttributeLanguageTag(string name)
        {
            var s = GetAttributeString(name);

            return(s != null?
                   LanguageTag.Parse(s)
                       : null);
        }
コード例 #20
0
        public void TryParse_Fail(string text)
        {
            Assert.That(LanguageTag.TryParse(text).HasValue, Is.False);

            var result = LanguageTag.TryParse(text, out var tag);

            Assert.That(result, Is.False);
            Assert.That(tag, Is.EqualTo(default(LanguageTag)));
        }
コード例 #21
0
        public void Constructor_LangExr()
        {
            var tag1     = new LanguageTag(Language.RU, new [] { new ExtensionSubtag('a', "aaa") });
            var tag2     = new LanguageTag(Language.RU, null, null, new Variant[] {}, new [] { new ExtensionSubtag('a', "aaa") }, new ExtensionSubtag());
            var expected = LanguageTag.Parse("ru-a-aaa");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #22
0
        public void Constructor_LangScrRegExrPr()
        {
            var tag1     = new LanguageTag(Language.RU, Script.Latn, Region.RU, new [] { new ExtensionSubtag('a', "aaa") }, ExtensionSubtag.ForPrivateUse("aaa"));
            var tag2     = new LanguageTag(Language.RU, Script.Latn, Region.RU, new Variant[] {}, new [] { new ExtensionSubtag('a', "aaa") }, ExtensionSubtag.ForPrivateUse("aaa"));
            var expected = LanguageTag.Parse("ru-Latn-RU-a-aaa-x-aaa");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #23
0
        public void Constructor_LangVar()
        {
            var tag1     = new LanguageTag(Language.RU, new [] { Variant.Petr1708 });
            var tag2     = new LanguageTag(Language.RU, null, null, new [] { Variant.Petr1708 }, new ExtensionSubtag[] {}, new ExtensionSubtag());
            var expected = LanguageTag.Parse("ru-Petr1708");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #24
0
        public void Constructor_LangScrVarPr()
        {
            var tag1     = new LanguageTag(Language.RU, Script.Latn, new [] { Variant.Petr1708 }, ExtensionSubtag.ForPrivateUse("aaa"));
            var tag2     = new LanguageTag(Language.RU, Script.Latn, null, new [] { Variant.Petr1708 }, new ExtensionSubtag[] {}, ExtensionSubtag.ForPrivateUse("aaa"));
            var expected = LanguageTag.Parse("ru-Latn-Petr1708-x-aaa");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #25
0
 public static bool StrictMode(LanguageTag languageTagInstance, string resourceKey,
                               IReadOnlyDictionary <LanguageTag, ITranslateResource> resources)
 {
     if (resources.TryGetValue(languageTagInstance, out var resource) && resource.CanTranslate(resourceKey))
     {
         return(true);
     }
     return(false);
 }
コード例 #26
0
        public void Constructor_LangScr()
        {
            var tag1     = new LanguageTag(Language.RU, Script.Latn);
            var tag2     = new LanguageTag(Language.RU, Script.Latn, null, new Variant[] {}, new ExtensionSubtag[] {}, new ExtensionSubtag());
            var expected = LanguageTag.Parse("ru-Latn");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #27
0
        public void Constructor_LangVarExrPr()
        {
            var tag1     = new LanguageTag(Language.RU, new [] { Variant.Petr1708 }, new [] { new ExtensionSubtag('a', "aaa") }, ExtensionSubtag.ForPrivateUse("aaa"));
            var tag2     = new LanguageTag(Language.RU, null, null, new [] { Variant.Petr1708 }, new [] { new ExtensionSubtag('a', "aaa") }, ExtensionSubtag.ForPrivateUse("aaa"));
            var expected = LanguageTag.Parse("ru-Petr1708-a-aaa-x-aaa");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #28
0
        public void Constructor_LangReg()
        {
            var tag1     = new LanguageTag(Language.RU, Region.RU);
            var tag2     = new LanguageTag(Language.RU, null, Region.RU, new Variant[] {}, new ExtensionSubtag[] {}, new ExtensionSubtag());
            var expected = LanguageTag.Parse("ru-RU");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #29
0
        public void Constructor_LangScrRegVarExr()
        {
            var tag1     = new LanguageTag(Language.RU, Script.Latn, Region.RU, new [] { Variant.Petr1708 }, new [] { new ExtensionSubtag('a', "aaa") });
            var tag2     = new LanguageTag(Language.RU, Script.Latn, Region.RU, new [] { Variant.Petr1708 }, new [] { new ExtensionSubtag('a', "aaa") }, new ExtensionSubtag());
            var expected = LanguageTag.Parse("ru-Latn-RU-Petr1708-a-aaa");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #30
0
        public void Constructor_LangPr()
        {
            var tag1     = new LanguageTag(Language.RU, ExtensionSubtag.ForPrivateUse("aaa"));
            var tag2     = new LanguageTag(Language.RU, null, null, new Variant[] {}, new ExtensionSubtag[] {}, ExtensionSubtag.ForPrivateUse("aaa"));
            var expected = LanguageTag.Parse("ru-x-aaa");

            Assert.That(tag1, Is.EqualTo(expected));
            Assert.That(tag2, Is.EqualTo(expected));
        }
コード例 #31
0
		/// <summary>
		/// Checks in first hand settings file, if not found there it checks file structure
		/// </summary>
		/// <returns>List of available languages</returns>
		public IEnumerable<Language> GetAvailableLanguages()
		{
			//todo: ideally we want to fill the other data in the Language object so this is usable by project incorporating i18n that they can simply lookup available languages. Maybe we even add a country property so that it's easier for projects to add corresponding flags.

			List<string> languages = _settings.AvailableLanguages.ToList();
			Language lang;
			List<Language> dirList = new List<Language>();


			//This means there was no languages from settings
			if (languages.Count == 0
                || (languages.Count == 1 && languages[0] == ""))
			{
				//We instead check for file structure
				DirectoryInfo di = new DirectoryInfo(GetAbsoluteLocaleDir());
				
				foreach (var dir in di.EnumerateDirectories().Select(x => x.Name))
				{
					try
					{
					    var lt = new LanguageTag(dir);
					    if (lt.CultureInfo == null)
					        throw new CultureNotFoundException(dir);
						lang = new Language
						{
						    LanguageShortTag = dir
						};
					    dirList.Add(lang);
					}
					catch (System.Globalization.CultureNotFoundException) 
					{ 
						//There is a directory in the locale directory that is not a valid culture so ignore it
					}
				}
			}
			else
			{
				//see if the desired language was one of the returned from settings
				foreach (var language in languages)
				{
					lang = new Language();
					lang.LanguageShortTag = language;
					dirList.Add(lang);
				}
			}

			return dirList;

		}
コード例 #32
0
 public virtual string GetText(string msgid, string msgcomment, LanguageItem[] languages, out LanguageTag o_langtag, int maxPasses = -1)
 {
     string s1;
     LanguageTag lt = LanguageMatching.MatchLists(
         languages,
         m_appLanguages.Values,
         msgid,
         null,
         out s1,
         maxPasses);
    //
     o_langtag = lt;
     if (lt.IsValid()) {
         return string.Format("{0}{1}{2}", prefix, msgid, suffix); }
     return null;
 }
コード例 #33
0
 public virtual string GetText(string msgid, string msgcomment, LanguageItem[] languages, out LanguageTag o_langtag, int maxPasses = -1)
 {
     string s1;
     LanguageTag lt = LanguageMatching.MatchLists(
         languages,
         m_appLanguages.Values,
         msgid,
         null,
         out s1,
         maxPasses);
    //
     o_langtag = lt;
     if (!lt.IsValid()) {
         return null; }
     if (this.msgid != msgid) {
         return null; }
     return msgstr;
 }
コード例 #34
0
        /// <summary>
        /// Wrapper around ITextLocalizer.GetText which is more resilient where the msgid
        /// passed may have been HtmlDecoded. Ref Issue #105 and #202.
        /// </summary>
        /// <param name="textLocalizer">Interface on text localizer object.</param>
        /// <param name="allowLookupWithHtmlDecodedMsgId">
        /// Controls whether a lookup will be attempted with HtmlDecoded-msgid should the first lookup with raw msgid fail.
        /// </param>
        /// <param name="msgid"><see cref="ITextLocalizer.GetText"/></param>
        /// <param name="msgcomment"><see cref="ITextLocalizer.GetText"/></param>
        /// <param name="languages"><see cref="ITextLocalizer.GetText"/></param>
        /// <param name="o_langtag"><see cref="ITextLocalizer.GetText"/></param>
        /// <param name="maxPasses"><see cref="ITextLocalizer.GetText"/></param>
        /// <returns><see cref="ITextLocalizer.GetText"/></returns>
        public static string GetText(
            this ITextLocalizer textLocalizer,
            bool allowLookupWithHtmlDecodedMsgId,
            string msgid, 
            string msgcomment, 
            LanguageItem[] languages, 
            out LanguageTag o_langtag,
            int maxPasses = -1)
        {
        // Lookup resource using canonical msgid with optional attempt with HtmlDecode of msgid.
        // 1. Try lookup with raw msgid as is.
        // 2. Failing that, if allowed, try lookup with HtmlDecoded msgid (ref Issue #105 and #202).
        // 3. Failing that, return the raw msgid.
        // See also unit test: NuggetLocalizer_can_process_nugget_htmlencoded.
        //
            string message;
           // 1.
			message = textLocalizer.GetText(
                msgid,
                msgcomment,
                languages,
                out o_langtag,
                maxPasses);
            if (message != null
                && message != msgid) { // <- message != msgid indicates message was found, and vice versa.
                return message; }
           // 2.
            if (allowLookupWithHtmlDecodedMsgId) {
                string msgIdHtmlDecoded = System.Web.HttpUtility.HtmlDecode(msgid);
    		    message = textLocalizer.GetText(
                    msgIdHtmlDecoded, 
                    System.Web.HttpUtility.HtmlDecode(msgcomment), 
                    languages,
                    out o_langtag,
                    maxPasses);
                if (message != null
                    && message != msgIdHtmlDecoded) { // <- message != msgIdHtmlDecoded indicates message was found, and vice versa.
                    return message; }
            }
           // 3.
            return msgid;
        }
コード例 #35
0
ファイル: TextLocalizer.cs プロジェクト: ajbeaven/i18n
 public virtual string GetText(string msgid, string msgcomment, LanguageItem[] languages, out LanguageTag o_langtag, int maxPasses = -1)
 {
     // Validate arguments.
     if (maxPasses > (int)LanguageTag.MatchGrade._MaxMatch +1) { 
         maxPasses = (int)LanguageTag.MatchGrade._MaxMatch +1; }
     // Init.
     bool fallbackOnDefault = maxPasses == (int)LanguageTag.MatchGrade._MaxMatch +1
         || maxPasses == -1;
     // Determine the key for the msg lookup. This may be either msgid or msgid+msgcomment, depending on the prevalent
     // MessageContextEnabledFromComment setting.
     string msgkey = msgid == null ? 
         msgid:
         TemplateItem.KeyFromMsgidAndComment(msgid, msgcomment, _settings.MessageContextEnabledFromComment);
     // Perform language matching based on UserLanguages, AppLanguages, and presence of
     // resource under msgid for any particular AppLanguage.
     string text;
     o_langtag = LanguageMatching.MatchLists(
         languages, 
         GetAppLanguages().Values, 
         msgkey, 
         TryGetTextFor, 
         out text, 
         Math.Min(maxPasses, (int)LanguageTag.MatchGrade._MaxMatch));
     // If match was successfull
     if (text != null) {
         // If the msgkey was returned...don't output that but rather the msgid as the msgkey
         // may be msgid+msgcomment.
         if (text == msgkey) {
             return msgid; }                
         return text;
     }
     // Optionally try default language.
     if (fallbackOnDefault)
     {
         o_langtag = LocalizedApplication.Current.DefaultLanguageTag;
         return msgid;
     }
     //
     return null;
 }
コード例 #36
0
ファイル: LocaleDetail.ascx.cs プロジェクト: jaytem/minGit
    /// <summary>
    /// Override OnPreRender to build the page sections
    /// </summary>
    /// <param name="e">The event arguments</param>
    protected override void OnPreRender(EventArgs e)
    {
        this.userLang = System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
        this.msgSelectPrompt = GetMessage("lbl first display text on choices option");

        this.isAssumedRegion = false;

        if (this.Locale != null)
        {
            hdnState.Value = this.Locale.LanguageState.ToString();
            hdnLocaleId.Value = this.Locale.Id.ToString();
            chkIsRightToLeft.Checked = this.Locale.IsRightToLeft;
            this.selectedLanguage = this.Locale.LangCode;
            this.selectedLanguageTag = new LanguageTag(this.Locale.XmlLang);

            if (!String.IsNullOrEmpty(this.selectedLanguage) && !this.selectedLanguage.Contains("-"))
            {
                string strLikelyTag = this.GetLikelyTag(this.selectedLanguage);
                LanguageTag likelyTag = new LanguageTag(strLikelyTag);
                this.isAssumedRegion = likelyTag.RegionSubtag == this.selectedLanguageTag.RegionSubtag;
            }

            if (this.likelyLanguageTag != null)
            {
                if (this.likelyLanguageTag.ScriptSubtag == this.selectedLanguageTag.ScriptSubtag &&
                    this.likelyLanguageTag.RegionSubtag == this.selectedLanguageTag.RegionSubtag)
                {
                    this.selectedLanguageTag.ScriptSubtag = string.Empty;
                }
            }
        }
        else
        {
            hdnState.Value = LocalizationLanguageState.Active.ToString();
            hdnLocaleId.Value = "-1";
            chkIsRightToLeft.Checked = false;
            this.selectedLanguage = string.Empty;
            this.selectedLanguageTag = new LanguageTag();
        }

        this.selectedLanguageTag.RegistryUri = new Uri(Request.Url, "language-subtag-registry.xml");

        string cldrMainXmlRelPath = String.Format("CLDR/common/main/{0}.xml", this.userLang);
        if (!System.IO.File.Exists(MapPath(cldrMainXmlRelPath)))
        {
            cldrMainXmlRelPath = "CLDR/common/main/en.xml";
        }

        string cldrMainXmlPath = new Uri(Request.Url, cldrMainXmlRelPath).AbsoluteUri;

        this.BuildLanguageSection(cldrMainXmlPath);
        this.BuildRegionSection(cldrMainXmlPath);
        this.BuildLocaleSection();
        this.BuildFallbackSection();
        this.BuildLanguageTagSection(cldrMainXmlPath);
        this.BuildCultureSections();
        this.BuildFlagSection();
        this.BuildDisplayNameSections();

        base.OnPreRender(e);
    }
コード例 #37
0
ファイル: LanguageMatching.cs プロジェクト: neo725/i18n
        /// <summary>
        /// Given a list of user-preferred languages (in order of precedence) and the list of languages
        /// in which an arbitrary resource is available (AppLanguages), returns the AppLanguage which
        /// the user is most likely able to understand.
        /// </summary>
        /// <param name="UserLanguages">
        /// A list of user-preferred languages (in order of precedence).
        /// </param>
        /// <param name="AppLanguages">
        /// The list of languages in which an arbitrary resource is available.
        /// </param>
        /// <param name="key">
        /// Optionally specifies the key or a message to be looked up in order to validate
        /// a language selection. Only if the language passes the validation will it be selected.
        /// Set in conjunction with TryGetTextFor.
        /// May be null (while TryGetTextFor is non-null) which specifies that one or more messages 
        /// must exists for a language for it to be considered valid (PO-valid).
        /// </param>
        /// <param name="TryGetTextFor">
        /// Optional delegate to be called in order to validate a language for selection.
        /// See TextLocalizer.TryGetTextFor for more details.
        /// </param>
        /// <param name="o_text">
        /// When language validation is enabled (TryGetTextFor is non-null) outputs the translated
        /// text that was returned by TryGetTextFor when the language was validated.
        /// If key == null then this will be set to "".
        /// </param>
        /// <param name="maxPasses">
        /// 0 - allow exact match only
        /// 1 - allow exact match or default-region match only
        /// 2 - allow exact match or default-region match or script match only
        /// 3 - allow exact match or default-region match or script match or language match only
        /// -1 to set to most tolerant (i.e. 4).
        /// </param>
        /// <param name="relatedTo">
        /// Optionally applies a filter to the user languages considered for a match.
        /// When set, then only user languages that have a matching language to that of relatedTo
        /// are considered.
        /// </param>
        /// <param name="palPrioritization">
        /// Indicates whether PAL Prioritization is enabled.
        /// </param>
        /// <returns>
        /// LanguageTag instance selected from AppLanguages with the best match, or null if there is no match
        /// at all (or UserLanguages and/or AppLanguages is empty).
        /// It is possible for there to be no match at all if no language subtag in the UserLanguages tags
        /// matches the same of any of the tags in AppLanguages list.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">Thrown if UserLanguages or AppLanguages is null.</exception>
        /// <remarks>
        /// This method called many times per request. Every effort taken to avoid it making any heap allocations.<br/>
        /// <br/>
        /// Principle Application Language (PAL) Prioritization:<br/>
        ///   User has selected an explicit language in the webapp e.g. fr-CH (i.e. PAL is set to fr-CH).
        ///   Their browser is set to languages en-US, zh-Hans.
        ///   Therefore, UserLanguages[] equals fr-CH, en-US, zh-Hans.
        ///   We don't have a particular message in fr-CH, but have it in fr and fr-CA.
        ///   We also have message in en-US and zh-Hans.
        ///   We presume the message from fr or fr-CA is better match than en-US or zh-Hans.
        ///   However, without PAL prioritization, en-US is returned and failing that, zh-Hans.
        ///   Therefore, for the 1st entry in UserLanguages (i.e. explicit user selection in app)
        ///   we try all match grades first. Only if there is no match whatsoever for the PAL
        ///   do we move no to the other (browser) languages, where return to prioritizing match grade
        ///   i.e. loop through all the languages first at the strictest match grade before loosening 
        ///   to the next match grade, and so on.
        /// Refinement to PAL Prioritization:<br/>
        ///   UserLanguages (UL) = de-ch,de-at (PAL = de-ch)<br/>
        ///   AppLanguages  (AL) = de,de-at,en<br/>
        ///   There is no exact match for PAL in AppLanguages.<br/>
        ///   However:<br/>
        ///    1. the second UL (de-at) has an exact match with an AL<br/>
        ///    2. the parent of the PAL (de) has an exact match with an AL.<br/>
        ///   Normally, PAL Prioritization means that 2. takes precedence.
        ///   However, that means choosing de over de-at, when the user
        ///   has said they understand de-at (it being preferable to be
        ///   more specific, esp. in the case of different scripts under 
        ///   the same language).<br/>
        ///   Therefore, as a refinement to PAL Prioritization, before selecting
        ///   'de' we run the full algorithm again (without PAL Prioritization) 
        ///   but only considering langtags related to the PAL.
        /// </remarks>
        public static LanguageTag MatchLists(
            LanguageItem[] UserLanguages, 
            IEnumerable<LanguageTag> AppLanguages,
            string key,
            Func<string, string, string> TryGetTextFor,
            out string o_text,
            int maxPasses = -1,
            LanguageTag relatedTo = null,
            bool palPrioritization = true)
        {
            int idxUserLang = 0;
            LanguageTag ltUser;
           // Validate arguments.
            if (UserLanguages == null) { throw new ArgumentNullException("UserLanguages"); }
            if (AppLanguages == null) { throw new ArgumentNullException("AppLanguages"); }
            if (maxPasses > (int)LanguageTag.MatchGrade._MaxMatch) {
                maxPasses = (int)LanguageTag.MatchGrade._MaxMatch; }

            //#78
            //if (key != null && key.Equals("Sign In", StringComparison.InvariantCultureIgnoreCase)) {
            //    key = key; }

           // If one or more UserLanguages determined for the current request
            if (UserLanguages.Length != 0) {
               // First, find any match for the PAL (see PAL Prioritization notes above).
               // If a PAL has been determined for the request
                if (palPrioritization
                    && (ltUser = (LanguageTag)UserLanguages[0].LanguageTag) != null
                    && (relatedTo == null || ltUser.Match(relatedTo, LanguageTag.MatchGrade.LanguageMatch) != 0)) { // Apply any filter on eligible user languages.
                   // Wiz through all match grades for the Principle Application Language.
                    for (int pass = 0; pass <= (int)LanguageTag.MatchGrade._MaxMatch; ++pass) {
                        LanguageTag.MatchGrade matchGrade = (LanguageTag.MatchGrade)pass;
                        foreach (LanguageTag langApp in AppLanguages) {
                           // If languages do not match at the current grade...goto next.
                            if (ltUser.Match(langApp, matchGrade) == 0) {
                                continue; }
                           // Optionally test for a resource of the given key in the matching language.
                            if (TryGetTextFor != null) {
                                o_text = TryGetTextFor(langApp.ToString(), key);
                                if (o_text == null) {
                                    continue; }
                            }
                            else {
                                o_text = null; }
                           // We have a match between PAL and an AL that is NOT an exact match, 
                           // there may be a UL that is related to the PAL but has a closer (more specific) 
                           // match to an AL. See "Refinement to PAL Prioritization" notes above for more details.
                            if (matchGrade != LanguageTag.MatchGrade.ExactMatch) {

                                LanguageTag lt = MatchLists(
                                    UserLanguages, 
                                    AppLanguages,
                                    key,
                                    TryGetTextFor,
                                    out o_text,
                                    maxPasses,
                                    langApp,
                                    false); // false = disable PAL Prioritization.
                                if (lt != null) {
                                    return lt; }
                            }
                           // Match.
                            ++UserLanguages[idxUserLang].UseCount;
                            return langApp;
                        }
                    }
                }
               // PAL didn't match so skip over that now.
                ++idxUserLang;
               // No match for PAL, so now try for the browser languages, this time prioritizing the
               // match grade.
                for (int pass = 0; pass <= (int)LanguageTag.MatchGrade._MaxMatch; ++pass) {
                    LanguageTag.MatchGrade matchGrade = (LanguageTag.MatchGrade)pass;
                    for (int i = idxUserLang; i < UserLanguages.Length; ++i) {
                        ltUser = (LanguageTag)UserLanguages[i].LanguageTag;
                        if (ltUser == null) {
                            continue; }
                            // TODO: move the Match functionality to this class, and make it operate on ILanguageTag.
                            // Or consider making the Match logic more abstract, e.g. requesting number of passes from
                            // the object, and passing a pass value through to Match.
                       // Apply any filter on eligible user languages.
                        if (relatedTo != null) {
                            if (ltUser.Match(relatedTo, LanguageTag.MatchGrade.LanguageMatch) == 0) {
                                continue; }
                        }
                        foreach (LanguageTag langApp in AppLanguages) {
                           // If languages do not match at the current grade...goto next.
                            if (ltUser.Match(langApp, matchGrade) == 0) {
                                continue; }
                           // Optionally test for a resource of the given key in the matching language.
                            if (TryGetTextFor != null) {
                                o_text = TryGetTextFor(langApp.ToString(), key);
                                if (o_text == null) {
                                    continue; }
                            }
                            else {
                                o_text = null; }
                           // Match.
                            ++UserLanguages[i].UseCount;
                            return langApp;
                        }
                    }
                }
            }
           // No match at all.
            o_text = null;
            return null;
        }
コード例 #38
0
ファイル: LocaleDetail.ascx.cs プロジェクト: jaytem/minGit
    /// <summary>
    /// Page load to handle post back and more
    /// </summary>
    /// <param name="sender">the page object</param>
    /// <param name="e">The event arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            string language = this.Request.Form["Language"];
            if (language != null)
            {
                string scriptSubtag = this.Request.Form["ScriptSubtag"];
                string regionSubtag = this.Request.Form["Territory"];
                string likelyLanguageTag = this.Request.Form["LikelyLanguageTag"];
                if (!String.IsNullOrEmpty(likelyLanguageTag))
                {
                    this.likelyLanguageTag = new LanguageTag(likelyLanguageTag);
                }

                string loc = txtLoc.Text;

                int id = -1;
                Int32.TryParse(hdnLocaleId.Value, out id);

                int fallbackId = 0;
                Int32.TryParse(lstFallbackLoc.SelectedValue, out fallbackId);

                string privateUseSubtag = txtPrivateUseSubtag.Text.Trim();

                LanguageTag objLangTag = new LanguageTag(language, scriptSubtag, regionSubtag, privateUseSubtag);
                objLangTag.RegistryUri = new Uri(Request.Url, "language-subtag-registry.xml");
                string languageTag = objLangTag.ToString();

                string culture = lstCulture.SelectedValue;
                string uiCulture = lstUICulture.SelectedValue;

                int lcid = 1033;
                System.Globalization.CultureInfo info = System.Globalization.CultureInfo.GetCultureInfo(uiCulture);
                if (info != null)
                {
                    lcid = info.LCID;
                }

                string flagFile = rblFlag.SelectedValue;
                string flagUrl = CommonApi.AppImgPath + "flags/" + flagFile;

                string nativeName = txtNativeName.Text;
                string englishName = txtEnglishName.Text;

                bool isRightToLeft = chkIsRightToLeft.Checked;

                LocalizationLanguageState localeState = LocalizationLanguageState.Active;
                if (Enum.IsDefined(typeof(LocalizationLanguageState), hdnState.Value))
                {
                    localeState = (LocalizationLanguageState)Enum.Parse(typeof(LocalizationLanguageState), hdnState.Value);
                    if (LocalizationLanguageState.Defined == localeState)
                    {
                        localeState = LocalizationLanguageState.Active;
                    }
                }

                this.Locale = new LocaleData(id, lcid, englishName, nativeName, isRightToLeft, loc, culture, uiCulture, language, languageTag, flagFile, flagUrl, fallbackId, localeState);
            }
        }
        else
        {
            LanguageDesc.Text = String.Format(LanguageDesc.Text, this.GetDateOfCLDR());
            System.Text.StringBuilder bcp47HyperlinkMarkup = new System.Text.StringBuilder();
            using (HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter(bcp47HyperlinkMarkup)))
            {
                BCP47.RenderControl(writer);
            }

            BCP47.Visible = false;
            System.Text.StringBuilder rfc5646HyperlinkMarkup = new System.Text.StringBuilder();
            using (HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter(rfc5646HyperlinkMarkup)))
            {
                RFC5646.RenderControl(writer);
            }

            RFC5646.Visible = false;
            XmlLangDescP1.Text = String.Format(XmlLangDescP1.Text, bcp47HyperlinkMarkup.ToString(), rfc5646HyperlinkMarkup.ToString());

            Ektron.Cms.BusinessObjects.Localization.L10nManager l10nMgr = new Ektron.Cms.BusinessObjects.Localization.L10nManager(this.CommonApi.RequestInformationRef);
            MachineTranslationUndefinedPanel.Visible = !l10nMgr.IsMachineTranslationSupported;
            PseudoLocalizationUndefinedPanel.Visible = !l10nMgr.IsPseudoLocalizationSupported;
        }
    }