Monday, July 17, 2006

Localize This!

Localization, that's pretty much what I've been doing since I got in the DeKlarit team. I've been working on it for win and web forms and I must say that it's really simple in .net framework 2.0.
There are different techniques in order to achieve that, one of them is to generate a resource file for every form in your app. Even though this approach is less complex, I don't like the idea of having as many resource files as forms in my application, so I'll describe how to achieve localization with a different approach.


First of all, create a simple win app and add some controls to the main Fomr (Form1). Add some labels some buttons and what ever you want.
Now create a resource file and name it StringResources.resx. Edita that file with VS2005 and add all the strings you want to localize, ok, cancel, HelloWorld, etc...
In order to localize your form create a method (called form the Page_Load method) where all texts are going to be set. In order to do that write the following sentence for every control you may have in your form:
btnOK.Text = StringResources.NewCaption;
Once you run the application you should see every text you've entered in your resource file.
I now what you're going to say, so, this is the cool part? nope, this is the hard part, to cool part is coming right now. From the Solution Explorer Copy and Paste your resource file and rename it as StringResource.es.resx. Change the values of that file to spanish, Aceptar, Cancelar, HolaMundo, etc. Now change you regional settings so your default language is spanish.
Rerun you app and that's it!, your app should now be displaying all the controls in spanish, or what ever you've entered in the resource file.
In order to get the same result for web applications you can do two things. One is to do exactly what we just did and the other one is to set the "call" to the resource file right on you aspx of ascx file. To do that just change the text attribute of the control for something like this:
Text="<%$Resources:StringResources,NewCaption%>"
You may need to Databind the control in order for the text to be displayed.

So there yo have it, your own application with localization features. Start playing with it and add it to your applications, you never know where's your next buyer from ;)

Read Full Post