Go to content Go to navigation Go to search

C# – Aplicaciones multilenguaje ( globalización y localización )

August 29th, 2010 by JuanK

Continuamente en mis conferencias y de paso por los foros a través de internet encuentro multitud de dudas e inquietudes al respecto de Cómo hacer una aplicación que soporte múltiples idiomas, ciertamente hay varias formas de conseguirlo y no todas esas formas son buenas en todos los escenarios, dependiendo de diferentes factores como por ejemplo el tamaño de la aplicación o la cantidad de idiomas soportados.

 

Sin embargo yo tengo mi método preferido, el cual considero que es válido para la inmensa mayoría de aplicaciones desarrolladas, el método de los archivos de recursos y ese es el tema principal de este artículo.

 

En tres pasos enseñare como hacerlo.

  1. Utilizar archivos de recursos para manipular las cadenas de texto
  2. Soportar múltiples lenguajes con los archivos de recursos
  3. Aislar los archivos de recursos para facilitar la actualización

 

Finalmente relacionare otros temas de interés para tener una funcionalidad más robusta.

 

1. UTILIZAR ARCHIVOS DE RECURSOS PARA MANIPULAR LAS CADENAS DE TEXTO

PREPARAR LA APLICACION

Lo primero que debemos hacer es crear una aplicación de Windows Forms con 1 ListBox y 5 Botones como se ven la siguiente imagen.

image

Para fines de este ejemplo con excepción de los textos del listbox ninguno de los textos es obligatorio.

Ahora, dentro de la solución, creamos una carpeta la cual llamaremos “Recursos Localizables”, justo como se ve a continuación.

image

Ahora creamos un nuevo archivo de recursos y lo llamaremos StringResources, debemos crearlo junto dentro de la carpeta “Recursos Localizables” que acabamos de crear.

 

Revisamos las propiedades del archivo recién creado y nos aseguramos que en Build Action diga “Embedded Resource”.

 

Ahora utilizaremos ese archivo de recursos para guardar las cadenas en el idioma principal (por defecto ) de nuestra aplicación, así que le damos doble clic y adicionamos los valores que se ven en la siguiente imagen.

 

image

 

Para efectos del ejemplo es importante hacerlo con los valores que ven.

 

UTILIZAR EL ARCHIVO DE RECURSOS EN NUESTRA APLICACION

Esta parte es muy sencilla, creamos un método llamado AplicarIdioma con el siguiente código:

private void AplicarIdioma()
{
    button1.Text = StringResources.ButtonLabel1;
    button2.Text = StringResources.ButtonLabel2;
    button3.Text = StringResources.ButtonLabel3;
    button4.Text = StringResources.ButtonLabel4;
    button5.Text = StringResources.ButtonLabel5;
    this.Text = StringResources.WindowTitle;
}

Y lo llamamos desde el Form_Load, ejecutamos la aplicación y obtenemos esto

 

image

 

2. SOPORTAR MÚLTIPLES LENGUAJES CON LOS ARCHIVOS DE RECURSOS

Casi todo el trabajo de codificación ha terminado ahora viene ‘la magia’ . En la carpeta “Recursos Localizables” creamos 3 copias de el archivo de recursos original, nos aseguramos de que cada una de ellas quede con los siguientes nombres.

 

image

 

Ahora editamos cada uno de ellos dejándolos con los textos que se ven a continuación (pueden ayudarse de traductores online para obtener los caracteres en japonés).

 

image

image

 

 

 

 

 

 

 

 

 

 

image

 

Una vez hecho esto procedemos a modificar el evento SelectedIndexChanged del listbox y lo dejamos así:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Thread.CurrentThread.CurrentUICulture = new CultureInfo((string)listBox1.SelectedItem);
    AplicarIdioma();
}

Lo que hemos hecho es hacer que cada vez que se de clic en uno de los miembros de la lista se cambie la cultura de la interfaz de usuario del hilo actual de la aplicación, y dado que cada miembro del listbox es el nombre corto de cada una de las tres culturas que tenemos, basta con crear un nuevo objeto de tipo CultureInfo que coincida con el nombre corto del ítem seleccionado.

 

PORQUÉ Y PARA QUÉ?

Esto que acabamos de hacer tiene un importante objetivo.

Cuando se utiliza un archivo de recursos el CLR  busca primero cual es la cultura del hilo actual, entonces con ese dato automáticamente utiliza el archivo de recursos cuya nomenclatura coincide con esa cultura, sino encuentra dicho archivo de recursos entonces el CLR utiliza el archivo de recursos que no tiene cultura específica.

 

FUNCIONA!

Ejecutamos la aplicación, damos clic en cada uno de los ítems del listbox y podemos ver esto Sorpresa:

 

CultureAnimation

 

3. AISLAR LOS ARCHIVOS DE RECURSOS PARA FACILITAR LA ACTUALIZACIÓN

Hasta aquí nuestro proyecto ya esta terminado y ya estamos en capacidad de hacer aplicaciones multilenguaje, sin embargo como tip final de este artículo les recomiendo que si piensan incluir alguna funcionalidad de actualizaciones en sus aplicaciones y tienen planeado actualizar o incluir nuevos idiomas en su aplicación, coloquen los archivo de recursos en una dl por aparte donde solo se coloquen archivos de recursos, esto permitirá que las actualizaciones relacionadas con cadenas de lenguaje se aíslen en un solo componente.

 

Para que esto funcione, en el proyecto de la librería que utilicen para tal fin, recuerden establecer en cada archivo de recursos el modificador de acceso en public como lo muestra esta imagen.

 

image

 

LECTURAS RECOMENDADAS

Este tema puede ir aún más allá de donde lo hemos llevado, los invito averiguar acerca de como utilizar ensamblados satélite para brindar algunas funcionalidades adicionales y que intenten utilizar la clase CultureInfo y demás relacionadas para detectar el idioma de la interfaz de usuario actual o el idioma con el cual se ha instalado el sistema operativo.

 

En Sistemas como Windows 7 si instalas el sistema en inglés y luego le actualizadas el lenguaje a español, algunas funciones te seguirán reportando que el idioma del sistema esta en inglés por lo que hay que hacer un trabajo adicional para detectar el idioma actual de la interfaz de usuario actual.

 

Pueden bajar la solución completa aquí: Articulo Aplicaciones multilenguaje ( globalización y localización )

 

Espero que le puedan sacar mucho provecho.

 

Saludos.

Bookmark and Share

BogotaDotNet en el Barcamp Bogotá 2010

August 18th, 2010 by JuanK

Hola, BogotaDotNet te invita a participar del Barcamp el próximo 21 de Agosto en las instalaciones de la Fundación Universitaria CAFAM.

 

Un Barcamp es el nombre que recibe una no-conferencia generada por los usuarios. No tiene nada muy formal y los errores/fallas/problemas son siempre bien recibidos. Los asistentes llegan, van poniendo su tema de presentación en una pared; y la gente elige a cuál asistir.

 

Un Barcamper debe estar preparado para:

  • Participar
  • Discutir
  • Llevar su laptop (aunque no es vital)
  • Llegar temprano y ayudar con la puesta en escena
  • Y mantener siempre la buena onda

 

Detalles del evento

Cuándo: Sábado 21 de agosto de 2010

Horario: 9:00a.m.-5:00p.m.

Dónde:  Fundación Universitaria Cafam

 

Inscripción

Para asistir al barcamp NO es obligatorio inscribirse, pero aun así es bueno para que sepamos cuantos puestos montar:Inscripción Barcamp Bogotá 2010

 

Patrocinadores

 

Todavía no tenemos patrocinadores si conoce a algún interesado, por favor comuníquese con los organizadores o escriba en twitter usando el tag barcampbogota.

 

Conferencias

Dentro de la amplia gama de no-conferencias que se darán, algunos de los integrantes de BogotaDotNet serán speaker de estas:

 

Hora

Tema

Ponente

09:00

Desarrollo para Windows Phone 7

Roberto Alvarado

09:30

Entity Framework 4.0, beneficios como herramienta ORM

Nelson Venegas

10:00

SQL Server 2008 R2 Express

John Alexander Bulla

10:30

Parallel Computing Development

Juan Carlos Ruiz

 

 

Los esperamos Inscripción Barcamp Bogotá 2010

Bookmark and Share

C# – 10 steps to consume "The Washington Post" Top news RSS in an IE Toolbar

August 14th, 2010 by JuanK

Hi, few months ago I wrote this article about this tool:“Add-In Express for IE” it huge ease add-on building for Internet Explorer: C#-creating Toolbars, buttons and menus for IE.

 

I found the  tool while I was developing a Microsoft important project in my country, they’ve contacted me to make it and by the way they told me that they’d use this tool to perform this project.

 

As I mentioned earlier at the beginning I believed this was a project based on IE SDK and COM but when Microsoft told me about this tool I started to study and learn about that via internet.

 

Create an Add-on for IE is something pretty interesting and ins essence easy to do using “Add-In Express for IE”.

 

I stop for a while to think what kind of things I can make with this tool and I saw that to take maximum advantage I should devise dynamic components that allow the user to interact in a direct way with toolbar, sidebar or button contents.

 

Among the thousands of different alternatives that may exist to create dynamic components I’ve chosen this two:

  • RSS consumption for data delivery
  • Create a search box

 

In this article I teach how to create a component with Add-In Express for IE that behave dynamically consuming an RSS data .

 

To create a component that reads the RSS Top news from The Washington Post and deploy these data as a text with Hyper link. I’d Drag this component into an IE toolbar.

 

CONSUMING TOP NEWS RSS

I can accomplish this job using this simple method I’ve created:

C#- easily consuming an XML or RSS feed hosted on the web

 

I’ll simply call the method passing it the URL of the RSS Top news: http://www.washingtonpost.com/wp-dyn/rss/linkset/2005/03/24/LI2005032400102.xml

 

STEP 1 – CREATE THE PROJECT

 

 

STEP 2 – CREATE A CLASS THAT IS HOSTING THE METHOD TO CONSUME THE RSS

 

using System.Net;
using System.Data;
 
/// <summary>Provee funcionalidades de conexión a una URL que publica un archivo XML</summary>
public static class RemoteXML
{
    /// <summary>
    /// Se conecta a una URL que representa un archivo XML y convierte la información en un DataSet
    /// </summary>
    /// <param name="URL" />URL del xml publicado en la web</param>
    /// <returns>Dataset que representa los datos XML</returns>
    public static DataSet GetXMLDataSet(string URL)
    {
        HttpWebRequest xmlRequest = (HttpWebRequest)WebRequest.Create(URL);
        DataSet xmlData = new DataSet();
        xmlData.ReadXml(xmlRequest.GetResponse().GetResponseStream());
        return xmlData;
    }
}

 

STEP 3 – CREATE A TOOLBAR

This is simple thanks to "Add-In Express for IE", only:

  • right-click on the project
  • Add new item
  • and…

 

 

STEP 4 – CREATE A LABEL TO DISPLAY THE RSS CONTENT AND LINK

The toolbar as such a Panel is empty, so there I drag a new label, the best part is that controls to add to the toolbar are the same Windows Forms controls Sonrisa (I have placed different colors to distinguish between them).

 

 

STEP 5 – CONSUME THE RSS AND TAKE THE FIRST NEWS

Now using step 2 I’d take RSS and will use the first news. For this purpose I created a RSSEntryInfo structure:

 

/// <summary>Representa información de una entrada RSS</summary>
public struct RSSEntryInfo
{
   public string title, url;
}

 

Then I think the following class RemoteXML method:

/// <summary>
/// Devuelve la última entrada de un RSS
/// </summary>
/// <returns></returns>
private static RSSEntryInfo GetLatestRSSEntry(string RSSUrl)
{
    RSSEntryInfo ni = new RSSEntryInfo();
 
    try
    {
        using (var datos = RemoteXML.GetXMLDataSet(RSSUrl))
        {
            foreach (DataRow row in datos.Tables[&quot;item&quot;].Select())
            {
                ni.title = (string)row[&quot;title&quot;];
                try
                {
                    ni.url = (string)row[&quot;link&quot;];
                }
                catch 
                {
                    ni.url = ((Uri)row[&quot;link&quot;]).AbsoluteUri;
                }
                break;
            }
        }
    }
    catch
    {
        throw;
    }
 
    return ni;
}

 

It is IMPORTANT to be aware that if GetXMLDataSet deployment includes the loading of the XSD RSS 2.0 then the URL will come in object Uri format. See "additional Note" at the end of this article:

C# – easily consuming an XML or RSS feeds hosted on the web

 

STEP 6 – CONFIGURE THE LABEL WITH INFORMATION OBTAINED FROM THE RSS

We must now configure the label with information, so I created a lblLastTopNewInfo inside of the toolbar code method, and I created a variable string to store the URL of the last news. Here I use the top news RSS from The Washington Post: http://www.washingtonpost.com/wp-dyn/rss/linkset/2005/03/24/LI2005032400102.xml

 

/// <summary>URL donde esta la noticia contenida en el label</summary>
string ltnUrl;
/// <summary>Trae la última noticia de un RSS y establece la información necesaria en el label</summary>
private void lblLastTopNewInfo()
{
    var ltnInfo = RemoteXML.GetLatestRSSEntry(&quot;http://www.washingtonpost.com/wp-dyn/rss/linkset/2005/03/24/LI2005032400102.xml&quot;);
    lblLastTopNew.Text = ltnInfo.title;
    ltnUrl = ltnInfo.url;
}

 

STEP 7 – PROGRAMMING THE CLICK EVENT OF THE LABEL TO MAKE IE NAVIGATE TO LAST NEWS URL

To make IE navigate to the URL for the latest news I use other features of "Add-In Express for IE", each created object (toolbar, bar, etc) have two references to IE one to a type object, and another to the same object type but accessed as Interop.SHDocVw.WebBrowser, this ease work with browser, on each object of "Add-In Express for IE" we have this reference in the IEApp field.

So is the label click event:

 

/// <summary>
/// Hace que IE navegue al URL correspondiente
/// </summary>
/// <param name="sender" /></param>
/// <param name="e" /></param>
private void lblLastTopNew_Click(object sender, EventArgs e)
{
    object nullObject =null;
    this.IEApp.Navigate(ltnUrl, ref nullObject,
        ref nullObject, ref nullObject, ref nullObject);
}

 

STEP 8 – MAKE THE LABEL START WITH RSS INFORMATION

Working with the toolbar OnConnect event, this event fires each time the Toolbar integrates with IE.

/// <summary>
/// Configura el estado inicial del label
/// </summary>
/// <param name="sender" /></param>
/// <param name="threadId" /></param>
private void TWPToolbar_OnConnect(object sender, int threadId)
{
    lblLastTopNewInfo();
}

 

STEP 9 – MAKE EACH HALF HOUR REFRESH THE LAST NEWS

With a System.Timers.Timer I setup lblLastTopNewInfo() call every 30 minutes

 

/// <summary>Temporizados para refrescar la última noticia</summary>
System.Timers.Timer timerWpLn = new System.Timers.Timer();
 
/// <summary>
/// Configura el estado inicial del toolbar
/// </summary>
/// <param name="sender" /></param>
/// <param name="threadId" /></param>
private void TWPToolbar_OnConnect(object sender, int threadId)
{
    lblLastTopNewInfo();
    timerWpLn.Interval = 1000 * 60 * 30;
    timerWpLn.Elapsed += new System.Timers.ElapsedEventHandler(timerWpLn_Elapsed);
    timerWpLn.Enabled = true;
    timerWpLn.Start();
}
 
/// <summary>
/// Establece periodicamente los valores del label
/// que muestra la última noticia
/// </summary>
/// <param name="sender" /></param>
/// <param name="e" /></param>
void timerWpLn_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    lblLastTopNewInfo();
}

 

In addition I’ve colored label Blue and I did that to move the mouse over the control the mouse cursor changes to show that it is a hyper link, this in the MouseEnter and MouseLeave events of the label.

 

STEP 10 – INTEGRATE, COMPILE, AND TEST IN IE

This is very easy, in Visual Studio make a double-click on IEModule to open module panel, I’m going to module properties and then go where it says toolbars:

There add a new toolbar and make it as seen in this image:

compile the solution, then right click over the project and select Register ADX project,

 

 

Open IE and go!… view video below.

 

 

http://www.youtube.com/watch?v=ovIZtcmkkNA

Bookmark and Share

« Previous Entries