Tag Archives: Internationalization

Making your ASP.NET Global Resource files work in JavaScript. IntelliSense included!

Any modern web application needs localization! You simply can’t ignore the huge amounts of people who doesn’t speak your language, or whose native language is different from yours.

You’re probably using resource files (.resx) in .NET, but how do you go about getting values from your resource files in JavaScript?

Rick Strahl wrote a great blog post about an HttpHandler that serves the content of your resource files in JavaScript. You basically add a script tag to your page that points to the HttpHandler, and the HttpHandler will produce the resources in JavaScript as an object with properties on it, like this:

[code lang="js"]var localRes = {
AreYouSureYouWantToRemoveValue: "Sind Sie sicher dass Sie diesen Wert l\u00F6schen wollen?",
BackupComplete: "Der Backup f\u00FChrte erfolgreich durch",
BackupFailed: "Der Backup konnte nicht durchgef\u00FChrt werden",
BackupNotification: "Diese Operation macht einen Backup von der Lokalisationtabelle. \nM\u00F6chten Sie fortfahren?",
Close: "Schliessen",
FeatureDisabled: "Diese Funktion ist nicht vorhanden im on-line Demo ",
InvalidFileUploaded: "Unzul\u00E4ssige Akten Format hochgeladen.",
InvalidResourceId: "Unzul\u00E4ssige ResourceId",
Loading: "Laden",
LocalizationTableCreated: "Lokalisations Akte wurde erfolgreich erstellt.",
LocalizationTableNotCreated: "Die Localizations Akte konnte nicht erstellt werden."
};[/code]

This is awesome! Now you can access your resource files from JavaScript. Though, I see a single improvement to be made. The thing I don’t like about the HttpHandler approach, is that you don’t get IntelliSense support in Visual Studio. So you have to browse your resource file and copy & paste the resource key to your JavaScript files in order for this to work.

Generate static JavaScript files on Post-build

Instead of generating dynamic files at runtime, I prefer to generate static JavaScript files and then dynamically include the file of the current language on my pages. I do this by calling a Console Application I’ve written on the Post-build event of my ASP.NET (MVC) project, which you can set in the property pages of your project (By the way, did you know that you can open property pages of a project by double clicking the default Properties folder?):

image

What my JavascriptResxGenerator App does, is quite messy. But the essence of the App is, of course, to take a single (or several) .resx files and do the following:

1. Loop through all keys.

2. Make sure the key is not a JavaScript reserved word.

3. Add the key and value to a dictionary (in JavaScript).

4. Write the file.

And for the default culture I generate a –vsdoc file, that I can use for Visual Studio IntelliSense.

Using the JavaScript Resx Generator App

My App supports a single file approach, and directory approach.

Single file: JavascriptResxGenerator.exe C:\Folder\Text.resx C:\Output C:\Output\VsDoc MyApp.Namespace.Resources

Directory: JavascriptResxGenerator.exe C:\Folder C:\Output C:\Output\VsDoc MyApp.Namespace.Resources

The MyApp.Namespace.Resources value, is the namespace your resource dictionary will get enclosed in.

image

Embedding the file on your pages

To include the JavaScript resource file in your page, you simply add a script include tag that points to the correct language. The App will respect the region token used in your Resx files. So if you have a file called Text.da.resx, the JavaScript file generated will include .da.resx at the end. It’s then up to you to add the correct logic to keep hold of the current language and specify the correct region token in order to include the correct JavaScript resource file.

Download

You can download the App here, as a ZIP file.

Translate text in C#, using Google Translate, revisited

A long time ago, I wrote a blog post about how to translate text in C# using Google Translate. Since then, an official AJAX API has been released, which is a much better solution. Reading the comments of the blog post indicates that the code was broken quite quickly!

Google’s AJAX Language API, also includes functionality to detect language from a given string. All you can do on translate.google.com you can do via the API. Reading the class reference for the Translation API, for Flash and other Non-Javascript environments gives us the information we need to perform translations from C#. Most important is the URL and the parameters required and accepted.

Another very important thing we can read in the documentation is this:

Applications MUST always include a valid and accurate http referer header in their requests

We must remember to add a valid referrer when making the actual call!

The response object

Google’s AJAX Language APIs uses JSON, and returns a JSON object containing 3 properties:

  • responseData
  • responseDetails
  • responseStatus

This means we need to have some C# objects that we can use to deserialize the JSON returned from Google. I’m using a generic class called GoogleAjaxResponse<T>, with T being the specific class I want the JSON to be deserialized to.

using System.Runtime.Serialization;

namespace Milkshake.Integration.Google
{
	/// Defines a response from one of Google's AJAX APIs.
	/// The type of object, being returned.
	[DataContract]
	public class GoogleAjaxResponse<T>
	{
		///
		/// Gets or sets the response data.
		///
		///
		/// The responseData from Google AJAX API Call
		///
		/// The response data.
		[DataMember(Name = "responseData", Order = 0)]
		public T ResponseData { get; set; }
	}
}

To deserialize the Translation specific JSON, I use the TranslationResponse class:

using System.Net;
using System.Runtime.Serialization;

namespace Milkshake.Integration.Google.Translate
{
	/// Defines a response from the Google AJAX Translate API.
	[DataContract]
	public class TranslationResponse
	{
		/// Initializes a new instance of the  class.
		public TranslationResponse()
		{
			this.ResponseStatus = HttpStatusCode.OK;
		}

		/// Gets or sets the translated text.
		/// The translated text.
		[DataMember(Name = "translatedText", Order = 0)]
		public string TranslatedText { get; set; }

		/// Gets or sets the response details.
		/// The response details.
		[DataMember(Name = "responseDetails", Order = 1)]
		public object ResponseDetails { get; set; }

		/// Gets or sets the response status.
		/// The response status.
		[DataMember(Name = "responseStatus", Order = 2)]
		public HttpStatusCode ResponseStatus { get; set; }
	}
}

Calling the Google AJAX Translate API

To make the actual call, we can use the HttpWebRequest and HttpWebResponse classes.

using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

namespace Milkshake.Integration.Google.Translate
{
	/// An API Client for the Google AJAX Translate API.
	public class TranslateApi
	{
		/// The JavaScript serializer
		private JavaScriptSerializer _Serializer = new JavaScriptSerializer();

		/// Translates the text.
		public string TranslateText(string inputText, string sourceLanguage, string destinationLanguage, string referrer, string apiKey)
		{
			string requestUrl = string.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={0}&langpair={1}|{2}&key={3}", HttpUtility.UrlEncode(inputText), sourceLanguage.ToLowerInvariant(), destinationLanguage.ToLowerInvariant(), apiKey);

			try
			{
				using (HttpClient http = new HttpClient(requestUrl))
				{
					http.AddReferrer(referrer);
					http.ExecuteRequest();

					string responseJson = http.GetResponseString();

					GoogleAjaxResponse<TranslationResponse> translation = this._Serializer.Deserialize<GoogleAjaxResponse<TranslationResponse>>(responseJson);

					if (translation != null && translation.ResponseData != null && translation.ResponseData.ResponseStatus == HttpStatusCode.OK)
					{
						return translation.ResponseData.TranslatedText;
					}
					else
					{
						return String.Empty;
					}
				}
			}
			catch
			{
				return String.Empty;
			}
		}
	}
}

The response JSON and translated text

Doing a simple test, I translate “Hello world” from English to Danish, and I can see that it works like a charm.

image

Professional translations – even via API!
translation agency

Unit test for verifying references from DataAnnotation validation to the ErrorMessageResourceName value

I love the new model validation features in System.ComponentModel.DataAnnotations. One thing I don’t like though, is that the ErrorMessageResourceName is loosely typed. The ErrorMessageResourceType, however, is a System.Type which will be strongly typed by assigning its value using the typeof(Namespace.ResourceSetType) method.

Since there’s no build-breaking reference between a resource file and the value of the ErrorMessageResourceName on all classes where you use it, I thought it would be cool to have a unit test that verifies the existence of all referenced resource keys.

Remember to add a reference to System.ComponentModel.DataAnnotations.

Code

/// <summary>
/// Verifies that all properties that are decorated with validation data-annotations, refers to 
/// an existing resource. This will make sure, that missing resources are not referenced.
/// </summary>
[TestMethod]
public void All_Properties_With_Validation_Annotations_Must_Refer_To_Existing_Resource()
{
    Assembly assembly = Assembly.Load(new AssemblyName("MyApp.Model.Namespace"));
    var types = assembly.GetTypes().Where<Type>(t => t.IsClass && !t.IsAbstract);

    foreach (var type in types)
    {
        var properties = type.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            var attributes = property.GetCustomAttributes(true);

            foreach (var item in attributes)
            {
                if (item is ValidationAttribute)
                {
                    ValidationAttribute val = item as ValidationAttribute;

                    Assert.IsNotNull(val);

                    if (val.ErrorMessageResourceType != null)
                    {
                        Assert.AreNotEqual(String.Empty, val.ErrorMessageResourceName,
                            String.Format(@"Validation Error Resource specified on property:
                        {0}.{1} is empty!", type.ToString(), property.Name));

                        try
                        {
                            ResourceManager rm = new ResourceManager(val.ErrorMessageResourceType);
                            string resourceValue = rm.GetString(val.ErrorMessageResourceName);
                            Assert.IsFalse(String.IsNullOrEmpty(resourceValue),
                                String.Format(@"The value of the Validation Error Resource specified on property:
                            {0}.{1} is empty!", type.ToString(), property.Name));
                        }
                        catch (MissingManifestResourceException)
                        {
                            Assert.Fail(String.Format(@"Validation Error Resource specified on property:
                            {0}.{1} could not be found!", type.ToString(), property.Name));
                        }
                    }
                }
            }
        }
    }
}

Automatically translate Global and Local Resource (resx) files

Yesterday, I blogged about how you can use Google Translate to translate a string in C#. To make it more useful than just a simple translator, and because I need to translate some Global Resource files for an E-commerce website that I’m working on, I wanted to create a small Windows Application in C# that could read a Global Resource file (.resx) and translate it into a selected language using the method for translating a word in C# that i blogged about yesterday.

image

This is how it looks so far. You simply select the resource file you want to translate. Select the current language of the resource file in the middle box, and select the language you want to translate it to in the last box. Click Translate at it should work. The new resource file will be saved in the same location as the application itself.

Designing for Internationalization

Web sites and Web Applications today, are very often exposed beyond the borders of your home country, and therefore users speak different languages, and has a different currency, date- and time formats etc. ASP.NET provides you with an entire namespace for handling things like this. That is the System.Globalization namespace, where you will find a lot of classes for handling your every day globalization tasks. I’m not going to cover anything in this namespace now, if you want to get your hands dirty take a look at this video: http://asp.net/learn/videos/video-40.aspx where you will see how to use local and global resources for your application.

Using a global resource file for a place to store display text on buttons, labels, validation controls etc. is fine. But if you have an e-commerce site, selling products in multiple regions with different languages, you need an extra level. That level is a way to globalize e.g. the name and description of your product. When a user changes language, the name and description of your “display product details page” should change accordingly.

For me, the ideal solution should not result in extra database columns like name_us, name_da, name_es. This would be a very static solution, as you would have to change your database whenever a new language is added to your application. Nor should it require extra tables, so you need to join like hell, when you need to select a product.

I’ve decided to store e.g. the Name values as XML in the database, and parse that XML into a Dictionary<string, string> property on my Product object, with the key of the Dictionary being the language code (en-US for US English). To me this seems to work just fine. My database design is not getting more complex, and I can get and set values quite easily.

The XML string that goes into my ProductName column in the database table, looks like this:

<cultures><culture code=”en-us”>Logitech SmartCam 124</culture></cultures>

On my Product object, the Name property is a Dictionary:

private Dictionary<string, string> _Name;

public Dictionary<string, string> Name
{
  get { return _Name; }
  set
  {
    if (_Name != value) MarkDirty("Name");
    _Name = value;
  }
}

When I need to get the US English value of the Product.Name property, I call:

p.Name["en-us"]

To get a Dictionary from my XML, I use this helper method:

public static Dictionary<string, string> GetDictionary(string xml)
{
  if (String.IsNullOrEmpty(xml))
    return new Dictionary<string, string>(owner);

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  Dictionary<string, string> dic = new Dictionary<string, string>();

  foreach (XmlNode node in doc.DocumentElement)
  {
    dic.Add(node.Attributes["code"].Value, node.InnerText);
  }

  return dic;
}

And when I want to update my database, after I change the Name of the Product, I convert to Dictionary to an XML string using this helper method:

public static string GetXmlDocument(Dictionary<string, string> dic)
{
  XmlDocument doc = new XmlDocument();
  XmlNode docElement = doc.CreateNode(XmlNodeType.Element, "cultures", "");

  foreach (string key in dic.Keys)
  {
    XmlNode node = doc.CreateNode(XmlNodeType.Element, "culture", "");
    XmlAttribute att = doc.CreateAttribute("code");
    att.Value = key;
    node.Attributes.Append(att);

    node.InnerText = dic[key];

    docElement.AppendChild(node);
  }

  doc.AppendChild(docElement);

  return doc.OuterXml;
}

If you need more information on this huge topic, take a look at the ASP.NET Wiki: http://wiki.asp.net/page.aspx/55/internationalization/