Umbraco 7 Code-First Dictionary Key Manager

Michael Roma on Jun 19, 2015

This post shows a simple code-first dictionary manager for Umbraco 7. Click here to download the source. First define the attribute class and a helper to get the details of an attribute by key name

// define the dictionary key attributes
public class DictionaryKeyAttribute : Attribute
{
    // define fields
    public string Name { get; set; }
    public string DefaultText { get; set; }

    // constructor
    public DictionaryKeyAttribute(string name, string defaultText)
    {
        Name = name;
        DefaultText = defaultText;
    }
}   

// helper that gets the details
private static DictionaryKeyAttribute GetDetails(Keys key)
{
    return key.GetType()
        .GetField(key.ToString())
        .GetCustomAttributes(typeof(DictionaryKeyAttribute), false)
        .SingleOrDefault() as DictionaryKeyAttribute;            
}
Here is the function that initializes the keys by creating new Umbraco dictionary entries if the key does not already exist
// function that inits the dictionary and add new items if needed
public static void Init()
{
    // get the service
    var locationService = ApplicationContext.Current.Services.LocalizationService;

    // get all languages
    var langs = locationService.GetAllLanguages();

    // go through each key
    foreach(var key in Enum.GetValues(typeof(Keys)))
    {
        // get details, check if any
        var keyDetails = GetDetails((Keys)key);
        if (keyDetails != null)
        {
            string keyName = String.Concat(Prefix, keyDetails.Name);
            if (!locationService.DictionaryItemExists(keyName))
            {
                // init the new item
                var newItem = new DictionaryItem(keyName);
                newItem.Translations = langs
                    .Select(lang => new DictionaryTranslation(lang, keyDetails.DefaultText));                        

                // save
                locationService.Save(newItem);
            }
        }
    }

}
The following functions can be used to extract the dictionary text by key
// function that returns a dictionary string
public static string GetText(string key)
{
    // get the service
    var locationService = ApplicationContext.Current.Services.LocalizationService;

    // find the dictionary item
    var item = locationService.GetDictionaryItemByKey(String.Concat(Prefix, key));
    if (item != null && item.Translations != null)
    {
        // get the current language
        int languageId = GetCurrentLanguage();

        // get the translation
        var t = item.Translations.FirstOrDefault(x => x.Language.Id == languageId);
        if (t == null)
        {
            t = item.Translations.FirstOrDefault();
        }

        // check if a translation
        if (t != null)
        {
            // return
            return t.Value;
        }
    }

    // fallback to empty
    return “”;
}

// function that gets the dictionary string
public static string GetText(Keys key)
{
    // get the dictionary key details
    var keyDetails = GetDetails((Keys)key);
    if( keyDetails != null)
    {
        return GetText(keyDetails.Name);
    }

    // fallback to empty
    return “”;
}
Last, define your key prefix and keys
// define prefix
public const string Prefix = “roma”;

// define dictionary items
public enum Keys
{            
    [DictionaryKey(“PageTitle”, “{0} | Michael Roma Development”)] PageTitle,
    [DictionaryKey(“CategoriesTitle”, “Categories”)] CategoriesTitle
}
Here is a helper to get the current page’s language
// function that gets the current language
public static int GetCurrentLanguage()
{
    // get the current page
    var currentPage = new UmbracoHelper(UmbracoContext.Current)
        .TypedContent(UmbracoContext.Current.PageId.Value);

    // check if a page
    if (currentPage != null)
    {
        // get the home page
        var home = currentPage.AncestorOrSelf(1);
        if (home != null)
        {
            // get the domains for home
            var domains = umbraco.cms.businesslogic.web.Domain.GetDomainsById(home.Id);
            if (domains.Count() > 0)
            {
                return domains[0].Language.id;
            }
        }
    }

    // if here, no language
    return 0;
}