Monday, June 29, 2009

Localization with Strongly-Typed Keys

I came across this issue while working on an MVC application in VS 2008. The project required localization to be setup such that future phases could easily incorporate languages other than English. As expected, I initially added local resources in their respective resx files.

Problem: As usual, I was thinking of improved ways to extend long term management of the application. When working with string-keyed references, I typically like to think of ways to enumerate or use static constants for strongly-typed keys instead of loosely defined strings. So I thought maybe I could build some kind of custom tool or a pre-build event executable to read through the resx xml and create code that would reflect the keyed strings. However, after some googling, I discovered that the solution was right under my nose; VS 2008 does this for me. At the top of the GUI for the resx file in VS is a dropdown menu with the label Access Modifier. When I selected Public in the dropdown, a code behind file appeared for my resx file. It had the strongly-typed key constants just as I wanted so that I could access the keys with intellisense.

For all effective purposes this seemed to work great until I added another resx file for the Spanish language. After some time looking into this, I discovered that when I changed the dropdown to public, my English resx file changed from a Content page (see Build Action field in the file's properties) to an Embedded Resource. So this means that instead of loading the resource file from IO during runtime, it will embed the file directly into my dll at compile time. However, accessing the corresponding Spanish file was not localization as usual. I needed to set the es.resx file to also have Embedded Resource in the Build Action, because localization at runtime now looks for the embedded resource files, not the IO files. There is just one thing to remember, make sure that the Access Modifier is set to No code generation for the Spanish file, don't think this will be set exactly how you set your primary language resx file with the dropdown menu in the GUI, because we already defined the keys in the primary language file.

Solution:
  1. Set the the primary resx file to Public from the Access Modifier dropdown.
  2. Set all other language resx sister files to Embedded Resource from the Build Action field in the respective file's property window.
Hope this is helpful:)