RSS

Category 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.

resources

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.

<configuration>
<system.web>
<globalization culture="auto:en-US" uiCulture="auto:fr" />
</system.web>
</configuration>

 

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.

accept-language

 

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 = 
            CultureInfo.CreateSpecificCulture("en-US");
        Thread.CurrentThread.CurrentUICulture = new 
            CultureInfo("en-US");

        base.InitializeCulture();
}

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 https://docs.angularjs.org/guide/i18n. Language translations to be done easier in AngularJS, we can use https://github.com/angular-translate/angular-translate 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) {
$translateProvider
 .addInterpolation('$translateMessageFormatInterpolation')
 .preferredLanguage('en')
 .fallbackLanguage('en')
 .useStaticFilesLoader({
 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 (http://plnkr.co/edit/nLw9DMgOLDK1dTIOJq4Q?p=preview)

    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.
Advertisements
 
Leave a comment

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

 

Tags: , , , , ,

Creating Custom Selector in JQuery

JQuery custom selectors are very powerful. This allows you to write custom selectors that are fulfilling needs for your script domain. This makes repetitive complex selector logic much intention revealing and more succinc.
Custom selectors are just like other selectors that selects DOM elements with criteria defined by yourself. Most of the time they just allows you to write more succinct code that will enhance code reuse.
Say if you want to select hyperlinks that point to pdf files and give indication of them with icon you can achieve it with CSS selectors. Particular CSS that is used are indicated below.
jquery custom selector

• Please note for demo purpose I have not spent much time formatting the page

a[href $='.pdf'] { 
background: url("../Images/pdf-icon.jpg") no-repeat scroll right center / 20px auto rgba(0, 0, 0, 0);   
padding-right: 30px; //this padding will universally accommodate the pdf icon
}
 

For above code browser support is not bad either according to here. http://www.quirksmode.org/css/selectors/
However for demo purpose regarding custom JQuery selectors I am achieving the same using JQuery which is however not the better way but I saw that I had used it for one of my old project which I saw when I was doing maintenance fix.

jQuery.noConflict();

(function($) {
	$.extend($.expr[':'], {pdfLinks : function(o) {
		if (typeof o.href !== "undefined") {
			var link = o.href;
			return link.indexOf("pdf", link.length - 3) !== -1;
		}
		return false;
	}});
	
	$("a:pdfLinks").addClass('pdfIcon');
})(jQuery);
.pdfIcon {
	background: url("../Images/pdf-icon.jpg") no-repeat scroll right center / 20px auto rgba(0, 0, 0, 0);
	padding-right: 30px;
}

It is that $.extend does the job of extending JQuery to use the custom selector. In above CSS class we give additional padding of 30px to the right of the selected links so that there is a space to include background pdf icon.

 
Leave a comment

Posted by on May 27, 2014 in Javascript, jQuery

 

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.

jQuery.noConflict();
(function( $ ) {
  $(function() {
    // More code using $ as alias to jQuery
  });
})(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 $ 
  });
})(jQuery);

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,
cb([“value1”,”value2”,”value3”]);
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.

$.ajax({
                    url: ‘http://extdomain.com/jsondata.js’
                    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

 

Tags:

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"
}
func(); 

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"
}
func();
 
Leave a comment

Posted by on July 22, 2013 in Javascript

 

Tags:

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) {

                callback(calcResult);
                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

 

Tags:

Lessons to learn from facebook like button widget for asynchronously loading javascript files

Consider how we load external javascript files in our web pages.

<script type="text/javascript" src="http://mysite.com/scripts/myscript.js"></script>

Normally while this JavaScript file is downloading other loading other components on the page get blocked. Need a proof? well using firebug’s Net tab you can easily see this effect.

The way facebook developers have handled this situation in their facebook like button widget script is really worth to note.

Consider following code which is what their like button widget code looks like.


<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=401009919956151";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

If you look closely at this script what actually it does is creating the script tag dynamically in the page.If you follow this technique what you are essentially  doing is you are downloading the script file asynchronously without a blocking call to a external JavaScript file. Real magic behind this is when you create script tag dynamically you are not blocking browser rendering of the rest of the components while the script file is being downloaded. Browser will create another thread and starts downloading the file.
Why they have used

fjs.parentNode.insertBefore(js, fjs);

instead of trivial version like this

(document.head || document.getElementsByTagName('head')[0]).appendChild(js);

The reasons might be facebook developers don’t control the markup of the host page where this script will be included. What if the host page doesn’t have a head element. Yes it might be not valid markup but many browsers create missing tags and create head tag if host page does not have one. So there might be rare situations that dependance of head tag script might break. Then comes the question why you cannot do this….

document.body.appendChild(js);

Same story as head, almost all browsers create body tag automatically if your document does not contain one.

fjs.parentNode.insertBefore(js, fjs);

in above code what facebook developers have done is find the first script tag in the host page and create facebook script element before the first script tag since any one who uses facebook like widget must have at least one script tag(even if host page of the facebook widget code don’t have a head  or body tags) which is very clever thinking :).

But you may have another function or more script that need to be run when your script file has downloaded. In those situations you could use code like these

 
js.onload = function () {
/*do your magic here*/
} 
 
Leave a comment

Posted by on July 29, 2012 in Javascript

 

Tags: ,