Tag Archives: Javascript

Internationalization Aspects for Web Applications

Making web applications that supports multiple languages might be a challenging to maintain. So before building you should consider several aspects that are concerned with internationalization.

In summary very often it is not only translating the texts to other “languages” but also supporting “specific culture/locale”s as well!!!.

First of all there are certain terms that are often described when it comes to supporting multiple languages.

Internationalization (I18n)

In software applications, internationalization (often shortened to “I18N , meaning “I – eighteen letters and then a -N”) is the process of planning and implementing applications and services so that they can easily be adapted to specific local languages translations and cultures, a process called localization(which described below) which also means making your applications and services “localizable”.

In Other words the process of changing your software so that it isn’t hardwired to one language/locale/culture.


Localization (l10n)

The process of adding the appropriate resources to your software so that a particular language/locale is supported. This often includes adding language translation files without re-implementing/rebuilding your application.


Approaches to Localizing Web Applications

For web applications you can either do the translations in server side or do it in the client side. This almost always depends on the way your web application has been developed. ie. if it is a SPA application written with AngularJS then doing the translations in client side is preferable.


Server Side Translations for ASP.NET Applications

Obvious choice is to use the .NET framework support to create resource files(.resx) in the application and get the framework support to set CurrentCulture and CurrentUICulture for the current request thread. You need to suffix resource files with standard culture acronym and appropriate resource values will be selected by framework. Visual studio has builtin support for managing resource files.


In summary “CurrentCulture” will be used for date formatting, number formatting etc. and the CurrentUICulture will be used for resource translations. You can configure the settings as following in Web.config file.

<globalization culture="auto:en-US" uiCulture="auto:fr" />


Use of “auto” in globalization setting.

We can set the current culture and “ui culture” as shown above with “auto” prefixed setting. when we use “auto” client user browser’s settings will be used to detect cultures and if not present will be defaulted to “en-US” and “de” in above example. This is through accept-language” request header as shown below. These settings are typically found in OS level or changeable in browser settings.



Set Current Culture and Current UI Culture Programatically

For ASP.NET applications culture settings can be set at application_beginrequest or application_aquirerequeststate. This will affect all web pages unless they have been written at page level as describe below

void Application_BeginRequest(object sender, EventArgs e)
  Thread.CurrentThread.CurrentCulture = new System.Globalization.CreateSpecificCulture("en-US");

  Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

Overriding Culture at Individual Page Level(ASP.NET Web Forms)

ASP.NET web forms has a virtual method called  “InitializeCulture” which can be overridden to change culture settings at page level as shown below.

protected override void InitializeCulture()
        Thread.CurrentThread.CurrentCulture = 
        Thread.CurrentThread.CurrentUICulture = new 


Client Side Translations

For web applications client side translations are often done with the help of JSon files which acts as resource files.

Localization for Angular JS

Angular Js has built in support for datetime, currency simbol and number format culture support via Language translations to be done easier in AngularJS, we can use library.

In brie your angular application’s config phase you need to configure the translate provider service that provided with the library with some basic settings ie. path to language translation resources folder etc.  as shown below

function configure($logProvider, routerHelperProvider, exceptionHandlerProvider, $translateProvider) {
 prefix: '/app/i18n/',
 suffix: '.json'

You can maintain the translation files JSON in your project as indicated below

translation folder

translation json content

Translation JSON Example (Spanish-es)

Within the UI language translation key can be used with the directive given by the translation library as indicated below.

translation in UI

Above the “translate” is a directive given by angular translate library. “Splash_Msg” is a key in translation file which will be included in run time.

Internationalization Concerns

  • Date Time – Week month name translations should be done to support localization. It is often easier to find and use controls that supports these concerns or build your own that supports these features. When date time period calculations done it is often easier to do it with base neutral culture.
  • calendar

    French and English Language Supported Date Picker

    Bootstrap UI DateTime Picker (

    Date time related concerns are probably be the most complex and challenging concern in localization. Time Zone related conversions are extremely hard to deal accurately in web applications with different locales.

  • Unit of Measure – This might be probably not very important but some parts of the world it is often specific units are being used when displaying data. e.g., in Russia, it is normal to use Russian abbreviations (in Cyrillic letters) instead of standard symbols, e.g. кг and not kg.
  • Monetary conversions – It is often useful to display monetary values with locale specific currency units or using money symbols specific to the culture. Frameworks like .NET framework and Angular l18n supports currency formatting and currency symbols but biggest concern is exchange rates.
  • Numeric Formats – In some cultures symbols have been used for different purposes. e.g. Comma and period being used  alternatively for decimals  33.3 (English) > 33,3 (German). Client side validations and server side validations should be used with care for these concerns and additional coding has to be done.
  • String translations – String translations for static string labels are relatively easier to do when it compared to culture specific formatting. Resource files with different languages are often used.

Language/Culture Selections

Culture and language selections can be done in variety of ways in web applications. It can be detected automatically based on request information or can be set by user as briefly described below.

  • Browser settings
    • accept-language http header present in request headers
    • Location of the client – Based on client request remote IP location can be detected and hence the culture can be set automatically.
  • User Selections
    • User selects language – Within the UI we can let user to select preferred language and change the language in user interface.
    • Store it in profile – Based on user registration or in user profile page we can set the language and culture.

What to Translate

  • Static Texts – Static text labels are relatively easily factored out to resource files
  • Application Data – Application data is probably one of the most difficult to be translated unless you use a dynamic translation service to translate data(e.g. Google Translate). It is difficult and inefficient to “store” these translation data and will be difficult to maintain highly changing data to be maintained with different languages unlike static text labels etc. present in a web site.
  • Error Messages – Error messages should also be translated to specific languages. Specially the client side validation script should be written to support multiple langues.
Leave a comment

Posted by on April 22, 2016 in .NET, AngularJs, ASP.NET, Javascript


Tags: , , , , ,

Using JSX With Bable to Write React JS Components

I have been working on number of AngularJS and lately into React JS development as well. If you write ReactJs components just using pure JavaScript it might be tedious task to write virtual DOM to actual browser DOM friendly structure that is necessary by the framework in JavaScript.


var Menu = React.createClass({
    render: function () {
       return React.createElement("nav", {
         className: "nav navbar-default"
        React.createElement("div", {
          className: "container-fluid"
          React.createElement("ul", {
            className: "nav navbar-nav"
            React.createElement("li", {
              className: "active"
              React.createElement("a", {
                className: "active",
                  href: "#"
              }, "Home")),

           React.createElement("li", {
              className: ""
              React.createElement("a", {
                className: "",
                href: ""
               }, "Contact Us")))));

ReactDOM.render(React.createElement(Menu, null), document.getElementById("menu"));

As shown below all above code is just about rendering following simple html menu :-).


Actually this is an insanely unmaintainable structure and this kind of structure is indeed for ReactJs to build the virtual DOM structure that is being internally used.  One obvious choice that given by ReactJs authors is to utilize a transpiled language.

What is Transpilation?

Transpilation is converting one programing language grammar into another programing language typically trough compilation.

One such compiled language is React JSX or React JS extensions.  So React JSX is a language which transforms from a XML like syntactic sugar into actual JavaScript. XML elements, attributes and children are transpiled into arguments that are passed to React.createElement with appropriate nested structure.

How to Use JSX?

One popular  JSX transpiler is Babel.

To setup Babel go to root of your application and execute following in your node command prompt,

npm install babel-cli --save-dev

Note: You need to install NodeJs and npm for this to work

Next we need to setup React for Babel with following.

npm install babel-preset-react -- save-dev

Above will install react transpiler plugin support in node for Babel.
Next we need to setup basic package.json script to easily transpile our JSX files. To that we need to tell in which folder we have JSX files and into which folder the transpiled files should be copied as shown below in package.json file.

  "name": "reacttest",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "devDependencies": {
    "babel-cli": "^6.6.5",
    "babel-preset-react": "^6.5.0"
  "scripts": {
    "build": "babel js -d built --presets react"
  "author": "",
  "license": "ISC"

In above we include “babel js -d built –presets react” which tells that “js” folder is where we have JSX files and “built” folder is where we need to copy transpiled files. As indicated in my project explorer below.

project explorer
Babel Transpilation Source And Target Folders

So we can rewrite the initial menu example with JSX as shown below in the react component,

var Menu = React.createClass({
    render: function() {
       return (
<nav className="nav navbar-default">
<div className="container-fluid">
<ul className="nav navbar-nav">
	<li className="active"><a className="active" href="#">Home</a></li>
	<li className=""><a className="" href="">Contact Us</a></li>


ReactDOM.render(React.createElement(Menu, null), document.getElementById("menu"));

Notice the return statement where you just return more close to HTML version of XML(please note the use of “className” instead of standard “class”). This will be transpiled into native JavaScript that will be syntactically identical to our code sample with code to build the react component if we execute below command in Node command prompt.

npm run build

this will run “build” npm script to compile with babel as shown below.

babel transpilation
Bebel Transpilation Step

Furthermore, you can integrate this command to Gulp or Grunt task runners which maybe to include a development build workflow to make this bit easier.

Leave a comment

Posted by on March 12, 2016 in ASP.NET, Babel, JSX, React


Tags: , , , ,

Optimizing AngularJS Directives By Using Compile Phase

Many AngularJs developers do not use compile phase in directives at all, instead they almost always use link function. I have seen this so much times. But refactoring them later might be painful and might introduce glitches. Learning to use compile function when appropriate is really important skill to have since it will improve performance of your application as well. Consider following AngularJs view fragment,

 <div ng-app="app">
    <div ng-controller="myController">
        <div ng-repeat="fruit in fruits">
            <my-directive fruit="{{fruit}}"></my-directive>

And consider possible naive JS implementation for the directive.

angular.module('app', [])
    .controller('myController', function ($scope) {
    $scope.fruits = ["Bananas", "Apples", "Oranges", "Grapes"];
    .directive('myDirective', function ($log) {
    return {
        template: "<div>{{fruit}}</div>",

        link: function (scope, element, attrs) {

                $log.log('link phase:', attrs.fruit);

As you can see in the above code, common pitfall is all the code that is common to all directive instances and instance specific code in same good old link function! Think how this will impact for the performance of the application, if the directive lives inside of a “ngrepeat” directive and especially if the repeated collection is relatively large performance impact will be augmented. In the above implementation common code is wasting time by executing additional code in each of “ngrepeat” directive’s iterations.

Solution is to use compile function as shown in below implementation.

angular.module('app', [])
    .controller('myController', function ($scope) {
    $scope.fruits = ["Bananas", "Apples", "Oranges", "Grapes"];
    .directive('myDirective', function ($log) {
    return {
        template: "<div>{{fruit}}</div>",

        compile: function (element, attrs) {
            // Code in this block will be called once regardless of instance count
            $log.log('compile phase:', attrs.fruit);
            return function link(scope, element, attrs) {
                // Code in this block will be called for each directive instance
                $log.log('link phase:', attrs.fruit);

One common use from compile phase is to do template customizations dynamically based on runtime conditions. If you run the above sample code in your browser you would see following console output, notice that compile phase log appears only once but for each iteration in ngrepeat item will be logged through link function of the directive.

directive output

What you should understand is in compile phase scope is not linked to directive content, so there are serious limitations on things you could do within it. What this means is you should avoid using it for registering DOM listeners etc. Compile phase is also useful to do template modifications dynamically hence it will be cloned and propagated to each and every directive instances.

Complete sample is available in following js fiddle.

Leave a comment

Posted by on August 5, 2015 in AngularJs


Tags: , , , ,

Safer Way of using JQuery – $ Sign to Avoid Conflics with Other Libraries

Due to dynamic nature in variable declarations and usage in JavaScript it is very easy that one of your variables get overwritten by scripts in other locations. This is very common for global variables so you must avoid using global variables. Many senior developers avoid using global variables but when using JQuery many unaware that they are using $ sign which is a large global variable. However there might be custom libraries or custom script files that use $ sign for their functional object roots.
Much safer option when using JQuery is to use “noConflict” method which will overcome this problem.
You can use the code like following to live with scripts that use $ sign for their own purpose.

(function( $ ) {
  $(function() {
    // More code using $ as alias to jQuery

Here is what the above code does.
During JQuery initialization it will do a sort of backup of “$” sign named object if there is already a one defined. So in this case if you had another library that use $ sign that object will be internally preserved when after JQuery initialized. So to restore the $ sign back you can use jQuery.noConflict();
This will essentially reverts $ sign to other library but which also introduces another annoyance. You are most likely not willing to use “jQuery” instead of much succinct “$” sign when scripting. So to avoid that you can use following technique which will again remap $ sign to JQuery but inside the anonymous function scope but not in the global window scope. So this will allow to use $ in JQuery scripting as usual.

 (function( $ ) {
  $(function() {
    // Jquery coding using $ as alias to jQuery without polluting global $ 

Remember this code will also restore $ sign of JQuery itself if your output has accidentally referred multiple JQuery files or multiple versions of JQuery.

Leave a comment

Posted by on April 30, 2014 in Javascript, jQuery


Tags: ,

JSONP and Ajax

If you are calling to external web service to get JSON data thorough Ajax and if it is in an external domain than your hosted calling application by default web clients will block the Ajax call. Common techniques used for this is JSONP and Cross Origin Resource Sharing(CORS). In JSONP the hack used is if you use tag that requests external javascript file browser will happily download it and server will pad the JSON data in a function call where JSON data included as an argument.
Eg. If you include script tag as following,

Server will respond with data similar to following,
So here “cb” can be a function defined in your application domain which can process the response data effectively. This will silently fail if you try to use $.getJSON.
How ever if you are using lot javascript calls to external domain APIs through javascript including this sort of script tags can be cumbersome tasks. However JQuery $.ajax supports cross domain script access where you can define your $.ajax calls like this. This essentially wraps the JSONP hack above mentioned and can be much convenient to use.

                    url: ‘’
                    cache: true,
                    dataType: 'jsonp',
                    jsonpCallback: 'cb',
                    success: function (data) {
                    error: function (jqXHR, textStatus, errorThrown) {

Leave a comment

Posted by on January 8, 2014 in Javascript



Hoisting In JavaScript Applications

In JavaScript functions if you have variable declarations inside it is best to declare all of them in top of the function which is known as single var pattern. Reason for this is “Hoisting” in JavaScript applications.
Consider following code,

// antipattern
myname = "global"; // global variable
function func() {
console.log(myname); // "undefined" expected "global"
var myname = "local";
console.log(myname); // "local"

It is surprising to see that first alert prints “undefined” rather than the “global” as expected. The reason for this is that when you declare variables inside functions they get “hoisted” which means variable declaration is being moved to the beginning of the function. This is very confusing at first which leads to logical errors hence its best to declare variables and their initializations to the top of the function in JavaScript. So what is happening in first alert is that since “myname” variable declaration moved to the top and it’s initialized to undefined (as normally JavaScript does).
So the above code works as if it was implemented like this,

myname = "global"; // global variable
function func() {
var myname; // same as -> var myname = undefined;
console.log(myname); // "undefined"
myname = "local";
console.log(myname); // "local"
Leave a comment

Posted by on July 22, 2013 in Javascript



Use Jquery command chaining pattern in your own javascript objects

Fluent APIs are really easy and popular(eg. LINQ, JQuery) in programming world because it makes your code more readable and provides really flexible programming pattern. If you write your own javascript for various needs you can easily achive this sort of fluent API pattern relatively easy with chaining sort of pattern.

      var MyLib = MyLib || {};

        MyLib.Calculator = function(initVal) {

            var calcResult = initVal;

            var context = this; // make sure 'this' is not modified by API users for correct usage in closure functions
            this.add = function(x) {
                calcResult = calcResult + x;
                return context;

            this.subtract = function(x) {
                calcResult = calcResult - x;
                return context;

            this.multiply = function(x) {
                calcResult = calcResult * x;
                return context;
            this.divide = function(x) {
                calcResult = calcResult / x;
                return context;

            this.displayResult = function(callback) {

                return context;




        //using calculator

        new MyLib.Calculator(5).add(10).multiply(2).divide(2).displayResult(function (result) { console.log(result);});

This is sort of a method chaining pattern. When you call math operation on calculator class it is returning the calculator object it self while keeping the result for next calls.

Leave a comment

Posted by on September 16, 2012 in Javascript