Exemple #1
0
        public void Can_Perform_Update_On_DictionaryRepository()
        {
            // Arrange
            IScopeProvider provider = ScopeProvider;

            using (provider.CreateScope())
            {
                IDictionaryRepository repository = CreateRepository();

                // Act
                IDictionaryItem item         = repository.Get(1);
                var             translations = item.Translations.ToList();
                translations[0].Value = "Read even more";
                item.Translations     = translations;

                repository.Save(item);

                IDictionaryItem dictionaryItem = repository.Get(1);

                // Assert
                Assert.That(dictionaryItem, Is.Not.Null);
                Assert.That(dictionaryItem.Translations.Count(), Is.EqualTo(2));
                Assert.That(dictionaryItem.Translations.FirstOrDefault().Value, Is.EqualTo("Read even more"));
            }
        }
 // Umbraco.Code.MapAll -ParentId -Path -Trashed -Udi -Icon
 private static void Map(IDictionaryItem source, EntityBasic target, MapperContext context)
 {
     target.Alias = source.ItemKey;
     target.Id    = source.Id;
     target.Key   = source.Key;
     target.Name  = source.ItemKey;
 }
        public override void Up()
        {
            ILocalizationService    localizationService = ApplicationContext.Current.Services.LocalizationService;
            IEnumerable <ILanguage> languages           = localizationService.GetAllLanguages();
            ILanguage language = languages.FirstOrDefault(x => x.IsoCode == "en-GB" || x.IsoCode == "en-US")
                                 ?? languages.FirstOrDefault();

            if (language == null)
            {
                return;
            }

            IDictionaryItem dataAnnotations = localizationService.GetDictionaryItemByKey("DataAnnotions");

            if (dataAnnotations != null)
            {
                return;
            }

            dataAnnotations = localizationService.CreateDictionaryItemWithIdentity("DataAnnotations", null);

            foreach (var item in defaultDictionaryItems)
            {
                if (localizationService.DictionaryItemExists(item.Key))
                {
                    continue;
                }

                localizationService.CreateDictionaryItemWithIdentity(item.Key, dataAnnotations.Key, item.Value);
            }
        }
    private static List <LanguageTextDto> BuildLanguageTextDtos(IDictionaryItem entity)
    {
        var list = new List <LanguageTextDto>();

        if (entity.Translations is not null)
        {
            foreach (IDictionaryTranslation translation in entity.Translations)
            {
                var text = new LanguageTextDto
                {
                    LanguageId = translation.LanguageId,
                    UniqueId   = translation.Key,
                    Value      = translation.Value,
                };

                if (translation.HasIdentity)
                {
                    text.PrimaryKey = translation.Id;
                }

                list.Add(text);
            }
        }

        return(list);
    }
Exemple #5
0
 public ItemInfos(IDictionaryItem item)
 {
     Id       = item.Key;
     Key      = item.ItemKey;
     Values   = item.Translations.ToDictionary(x => x.Language.CultureInfo.Name, x => x.Value);
     ParentId = item.ParentId;
 }
        /// <summary>
        /// Adds or updates a translation for a dictionary item and language
        /// </summary>
        /// <param name="item"></param>
        /// <param name="language"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <remarks>
        /// This does not save the item, that needs to be done explicitly
        /// </remarks>
        public void AddOrUpdateDictionaryValue(IDictionaryItem item, ILanguage language, string value)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }
            if (language == null)
            {
                throw new ArgumentNullException(nameof(language));
            }

            var existing = item.Translations.FirstOrDefault(x => x.Language.Id == language.Id);

            if (existing != null)
            {
                existing.Value = value;
            }
            else
            {
                item.Translations = new List <IDictionaryTranslation>(item.Translations)
                {
                    new DictionaryTranslation(language, value)
                };
            }
        }
Exemple #7
0
 public void UpdateCache(IDictionaryItem item)
 {
     if (!GlobalDictionary.ContainsKey(item.ItemKey))
     {
         GlobalDictionary.Add(item.ItemKey, item.ItemKey);
     }
 }
Exemple #8
0
        public void Can_Perform_Update_WithNewTranslation_On_DictionaryRepository()
        {
            // Arrange
            ILocalizationService localizationService = GetRequiredService <ILocalizationService>();
            IScopeProvider       provider            = ScopeProvider;

            using (provider.CreateScope())
            {
                IDictionaryRepository repository = CreateRepository();

                var languageNo = new Language("nb-NO", "Norwegian Bokmål (Norway)");
                localizationService.Save(languageNo);

                // Act
                IDictionaryItem item         = repository.Get(1);
                var             translations = item.Translations.ToList();
                translations.Add(new DictionaryTranslation(languageNo, "Les mer"));
                item.Translations = translations;

                repository.Save(item);

                var dictionaryItem = (DictionaryItem)repository.Get(1);

                // Assert
                Assert.That(dictionaryItem, Is.Not.Null);
                Assert.That(dictionaryItem.Translations.Count(), Is.EqualTo(3));
                Assert.That(dictionaryItem.Translations.Single(t => t.LanguageId == languageNo.Id).Value, Is.EqualTo("Les mer"));
            }
        }
        protected DictionaryModel Create(string itemKey, DictionaryModel parent, Func <CultureInfo, string> valueResolver)
        {
            DictionaryModelWrapper parentModel = parent as DictionaryModelWrapper;

            // Get the dictionary item from Umbraco. Otherwise crete a new.
            IDictionaryItem dictionaryItem = _localizationService.GetDictionaryItemByKey(itemKey) ??
                                             _localizationService.CreateDictionaryItemWithIdentity(itemKey,
                                                                                                   parentModel?.Key);

            // Create the model
            DictionaryModelWrapper model = new DictionaryModelWrapper(dictionaryItem, parentModel);

            // If no value resolver are provided, then return the model
            if (valueResolver == null)
            {
                return(model);
            }

            // A save indicator
            bool save = false;

            // Iterate through all languages
            foreach (ILanguage language in Languages)
            {
                IDictionaryTranslation translation =
                    dictionaryItem.Translations.SingleOrDefault(x => x.Language == language);
                // If the dictionary translation already has a value, then don't change it
                if (!string.IsNullOrEmpty(translation?.Value))
                {
                    continue;
                }

                // Get the culture specific default value from the value resolver
                string value = valueResolver(language.CultureInfo);
                // If there is no value, then do nothing
                if (value == null)
                {
                    continue;
                }

                // Add the value to the Umbraco dictionary item
                _localizationService.AddOrUpdateDictionaryValue(dictionaryItem, language, value);
                // Indicate that a value has been added to the dictionary, and ensure save
                save = true;

                // Log the addition
                Log.Information(
                    $"Adding '{language}' value:'{value}' for dictionary item: '{dictionaryItem.ItemKey}'");
            }

            // Save the dictionary item
            if (save)
            {
                _localizationService.Save(dictionaryItem);
            }

            // Return the model
            return(model);
        }
 /// <summary>
 /// Gets the entity identifier of the entity.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <returns>The entity identifier of the entity.</returns>
 public static GuidUdi GetUdi(this IDictionaryItem entity)
 {
     if (entity == null)
     {
         throw new ArgumentNullException("entity");
     }
     return(new GuidUdi(Constants.UdiEntityType.DictionaryItem, entity.Key).EnsureClosed());
 }
Exemple #11
0
        private TreeNode CreateTreeNode(IDictionaryItem item, string parentId)
        {
            var hasChildren = LocalizationService.GetDictionaryItemChildren(item.Key).Any();
            var node        = TreeController.CreateTreeNode(item.Key.ToString(), parentId, EmptyFormData, item.ItemKey, "icon-book-alt", hasChildren);

            node.AdditionalData["key"] = item.ItemKey;

            return(node);
        }
            public DictionaryItem(string key)
            {
                _dictionaryItem = ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemByKey(key);

                if (_dictionaryItem == null)
                {
                    throw new ArgumentException("No key " + key + " exists in dictionary");
                }
            }
            public DictionaryItem(int id)
            {
                _dictionaryItem = ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemById(id);

                if (_dictionaryItem == null)
                {
                    throw new ArgumentException("No id " + id + " exists in dictionary");
                }
            }
 public static DictionaryDto BuildDto(IDictionaryItem entity) =>
 new DictionaryDto
 {
     UniqueId         = entity.Key,
     Key              = entity.ItemKey,
     Parent           = entity.ParentId,
     PrimaryKey       = entity.Id,
     LanguageTextDtos = BuildLanguageTextDtos(entity),
 };
Exemple #15
0
        public void Can_Get_Dictionary_Item_By_Guid_Id()
        {
            IDictionaryItem parentItem = LocalizationService.GetDictionaryItemById(_parentItemGuidId);

            Assert.NotNull(parentItem);

            IDictionaryItem childItem = LocalizationService.GetDictionaryItemById(_childItemGuidId);

            Assert.NotNull(childItem);
        }
Exemple #16
0
        public void Can_Get_Dictionary_Item_By_Key()
        {
            IDictionaryItem parentItem = LocalizationService.GetDictionaryItemByKey("Parent");

            Assert.NotNull(parentItem);

            IDictionaryItem childItem = LocalizationService.GetDictionaryItemByKey("Child");

            Assert.NotNull(childItem);
        }
Exemple #17
0
        private void GetChildItemsForList(IDictionaryItem dictionaryItem, ICollection <EntityBasic> list)
        {
            foreach (var childItem in Services.LocalizationService.GetDictionaryItemChildren(dictionaryItem.Key).OrderBy(DictionaryItemSort()))
            {
                var item = Mapper.Map <IDictionaryItem, EntityBasic>(childItem);
                list.Add(item);

                GetChildItemsForList(childItem, list);
            }
        }
Exemple #18
0
        private void AssertDictionaryItem(string dictionaryItemName, string expectedValue, string cultureCode)
        {
            Assert.That(LocalizationService.DictionaryItemExists(dictionaryItemName), "DictionaryItem key does not exist");
            IDictionaryItem        dictionaryItem = LocalizationService.GetDictionaryItemByKey(dictionaryItemName);
            IDictionaryTranslation translation    = dictionaryItem.Translations.SingleOrDefault(i => i.Language.IsoCode == cultureCode);

            Assert.IsNotNull(translation, "Translation to {0} was not added", cultureCode);
            string value = translation.Value;

            Assert.That(value, Is.EqualTo(expectedValue), "Translation value was not set");
        }
Exemple #19
0
 public static DictItem ToDictItem(this IDictionaryItem dict)
 {
     return(new DictItem()
     {
         Id = dict.Id,
         ItemKey = dict.ItemKey,
         Key = dict.Key,
         ParentId = dict.ParentId,
         Translations = dict.Translations.ToDictTranslations()
     });
 }
        /// <summary>
        /// Get child items for list.
        /// </summary>
        /// <param name="dictionaryItem">
        /// The dictionary item.
        /// </param>
        /// <param name="level">
        /// The level.
        /// </param>
        /// <param name="list">
        /// The list.
        /// </param>
        private void GetChildItemsForList(IDictionaryItem dictionaryItem, int level, ICollection <DictionaryOverviewDisplay> list)
        {
            foreach (var childItem in Services.LocalizationService.GetDictionaryItemChildren(dictionaryItem.Key).OrderBy(ItemSort()))
            {
                var item = Mapper.Map <IDictionaryItem, DictionaryOverviewDisplay>(childItem);
                item.Level = level;
                list.Add(item);

                GetChildItemsForList(childItem, level + 1, list);
            }
        }
 /// <summary>
 /// Сравнивает детали имебщиеся в коллекции с добавляемой по их ID
 /// если деталь с подобным ID в коллекции не существует,
 /// то она добавляется в коллекцию и возвращается true
 /// ежели деталь с подобным ID в коллекции есть
 /// то она НЕ добавляется в коллекцию и возвращается false
 /// </summary>
 /// <param name="addedObject"></param>
 bool IDictionaryCollection.CompareAndAdd(IDictionaryItem addedObject)
 {
     if (addedObject == null)
     {
         throw new ArgumentNullException("addedObject", "must be not null");
     }
     if (addedObject is T)
     {
         return(CompareAndAdd(addedObject as T));
     }
     throw new ArgumentException("must be not of type:" + typeof(T), "addedObject");
 }
Exemple #22
0
        public void Can_Delete_DictionaryItem()
        {
            IDictionaryItem item = LocalizationService.GetDictionaryItemByKey("Child");

            Assert.NotNull(item);

            LocalizationService.Delete(item);

            IDictionaryItem deletedItem = LocalizationService.GetDictionaryItemByKey("Child");

            Assert.Null(deletedItem);
        }
Exemple #23
0
        private static void AddTranslations(JObject parent, IDictionaryItem dictionaryItem)
        {
            if (dictionaryItem != null)
            {
                JObject translations = new JObject();

                foreach (IDictionaryTranslation translation in dictionaryItem.Translations)
                {
                    translations.Add(translation.Language.IsoCode.Replace('-', '_').ToLower(), translation.Value);
                }

                parent.Add(Constants.Json.Translations, translations);
            }
        }
        public XElement Serialize(IDictionaryItem dictionaryItem)
        {
            var xml = new XElement("DictionaryItem", new XAttribute("Key", dictionaryItem.ItemKey));

            foreach (var translation in dictionaryItem.Translations)
            {
                xml.Add(new XElement("Value",
                                     new XAttribute("LanguageId", translation.Language.Id),
                                     new XAttribute("LanguageCultureAlias", translation.Language.IsoCode),
                                     new XCData(translation.Value)));
            }

            return(xml);
        }
Exemple #25
0
        /// <summary>
        /// Get child items for list.
        /// </summary>
        /// <param name="dictionaryItem">
        /// The dictionary item.
        /// </param>
        /// <param name="level">
        /// The level.
        /// </param>
        /// <param name="list">
        /// The list.
        /// </param>
        private void GetChildItemsForList(IDictionaryItem dictionaryItem, int level, ICollection <DictionaryOverviewDisplay> list)
        {
            foreach (var childItem in _localizationService.GetDictionaryItemChildren(dictionaryItem.Key)?.OrderBy(ItemSort()) ?? Enumerable.Empty <IDictionaryItem>())
            {
                var item = _umbracoMapper.Map <IDictionaryItem, DictionaryOverviewDisplay>(childItem);
                if (item is not null)
                {
                    item.Level = level;
                    list.Add(item);
                }

                GetChildItemsForList(childItem, level + 1, list);
            }
        }
        /// <summary>
        /// This is here to take care of a hack - the DictionaryTranslation model contains an ILanguage reference which we don't want but
        /// we cannot remove it because it would be a large breaking change, so we need to make sure it's resolved lazily. This is because
        /// if developers have a lot of dictionary items and translations, the caching and cloning size gets much much larger because of
        /// the large object graphs. So now we don't cache or clone the attached ILanguage
        /// </summary>
        private void EnsureDictionaryItemLanguageCallback(IDictionaryItem d)
        {
            var item = d as DictionaryItem;

            if (item == null)
            {
                return;
            }

            item.GetLanguage = GetLanguageById;
            foreach (var trans in item.Translations.OfType <DictionaryTranslation>())
            {
                trans.GetLanguage = GetLanguageById;
            }
        }
        private void UpdateLanguages(IDictionaryItem item, IDictionary <string, string> values)
        {
            var languages = LocalizationService.GetAllLanguages().ToArray();

            foreach (var value in values)
            {
                var language = languages.FirstOrDefault(x => x.CultureInfo.Name == value.Key);
                if (language == null)
                {
                    continue;
                }

                LocalizationService.AddOrUpdateDictionaryValue(item, language, value.Value);
            }
        }
 /// <summary>
 /// Добавляет объект в коллекцию
 /// </summary>
 /// <param name="addedObject"></param>
 void IDictionaryCollection.Add(IDictionaryItem addedObject)
 {
     if (addedObject == null)
     {
         throw new ArgumentNullException("addedObject", "must be not null");
     }
     if (addedObject is T)
     {
         Add(addedObject as T);
     }
     else
     {
         throw new ArgumentException("must be not of type:" + typeof(T), "addedObject");
     }
 }
        /// <summary>
        /// Exports a single <see cref="IDictionaryItem"/> item to xml as an <see cref="XElement"/>
        /// </summary>
        /// <param name="dictionaryItem">Dictionary Item to export</param>
        /// <param name="includeChildren">Optional boolean indicating whether or not to include children</param>
        /// <returns><see cref="XElement"/> containing the xml representation of the IDictionaryItem object</returns>
        public XElement Serialize(IDictionaryItem dictionaryItem, bool includeChildren)
        {
            var xml = Serialize(dictionaryItem);

            if (includeChildren)
            {
                var children = _localizationService.GetDictionaryItemChildren(dictionaryItem.Key);
                foreach (var child in children)
                {
                    xml.Add(Serialize(child, true));
                }
            }

            return(xml);
        }
 /// <summary>
 /// Удаляет объект из списка
 /// </summary>
 /// <param name="removedObject"></param>
 void IDictionaryCollection.Remove(IDictionaryItem removedObject)
 {
     if (removedObject == null)
     {
         return;
     }
     if (removedObject is T)
     {
         Remove(removedObject as T);
     }
     else
     {
         throw new ArgumentException("must be not of type:" + typeof(T), "removedObject");
     }
 }
        /// <summary>
        /// Deletes a <see cref="IDictionaryItem"/> object and its related translations
        /// as well as its children.
        /// </summary>
        /// <param name="dictionaryItem"><see cref="IDictionaryItem"/> to delete</param>
        /// <param name="userId">Optional id of the user deleting the dictionary item</param>
        public void Delete(IDictionaryItem dictionaryItem, int userId = 0)
        {
	        if (DeletingDictionaryItem.IsRaisedEventCancelled(new DeleteEventArgs<IDictionaryItem>(dictionaryItem), this)) 
				return;
	        
			var uow = _uowProvider.GetUnitOfWork();
	        using (var repository = _repositoryFactory.CreateDictionaryRepository(uow))
	        {
		        //NOTE: The recursive delete is done in the repository
		        repository.Delete(dictionaryItem);
		        uow.Commit();

		        DeletedDictionaryItem.RaiseEvent(new DeleteEventArgs<IDictionaryItem>(dictionaryItem, false), this);
	        }

	        Audit.Add(AuditTypes.Delete, "Delete DictionaryItem performed by user", userId, dictionaryItem.Id);
        }
        /// <summary>
        /// Saves a <see cref="IDictionaryItem"/> object
        /// </summary>
        /// <param name="dictionaryItem"><see cref="IDictionaryItem"/> to save</param>
        /// <param name="userId">Optional id of the user saving the dictionary item</param>
        public void Save(IDictionaryItem dictionaryItem, int userId = 0)
        {
	        if (SavingDictionaryItem.IsRaisedEventCancelled(new SaveEventArgs<IDictionaryItem>(dictionaryItem), this)) 
				return;
	        
			var uow = _uowProvider.GetUnitOfWork();
	        using (var repository = _repositoryFactory.CreateDictionaryRepository(uow))
	        {
		        repository.AddOrUpdate(dictionaryItem);
		        uow.Commit();

		        SavedDictionaryItem.RaiseEvent(new SaveEventArgs<IDictionaryItem>(dictionaryItem, false), this);
	        }

	        Audit.Add(AuditTypes.Save, "Save DictionaryItem performed by user", userId, dictionaryItem.Id);
        }
 public XElement Export(IDictionaryItem dictionaryItem, bool includeChildren, bool raiseEvents = true)
 {
     return realPackagingService.Export(dictionaryItem, includeChildren, raiseEvents);
 }