示例#1
0
        protected override object AddNewCore()
        {
            ILanguageItem item1 = new LanguageItem();

            base.Add(item1);
            return(item1);
        }
示例#2
0
        public async Task TestRetrieveWords()
        {
            using (var context = new LanguageAPIContext(options))
            {
                //Given
                LanguageItem languageItem1 = new LanguageItem()
                {
                    userId       = 1,
                    rank         = 1,
                    languageName = "Chinese (Simplified)",
                    languageCode = "zh-CN",
                    word         = "球"
                };
                LanguageItem languageItem2 = new LanguageItem()
                {
                    userId       = 1,
                    rank         = 2,
                    languageName = "Chinese (Simplified)",
                    languageCode = "zh-CN",
                    word         = "帽子"
                };

                //When
                LanguageItemsController languageItemsController = new LanguageItemsController(context);
                IActionResult           result = await languageItemsController.RetrieveFavouriteWords(languageItem1.userId, languageItem1.languageName);

                //Then
                Assert.IsInstanceOfType(result, typeof(OkObjectResult));
                Assert.IsNotNull(result);

                var checkResponse = result as OkObjectResult;
                Assert.IsNotNull(checkResponse);

                var languageItems = checkResponse.Value as List <LanguageItem>;
                for (var i = 0; i < languageItems.Count; i++)
                {
                    bool matchFound = false;
                    for (var j = 0; j < languageItems.Count; j++)
                    {
                        if (languageItems[i].languageName == languageItemList[j].languageName)
                        {
                            matchFound = true;
                        }
                        if (languageItems[i].languageCode == languageItemList[j].languageCode)
                        {
                            matchFound = true;
                        }
                        if (languageItems[i].rank == languageItemList[j].rank)
                        {
                            matchFound = true;
                        }
                        if (languageItems[i].word == languageItemList[j].word)
                        {
                            matchFound = true;
                        }
                    }
                    Assert.IsTrue(matchFound);
                }
            }
        }
示例#3
0
        public ActionResult Clone([Bind(Include = "LanguageID,LanguageName,LanguageTwoLetters,LanguageThreeLetters")] Language language)
        {
            if (ModelState.IsValid)
            {
                //Get old ID
                int oldID = language.LanguageID;

                var entries = from e in db.LanguageItems where e.LanguageID == oldID select e;

                db.Languages.Add(language);
                db.SaveChanges();
                int NewID = language.LanguageID;


                foreach (var Item in entries)

                {
                    LanguageItem LanguageItems = new LanguageItem();
                    LanguageItems.LanguageID        = NewID;
                    LanguageItems.LanguageItemKey   = Item.LanguageItemKey;
                    LanguageItems.LanguageItemValue = Item.LanguageItemValue;
                    db.LanguageItems.Add(LanguageItems);
                }
                ;

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(language));
        }
示例#4
0
        public async Task TestAddFavouriteWord()
        {
            using (var context = new LanguageAPIContext(options))
            {
                //Given
                LanguageItem languageItem = new LanguageItem()
                {
                    userId       = 1,
                    rank         = 3,
                    languageName = "English",
                    languageCode = "en",
                    word         = "Amazing"
                };
                //When
                LanguageItemsController languageItemsController = new LanguageItemsController(context);
                IActionResult           result = await languageItemsController.AddFavouriteWord(languageItem) as IActionResult;

                //Then
                Assert.IsNotNull(result);
                Assert.IsInstanceOfType(result, typeof(CreatedAtActionResult));

                var exists = await context.LanguageItem.Where(l =>
                                                              l.userId == languageItem.userId &&
                                                              l.rank == languageItem.rank &&
                                                              l.languageName == languageItem.languageName &&
                                                              l.languageCode == languageItem.languageCode &&
                                                              l.word == languageItem.word
                                                              ).AnyAsync();

                Assert.IsNotNull(exists);
                Assert.IsTrue(exists);
            }
        }
示例#5
0
 public void SetupDb()
 {
     using (var context = new LanguageAPIContext(options))
     {
         LanguageItem languageItem1 = new LanguageItem()
         {
             userId       = 1,
             rank         = 1,
             languageName = "Chinese (Simplified)",
             languageCode = "zh-CN",
             word         = "球"
         };
         LanguageItem languageItem2 = new LanguageItem()
         {
             userId       = 1,
             rank         = 2,
             languageName = "Chinese (Simplified)",
             languageCode = "zh-CN",
             word         = "帽子"
         };
         context.LanguageItem.Add(languageItem1);
         context.LanguageItem.Add(languageItem2);
         context.SaveChanges();
     }
 }
示例#6
0
    private void CreateNewFile(LanguageItem language, bool showExistsDialog = false)
    {
        string path = localizationDir + "/strings_" + language.Abbr + ".json";

        if (File.Exists(path))
        {
            return;
        }

        string[] files = Directory.GetFiles(localizationDir, "*.json");
        if (files.Length == 0)
        {
            File.WriteAllText(path, "{\"items\":[]}");
            return;
        }

        //проверяем есть ли русская локализация, если есть, то делаем ее копию для нового файла
        if (File.Exists(localizationDir + "/strings_ru.json"))
        {
            File.Copy(localizationDir + "/strings_ru.json", path);
        }
        else
        {
            File.Copy(files[0], path);
        }
    }
        public IActionResult Item(string id, [FromBody] JsonPatchDocument <LangItem> langItemPatch)
        {
            try
            {
                if (Guid.TryParse(id, out Guid parsedId))
                {
                    //var userId = User.FindFirstValue("sub");

                    LanguageItem languageItem = _unitOfWork.LanguageItems.Get(parsedId);

                    LangItem langItem = _mapper.Map <LangItem>(languageItem);

                    langItemPatch.ApplyTo(langItem);

                    _mapper.Map(langItem, languageItem);

                    _unitOfWork.Complete();

                    return(CreatedAtRoute("Item", new { id = _mapper.Map <LangItem>(languageItem).Id }, _mapper.Map <LangItem>(languageItem)));
                }
            }
            catch (Exception e)
            {
                string message = e.Message;
            }

            return(BadRequest());
        }
示例#8
0
 private void EditValue(string iLanguageKeyId)
 {
     //Nếu key language chưa có giá trị
     if (SetCountItem(iLanguageKeyId).Equals("0"))
     {
         for (int i = 0; i <= RpListLanguageNationals.Items.Count - 1; i++)
         {
             TextBox tbTitle = (TextBox)RpListLanguageNationals.Items[i].FindControl(("TbLanguageWord"));
             string  value   = tbTitle.Text.Replace("'", "''");
             if (tbTitle.ToolTip.Equals(iLanguageKeyId))
             {
                 LanguageItem.InsertLanguageItem(language, iLanguageKeyId, value, "", "");
             }
         }
     }
     else //Nếu key language có giá trị rồi
     {
         for (int i = 0; i <= RpListLanguageNationals.Items.Count - 1; i++)
         {
             TextBox tbTitle = (TextBox)RpListLanguageNationals.Items[i].FindControl(("TbLanguageWord"));
             string  value   = tbTitle.Text.Replace("'", "''");
             if (tbTitle.ToolTip.Equals(iLanguageKeyId))
             {
                 string[] fields    = { "nLanguageItemTitle" };
                 string[] values    = { "N'" + value + "'" };
                 string   condition = DataExtension.AndConditon(LanguageItemTSql.GetByiLanguageKeyId(iLanguageKeyId),
                                                                LanguageItemTSql.GetByiLanguageNationalId(language));
                 LanguageItem.UpdateLanguageItem(DataExtension.UpdateTransfer(fields, values), condition);
             }
         }
     }
 }
示例#9
0
    /// <summary>
    /// 刷新自身显示(增加语言需要修改)
    /// </summary>
    /// <param name="last"></param>
    /// <param name="type"></param>
    private void ReflashByLanguage(LanguageType last, LanguageType type)
    {
        LanguageItem item = null;

        if (langImage != null)
        {
            item = LanguageManager.instance.GetItemByString(last, langImage.sprite.name);
            if (item == null)
            {
                Debug.LogError("E该图片的语言版本信息未找到:" + name + "/" + langImage.sprite.name);
                return;
            }
            string info   = LanguageManager.GetInfoByType(item, type);
            string spName = DataController.iconPathSkill + info;
            langImage.sprite = Resources.Load(spName, typeof(Sprite)) as Sprite;
            langImage.SetNativeSize();
        }
        else if (langText != null)
        {
            if (string.IsNullOrEmpty(langText.text))
            {
                return;
            }
            item = LanguageManager.instance.GetItemByString(last, langText.text);
            if (item == null)
            {
                Debug.LogError("E该文字的语言版本信息未找到:" + name + "/" + langText.text);
                return;
            }
            string info = LanguageManager.GetInfoByType(item, type);
            langText.text = info;
        }
    }
示例#10
0
        public void LanguageItem_JustToCoverability_Test()
        {
            // arrange
            LanguageItem languageItem  = new LanguageItem();
            string       Name          = "";
            int          TotalStars    = 0;
            int          TotalProjects = 0;
            List <Item>  Items         = new List <Item>();

            // Act
            // Set.
            languageItem.Name          = Name;
            languageItem.TotalStars    = TotalStars;
            languageItem.TotalProjects = TotalProjects;
            languageItem.Items         = Items;
            // Get.
            Name          = languageItem.Name;
            TotalStars    = languageItem.TotalStars;
            TotalProjects = languageItem.TotalProjects;
            Items         = languageItem.Items;

            // Assert
            Assert.IsTrue(languageItem.Name == Name ||
                          languageItem.TotalStars == TotalStars ||
                          languageItem.TotalProjects == TotalProjects ||
                          languageItem.Items == Items);
        }
示例#11
0
    protected string GetImageItem(string iLanguageKeyId)
    {
        top       = "1";
        fields    = LanguageItemColumns.nLanguageItemParams;;
        condition = DataExtension.AndConditon(LanguageItemTSql.GetByiLanguageKeyId(iLanguageKeyId),
                                              LanguageItemTSql.GetByiLanguageNationalId(language));
        order = "";
        DataTable dt = new DataTable();

        dt = LanguageItem.GetLanguageItem(top, fields, condition, order);
        string s = "";

        if (dt.Rows.Count > 0)
        {
            if (dt.Rows[0][LanguageItemColumns.nLanguageItemParams].ToString().Length > 0)
            {
                s = "<img src='" + UrlExtension.WebisteUrl + FolderPic.Language + "/" + dt.Rows[0][LanguageItemColumns.nLanguageItemParams].ToString() + "' class='anhtukhoa' id='img" + iLanguageKeyId + "'/>";
            }
            else
            {
                s = "<img src='" + UrlExtension.WebisteUrl + "pic/icon/no_image.gif' class='anhtukhoa' id='img" + iLanguageKeyId + "'/>";
            }
        }
        else
        {
            s = "<img src='" + UrlExtension.WebisteUrl + "pic/icon/no_image.gif' class='anhtukhoa' id='img" + iLanguageKeyId + "'/>";
        }
        return(s);
    }
示例#12
0
        public BaseLanguageItem AddLanguage(Int32 idLanguage, String codeLanguage)
        {
            BaseLanguageItem item = null;

            if (UserContext.isAnonymous)
            {
                View.DisplaySessionTimeout();
            }
            else
            {
                List <BaseLanguageItem> languages  = View.AvailableLanguages;
                List <LanguageItem>     inUseItems = View.InUseLanguages;
                item = languages.Where(l => l.Id == idLanguage && l.Code == codeLanguage).FirstOrDefault();
                if (item != null)
                {
                    LanguageItem current = new LanguageItem(item);
                    current.IsSelected = true;
                    if (!inUseItems.Where(i => i.Id == current.Id && i.IsMultiLanguage == current.IsMultiLanguage && i.Code == current.Code).Any())
                    {
                        inUseItems.Add(current);
                    }
                    LoadItems(languages, inUseItems, current);
                }
            }
            return(item);
        }
        public static Dictionary <string, LanguageItem> ListVoiceLanguages(Grpc.Core.Channel channel)
        {
            TextToSpeechClient client = TextToSpeechClient.Create(channel);

            Dictionary <string, LanguageItem> languages = new Dictionary <string, LanguageItem>();
            // Performs the list voices request
            var response = client.ListVoices(new ListVoicesRequest {
            });

            foreach (Voice voice in response.Voices)
            {
                foreach (var languageCode in voice.LanguageCodes)
                {
                    if (!languages.ContainsKey(languageCode.ToString()))
                    {
                        string       displayName = languageCode + " | " + new CultureInfo($"{languageCode}").DisplayName;
                        LanguageItem newItem     = new LanguageItem
                        {
                            Text = displayName,
                            Id   = languageCode
                        };

                        languages.Add(languageCode, newItem);
                    }
                }
            }
            return(languages);
        }
示例#14
0
        public LanguageItem SelectLanguage(Int32 idLanguage, String codeLanguage)
        {
            LanguageItem item = null;

            if (UserContext.isAnonymous)
            {
                View.DisplaySessionTimeout();
            }
            else
            {
                List <LanguageItem> inUseItems = View.InUseLanguages;
                item = inUseItems.Where(l => l.Id == idLanguage && l.Code == codeLanguage).FirstOrDefault();
                if (item != null)
                {
                    inUseItems.ForEach(i => i.IsSelected = false);
                    LanguageItem current = item;
                    current.IsSelected  = true;
                    inUseItems          = inUseItems.OrderByDescending(i => i.IsMultiLanguage).ThenBy(i => i.Name).ToList();
                    View.SelectedItem   = current;
                    View.InUseLanguages = inUseItems;
                    View.LoadItems(inUseItems);
                }
            }
            return(item);
        }
示例#15
0
        public LanguageItem RemoveCurrent(LanguageItem current)
        {
            List <BaseLanguageItem> availableLanguages = View.AvailableLanguages;
            List <LanguageItem>     inUseItems         = View.InUseLanguages;
            Int32 index = (inUseItems == null) ? -1 : inUseItems.Select(i => i.Code).ToList().IndexOf(current.Code);

            if (index == 0 && inUseItems.Count == 1)
            {
                current    = null;
                inUseItems = new List <LanguageItem>();
            }
            else if (index == 0 && inUseItems.Count > 1)
            {
                current = inUseItems[1];
                inUseItems.RemoveAt(0);
            }
            else if (inUseItems.Count > 1 && index > -1)
            {
                current = inUseItems[index - 1];
                inUseItems.RemoveAt(index);
            }

            LoadItems(availableLanguages, inUseItems, current);
            return(current);
        }
        private CompletionDataList GetMembersOfItem(string itemFullName)
        {
            CProject project = Document.Project as CProject;

            if (project == null)
            {
                return(null);
            }

            ProjectInformation info = ProjectInformationManager.Instance.Get(project);
            CompletionDataList list = new CompletionDataList();

            LanguageItem container = null;

            string currentFileName = Document.FileName;
            bool   in_project      = false;

            foreach (LanguageItem li in info.Containers())
            {
                if (itemFullName == li.FullName)
                {
                    container  = li;
                    in_project = true;
                }
            }

            if (!in_project && info.IncludedFiles.ContainsKey(currentFileName))
            {
                foreach (CBinding.Parser.FileInformation fi in info.IncludedFiles[currentFileName])
                {
                    foreach (LanguageItem li in fi.Containers())
                    {
                        if (itemFullName == li.FullName)
                        {
                            container = li;
                        }
                    }
                }
            }

            if (container == null)
            {
                return(null);
            }

            if (in_project)
            {
                AddItemsWithParent(list, info.AllItems(), container);
            }
            else
            {
                foreach (CBinding.Parser.FileInformation fi in info.IncludedFiles[currentFileName])
                {
                    AddItemsWithParent(list, fi.AllItems(), container);
                }
            }

            return(list);
        }
示例#17
0
        /// <summary>
        /// Set values of Language
        /// </summary>
        /// <param name="fileName">*.igLang path</param>
        public Language(string fileName)
        {
            _Items = new LanguageItem<string, string>();
            InitDefaultLanguageDictionary();

            _fileName = fileName;
            ReadLanguageFile();
        }
        public ActionResult DeleteConfirmed(int id)
        {
            LanguageItem languageitem = db.LanguageItems.Find(id);

            db.LanguageItems.Remove(languageitem);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        // GET: /LanguateItems/Create
        public ActionResult Create()
        {
            ViewBag.LanguageID = new SelectList(db.Languages, "LanguageID", "LanguageName");
            LanguageItem model = new LanguageItem();

            model = (LanguageItem)Helpers.TableTracker.TrackCreate(model, User.Identity.Name);
            return(View(model));
        }
示例#20
0
        private string LoadLangList(string xmlFile)
        {
            try
            {
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(xmlFile);

                XmlNode xroot = xdoc.DocumentElement;
                _defaultLang = xroot.Attributes.GetNamedItem("default").Value;

                _serverLangList = new Hashtable();
                XmlNodeList xserverlist = xroot.SelectNodes("server");
                foreach (XmlNode xserver in xserverlist)
                {
                    string    serverType     = xserver.Attributes.GetNamedItem("type").Value;
                    Hashtable serverItemList = null;
                    if (_serverLangList.Contains(serverType))
                    {
                        serverItemList = _serverLangList[serverType] as Hashtable;
                    }
                    else
                    {
                        serverItemList = new Hashtable();
                        _serverLangList[serverType] = serverItemList;
                    }

                    XmlNodeList xitemlist = xserver.SelectNodes("item");
                    foreach (XmlNode xitem in xitemlist)
                    {
                        string       itemId   = xitem.Attributes.GetNamedItem("id").Value;
                        LanguageItem langItem = null;
                        if (serverItemList.Contains(itemId))
                        {
                            langItem = serverItemList[itemId] as LanguageItem;
                        }
                        else
                        {
                            langItem = new LanguageItem();
                            serverItemList.Add(itemId, langItem);
                        }

                        XmlNodeList xmessagelist = xitem.SelectNodes("message");
                        foreach (XmlNode xmessage in xmessagelist)
                        {
                            string lang  = xmessage.Attributes.GetNamedItem("lang").Value;
                            string words = xmessage.Attributes.GetNamedItem("words").Value;
                            langItem.AddMessage(lang, words);
                        }
                    }
                }

                return("");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#21
0
        void Init()
        {
            // Set Default Value for picker
            LanguageItem language = (BindingContext as MainSettingsViewModel).LanguageItems
                                    .FirstOrDefault(s => s.Code == App.Current.Properties["LocalizeApp"]
                                                    .ToString());

            PickerSettingsLanguage.SelectedItem = language;
        }
        public override void ActivateItem()
        {
            LanguageItem item = (LanguageItem)CurrentNode.DataItem;
            Document     doc  = IdeApp.Workbench.OpenDocument(item.File);

            //bool isMacro = item is Macro;

            doc.Editor.SetCaretTo((int)item.Line, 0);              // TODO: get column?
        }
示例#23
0
        public override async void ActivateItem()
        {
            LanguageItem item = (LanguageItem)CurrentNode.DataItem;
            Document     doc  = await IdeApp.Workbench.OpenDocument(item.File);

            //bool isMacro = item is Macro;

            doc.Editor.CaretLocation = new DocumentLocation((int)item.Line, 1);              // TODO: get column?
        }
示例#24
0
        private void comBoxLangSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var          selectedBox  = (ComboBox)sender;
            LanguageItem selectedLang = (LanguageItem)selectedBox.SelectedItem;

            ConfigModel.Language = selectedLang.Name;

            txtBlockLangInfo.Text = $"Language:{ConfigModel.Language}";
        }
 private void comboBoxVoiceLanguages_SelectedIndexChanged(object sender, EventArgs e)
 {
     updateVoiceDisplay();
     if (comboBoxVoiceLanguages.SelectedIndex >= 0)
     {
         LanguageItem selectedLanguage = comboBoxVoiceLanguages.SelectedItem as LanguageItem;
         Properties.Settings.Default.defaultLanguage = selectedLanguage.Id;
     }
 }
示例#26
0
        private void CLanguageSelectedIndexChanged(object sender, EventArgs e)
        {
            LanguageItem item = cLanguage.SelectedItem as LanguageItem;

            if (item != null)
            {
                SetLanguage(this, item.Culture);
            }
        }
示例#27
0
        public void GotoDeclaration()
        {
            LanguageItem item = GetLanguageItemAt(Editor.Caret.Location);

            if (item != null)
            {
                IdeApp.Workbench.OpenDocument((FilePath)item.File, (int)item.Line, 1);
            }
        }
示例#28
0
        public CompletionData(LanguageItem item)
        {
            if (item is Class)
            {
                image = Stock.Class;
            }
            else if (item is Structure)
            {
                image = Stock.Struct;
            }
            else if (item is Union)
            {
                image = "md-union";
            }
            else if (item is Enumeration)
            {
                image = Stock.Enum;
            }
            else if (item is Enumerator)
            {
                image = Stock.Literal;
            }
            else if (item is Function)
            {
                image = Stock.Method;
            }
            else if (item is Namespace)
            {
                image = Stock.NameSpace;
            }
            else if (item is Typedef)
            {
                image = Stock.Interface;
            }
            else if (item is Member)
            {
                image = Stock.Field;
            }
            else if (item is Variable)
            {
                image = Stock.Field;
            }
            else if (item is Macro)
            {
                image = Stock.Literal;
            }
            else
            {
                image = Stock.Literal;
            }

            this.text = item.Name;
            this.completion_string = item.Name;
            this.description       = string.Empty;
            this.description_pango = string.Empty;
        }
示例#29
0
        private void AddLanguageItem(string displayName, string languageTag)
        {
            var languageItem = new LanguageItem
            {
                DisplayName = displayName,
                LanguageTag = languageTag
            };

            _languageItems.Add(languageItem);
        }
示例#30
0
        protected override object AddNewCore()
        {
            ILanguageItem languageItem = new LanguageItem();

            Add(languageItem);

            // Not necessary to hook up event handlers, base class calls InsertItem

            return(languageItem);
        }
        public override PresentationResult OnInspectorGui(PresentationParamater parameter)
        {
            PresentationData presentationData = parameter.PresentationData as PresentationData;

            if (presentationData == null)
            {
                presentationData = new PresentationData();
            }
            LanguageItem languageItem    = parameter.Instance as LanguageItem;
            Type         itemType        = parameter.DataType.GetProperty("Value").PropertyType;
            bool         newLanguageItem = false;

            if (languageItem == null)
            {
                newLanguageItem = true;
                languageItem    =
                    (LanguageItem)Activator.CreateInstance(typeof(InfoLanguageItem <>).MakeGenericType(itemType));
            }
            PresentationSite presentationSite = new PresentationSite
            {
                Base             = languageItem,
                BaseSite         = parameter.PresentationSite,
                BasePresentation = this,
                SiteType         = PresentationSiteType.None
            };
            Change change;
            OverridableLanguageAttribute overridableLanguageAttribute = parameter.DataType.GetCustomAttribute <OverridableLanguageAttribute>();

            if (overridableLanguageAttribute == null)
            {
                PropertyInfo propertyInfo = parameter.PresentationSite.GetFirtTargetedPropertyInfo();
                if (propertyInfo != null)
                {
                    overridableLanguageAttribute = propertyInfo.GetCustomAttribute <OverridableLanguageAttribute>();
                }
            }
            if (overridableLanguageAttribute == null)
            {
                change = ApplyNotOvveriededLanguageItem(parameter, languageItem, itemType, presentationSite, presentationData);
            }
            else
            {
                if (newLanguageItem)
                {
                    ((IInfoLanguageItem)languageItem).UseOverridedValue = true;
                }
                change = ApplyOvveriededLanguageItem(parameter, languageItem, itemType, presentationSite, presentationData);
            }
            return(new PresentationResult
            {
                Change = change,
                PresentationData = presentationData,
                Result = languageItem
            });
        }
示例#32
0
        /// <summary>
        /// Set default values of Language
        /// </summary>
        public Language()
        {
            _langCode = "en";
            _langName = "English";
            _author = "Dương Diệu Pháp";
            _description = "English";
            _minVersion = "3.5.0.0";
            _fileName = "";
            _isRightToLeftLayout = RightToLeft.No;

            _Items = new LanguageItem<string, string>();
            InitDefaultLanguageDictionary();
        }
 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;
 }
 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;
 }
示例#35
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;
        }
示例#36
0
 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;
 }
 public Meta()
 {
     language = new LanguageItem();
     Authors = new List<AuthorItem>();
 }
示例#38
0
        public string ProcessNuggets(string entity, LanguageItem[] languages)
        {
            // Lookup any/all msgid nuggets in the entity and replace with any translated message.
            string entityOut = _nuggetParser.ParseString(entity, delegate(string nuggetString, int pos, Nugget nugget, string i_entity)
            {
            // Formatted nuggets:
            //
            // A formatted nugget will be encountered here like this, say:
            //
            //    [[[Enter between %0 and %1 characters|||100|||6]]]
            //
            // while the original string in the code for this may have been:
            //
            //    [[[Enter between %0 and %1 characters|||{1}|||{2}]]]
            //
            // The canonical msgid part is that between the opening [[[ and the first |||:
            //
            //    Enter between %0 and %1 characters
            //
            // We use that for the lookup.
            //
                LanguageTag lt;
                string message;
               // Check for unit-test caller.
                if (_textLocalizer == null) {
                    return "test.message"; }
               // Lookup resource using canonical msgid.
                message = _textLocalizer.GetText(
                    true, // true = try lookup with HtmlDecoded-msgid if lookup with raw msgid fails.
                    nugget.MsgId,
                    nugget.Comment,
                    languages,
                    out lt);
               //
                if (nugget.IsFormatted) {
                   // Convert any identifies in a formatted nugget: %0 -> {0}
                    message = ConvertIdentifiersInMsgId(message);
                   // Format the message.
                    var formatItems = new List<string>(nugget.FormatItems);
                    try {
                        // translate nuggets in parameters
                        for (int i = 0; i < formatItems.Count; i++)
                        {
                            // if formatItem (parameter) is null or does not contain NuggetParameterBegintoken then continue
                            if (formatItems[i] == null || !formatItems[i].Contains(_settings.NuggetParameterBeginToken)) continue;

                            // replace parameter tokens with nugget tokens
                            var fItem = formatItems[i].Replace(_settings.NuggetParameterBeginToken, _settings.NuggetBeginToken).Replace(_settings.NuggetParameterEndToken, _settings.NuggetEndToken);
                            // and process nugget
                            formatItems[i] = ProcessNuggets(fItem, languages);
                        }

                        message = string.Format(message, formatItems.ToArray()); }
                    catch (FormatException /*e*/) {
                        //message += string.Format(" [FORMAT EXCEPTION: {0}]", e.Message);
                        message += "[FORMAT EXCEPTION]";
                    }
                }
               // Output modified message (to be subsituted for original in the source entity).
                DebugHelpers.WriteLine("I18N.NuggetLocalizer.ProcessNuggets -- msgid: {0,35}, message: {1}", nugget.MsgId, message);
               //
                if (_settings.VisualizeMessages)
                {
                    string languageToken = string.Empty;
                    if (!string.IsNullOrWhiteSpace(_settings.VisualizeLanguageSeparator))
                        languageToken = lt.ToString() + _settings.VisualizeLanguageSeparator;
                    string endToken = _settings.NuggetVisualizeToken;
                    if (!string.IsNullOrWhiteSpace(_settings.NuggetVisualizeEndToken))
                        endToken = _settings.NuggetVisualizeEndToken;
                    message = string.Format("{0}{1}{2}{3}", _settings.NuggetVisualizeToken, languageToken, message, endToken);
                }
                return message;
                    // NB: this was originally returning HttpUtility.HtmlEncode(message).
                    // Ref #105 and #202 as to why changed back to returning message as is.
            });
               // Return modified entity.
            return entityOut;
        }
示例#39
0
 public static LanguageTag GetMatchingAppLanguage(LanguageItem[] languages, int maxPasses = -1)
 {
     LanguageTag lt = null;
     LocalizedApplication.Current.TextLocalizerForApp.GetText(null, null, languages, out lt, maxPasses);
     return lt;
 }
示例#40
0
        /// <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;
        }
示例#41
0
	void OnGUI(){
		EditorGUILayout.BeginHorizontal();
						
		if(GUILayout.Button("Save")){
			Save();
			ShowNotification(new GUIContent("Dictionaries saved"));
		}
		
		if(GUILayout.Button("Load")){
			Load();
			ShowNotification(new GUIContent("Dictionaries loaded"));
		}
		
		if(GUILayout.Button("Add")){
			langItems.Add(new LanguageItem());
		}
										
		if(GUILayout.Button("Update Camera")){
			LangDictionaries ld = Camera.main.gameObject.GetComponent<LangDictionaries>() as LangDictionaries;
			if(ld == null) ld = Camera.main.gameObject.AddComponent<LangDictionaries>() as LangDictionaries;
			List<LanguageItem> selection = new List<LanguageItem>(from i in langItems where i.selected == true select i);
			ld.dictionaries.Clear();
			ld.langCode = langCode;
			for(int i = 0; i<selection.Count(); i++){
				string fileName = Application.dataPath + "/Resources Localization/" + selection[i].odsFileName + ".ods";
				if(System.IO.File.Exists(fileName)){
					OdsReadWrite.OdsReaderWriter reader = new OdsReadWrite.OdsReaderWriter();
					System.Data.DataSet dataset = reader.ReadOdsFile(fileName);
				
					foreach(System.Data.DataTable table in dataset.Tables){
						bool isDictionary = false;
						foreach(System.Data.DataRow row in table.Rows){
							if((row[0] as string).ToUpper() == "ID") isDictionary = true;
							else isDictionary = false;
							break;
						}
						if(isDictionary){
							ld.dictionaries.Add(new LangDictionaries.LangDictionary());
							ld.dictionaries.Last().aliasName = table.TableName;
							ld.dictionaries.Last().assetPath = "Dictionaries/" + table.TableName;
						}
					}		
				} else {
					Debug.LogError("FILE NOT EXISTS : " + fileName);	
				}
			}
			ShowNotification(new GUIContent("Camera.main dictionaries updated"));
		}
		
		langCode = (Lang.LanguageCode)EditorGUILayout.EnumPopup(langCode, GUILayout.Width(80));
		
		GUILayout.Label("Async", GUILayout.Width(40));
		async = EditorGUILayout.Toggle(async, GUILayout.Width(20));
		
		if(GUILayout.Button("Download from GoogleDocs")){
			for(int i = 0; i< langItems.Count; i++){
				if(langItems[i].selected){
					langItems[i].Download(async, ()=>{Repaint();});
				}
			}
		}
		
		
	
		EditorGUILayout.EndHorizontal();
		
		OSXOpenOffice = EditorGUILayout.TextField("OpenOffice(OSX)", OSXOpenOffice);
		WINOpenOffice = EditorGUILayout.TextField("OpenOffice(WIN)", WINOpenOffice);
		
		EditorGUILayout.BeginHorizontal();
		GUILayout.Box("Filename",GUILayout.Width(263));
		//GUILayout.Box("ODS Url",GUILayout.Width(300));
		//GUILayout.Box("Document Url",GUILayout.Width(260));
		GUILayout.Box("Public Document Key", GUILayout.Width(363));
		GUILayout.Box("",GUILayout.Width(20));
		GUILayout.Box("Last Download",GUILayout.Width(140));
		GUILayout.Box("ODS->TXT",GUILayout.Width(80));
		GUILayout.Box("Delete",GUILayout.ExpandWidth(true));
		EditorGUILayout.EndHorizontal();
		backgroundColor = GUI.backgroundColor;
		contentColor = GUI.contentColor;
		for(int i = 0; i< langItems.Count(); i++){
			langItem = langItems[i];
			EditorGUILayout.BeginHorizontal();
			GUI.backgroundColor = langItems[i].GetColor();	
			langItem.odsFileName = GUILayout.TextField(langItem.odsFileName, GUILayout.Width(200));
			if(GUILayout.Button("Open",GUILayout.Width(60))){
				string filePath = Application.dataPath + "/Resources Localization/" + langItems[i].odsFileName + ".ods";
				if(!File.Exists(filePath)){
					File.Copy(Application.dataPath + "/Foriero/Localization/Templates/Localization.ods", filePath);
					AssetDatabase.Refresh();
				} 
				if(Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX){
					System.Diagnostics.Process.Start(OSXOpenOffice, "\"" + filePath + "\"");
				} else {
					System.Diagnostics.Process.Start(WINOpenOffice, "\"" + filePath.Replace("/",@"\") + "\"");
				}
			}
			langItem.publicKey = GUILayout.TextField(langItem.publicKey, GUILayout.Width(196));
			//langItem.odsURL = GUILayout.TextField(langItem.odsURL, GUILayout.Width(196));
			if(GUILayout.Button("Download",GUILayout.Width(100))){
				langItems[i].Download(async, ()=>{Repaint();});
			}
			//langItem.documentURL = GUILayout.TextField(langItem.documentURL, GUILayout.Width(196));
			if(GUILayout.Button("Open",GUILayout.Width(60))){
				Application.OpenURL(langItem.documentURL);	
			}
			langItem.selected = EditorGUILayout.Toggle(langItem.selected,GUILayout.Width(20));
						
			GUILayout.Box(langItems[i].lastDownload, GUILayout.Width(140));
			
			if(GUILayout.Button("ODS->TXT", GUILayout.Width(80))){
				string fileNameOds = Application.dataPath + "/Resources Localization/" + langItems[i].odsFileName + ".ods"; 
				if(!File.Exists(fileNameOds)){
					File.Copy(Application.dataPath + "/Foriero/Localization/Templates/Localization.ods", fileNameOds);
					AssetDatabase.Refresh();	
				}
				ODSToDictionary(fileNameOds);
			}
			if(GUILayout.Button("Delete")){
				langItems.Remove(langItems[i]);
				break;
			}
			
			if(langItem.errorMessage != "OK") GUI.contentColor = Color.red;
			GUI.backgroundColor = backgroundColor;
			GUI.contentColor = contentColor;
			EditorGUILayout.EndHorizontal();
		}
	}
示例#42
0
        public static void SetPrincipalAppLanguageForRequest(this System.Web.HttpContextBase context, ILanguageTag pal, bool updateThreadCulture = true)
        {
        // The PAL is stored as the first item in the UserLanguages array (with Quality set to 2).
        //
            LanguageItem[] UserLanguages = GetRequestUserLanguages(context);
            UserLanguages[0] = new LanguageItem(pal, LanguageItem.PalQualitySetting, 0);

            // Run through any handlers installed for this event.
            if (LocalizedApplication.Current.SetPrincipalAppLanguageForRequestHandlers != null) {
                foreach (LocalizedApplication.SetLanguageHandler handler in LocalizedApplication.Current.SetPrincipalAppLanguageForRequestHandlers.GetInvocationList())
                {
                    handler(context, pal);
                }
            }

        }