Multilanguage AngularJS apps

Last two years, almost every project that I have worked on, has had the requirement of multilingual graphical user interface (GUI) and messages. This scenario may be important if your country has a multilingual environment or if you are opening to international markets and want to give your users the best possible user experience. The former is little easier as the number of supported languages is usually lower than the latter.

So, what is the problem definition here. We need to support dynamic language setting in GUI for two types of components:

  1. Labels
  2. Dropdown lists

In order to define the actual language the user is using, we chose to use a route parameter for it. Our route became something like this:

Route parameter :lang enabled us to get the user’s current language by calling

Then, we used angular library angular-translate which happened to be very convenient and easy to use for us. The setup is pretty easy. You include angular-translate.js file in your index.html and require reference to ‘pascalprecht.translate’ when defining your module, e.g.

After this, we create a json file for every language we wanted to define, eg. en.js file will contain the labels for English language (sq.js for Albanian, and so on), and it looks like this:

We also need to tell our app the translation configuration. I like to do this in a separate configuration file which I call translation.js (don’t forget to reference it in index.html) and it looks like this:

If later I want to add a translation for Albanian language, I will create one file sq.js which contain the translations e.g.

and I will add this line of code to the translation.js file

and the new language is automatically supported.

Now, in the controller that we want to use translation, we need to to tell the language to be used and we do it like by getting the param from route and pass it to $translate object:

In the view, we put the dynamic labels and messages by using an angularjs binding and filtering it with translate

Here we are, our labels will be translated automatically based on the route parameter :lang.

The labels are translated, now we need to translate the dropdown lists. To support list translation, as we already had a small number of languages to be supported, we chose to save list values in the database lookup tables in all languages, so basically, every lookup table has a structure similar to this:

id name_en name_sq

and when we return the json object for the lookup values, we return an object similar to the object below and bind it in our controller to a scope variable list

then our html select element will look like this

In this way, our ng-options will get automatically the language from lang parameter set in $scope from the $routeParams and it will automatically get the lookup name for the specific language

This might not be the best way to implement multilanguage angularjs apps but it worked pretty well in our case and in several other projects I have worked on.

Hope it helps to you as well.

Developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap

In my post Develop mobile applications using web development skills, I pointed out a list of possible frameworks which can be used to create a hybrid mobile app. My favorite choice so far is using Cordova/Phonegap (Read my post on my opinion about Cordova/Phonegap) in combination with a hybrid app development framework. In my previous mobile applications I have developed, I used to use jQuery mobile as my framework of choice for developing the UI of my apps. Nowadays, I have switched to another combination, which is:

Cordova/Phonegap + AngularJS + Bootstrap

The hybrid mobile app architecture with Phonegap, AngularJS, Bootstrap looks like this:

The presentation layer is built with Bootstrap framework, the app domain is modelled using AngularJS, and the is packaged using Cordova/Phonegap to a native app. Let us go through the components of this hybrid mobile app architecture and describe them.

Bootstrap

Bootstrap is a mobile-first responsive front-end framework. What this mean? Bootstrap has an easy to use responsive grid which allows you to position your layout in a well structured responsive way. As the framework is built with mobile use in mind, it responds well to different screen sizes and adapts the layout of the app easily to different screen sizes. This is a good possibility to use the very same implementation for tablet and mobile devices of different screen sizes. And it is not only the grid that makes it special. It helps you manage typography, responsive images, forms, form validation messages, notification messages, responsive tables, and a good number of UI components. You can download it from getbootstrap.com.

AngularJS

AngularJS

AngularJS

A very powerful, full-featured JavaScript MVW framework. With AngularJS framework, you can give a structure to your app domain model and manage your app logic in a very flexible way. Everything is organized around a model which is displayed through a View. Views can be well structured templated HTML code styled and organized using Bootstrap. Controllers organize the communication between the View, Services, and all other parts. The framework supports a good routing mechanism, which can also be extended by other extension libraries for more powerful functionalities. There are a plethora of extension libraries for AngularJS which add value to the framework by filling in the gaps of the framework. You can get AngularJS from angularjs.org.

 

Cordova/Phonegap

Cordova is an Apache project which creates an underlying platform for developing multiplatform mobile applications. In our case, it makes possible the AngularJS+Bootstrap web app to be packaged to a native mobile app which can be published to the mobile markets and be instlalled in mobile devices. Adobe PhoneGap is a distribution of Cordova.

Basically what Cordova does is to make possible the web app to run inside a WebView component of a native app, we can say it as a native package of a web app. You can do the packaging using Cordova Command Line Interface (CLI) or using Adobe PhoneGap Build which does not require any installations.

The most powerful feature of Cordova in my opinion is the extension possibility by plugins. By installing specific plugins, you get access to device’s hardware such as camera, compass, geolocation, as well as other device specific APIs such as contacts, media, notifications, etc. Very powerful plugins such as barcode reading, push notifications, and many more, can give your application good features by writing few lines of code.

The development process

As we described the architecture parts, let us start with the process of developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap. We start with creating a sample application  which shows you your current location coordinates and demonstrate the development process. The easiest way to start the app development is by creating initial template using Cordova/Phonegap CLI. We do this through this command (if you do not have cordova cli installed, here is the link showing how to do it: https://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html)

The create command requires 3 arguments:

  1. The directory name to be created for generation of the project, in our case “blogSample”
  2. The second argument is the project identifier, in our case “com.ariancelina.blogSample”. Usually it is used as a reversed domain name identifier
  3. The third argument is the display title of the application, in our case “BlogSample”

In this sample code, I used phonegap to create the app. The command equally applies to cordova as well.

If you already had phonegap installed and the app was created successfully, inside blogSample directory you should have a config.xml file and four other directories (hooks, platforms, plugins, and www). Platforms folder contains builds for specific platforms, plugins directory contains installed plugins, and WWW directory contains all our web code (AngularJS + Bootstrap + other files).

To read our location coordinates we need to install the Geolocation plugin (Find the list of plugins) and we do that by executing this command:

Now that we have the initial structure, we need to add platforms to which we want to deploy, but to do that, we need to be inside out app directory, which in our case is blogSample. Adding ios platform is done using the command

After the platform is added, we can build our app using

We can repeat last two commands for all other supported platforms like android, windows phone, etc.

If we want to test our app, we can go to directory blogSample/platforms/ios and lunch BlogSample.xcodeproj and run the app in simulator or existing device.

We have our platform set up, now let us add the AngularJS and Bootstrap files. After we download these (download AngularJS as a zip file so you get all parts of it), we put inside blogSample/www/js directory AngularJS and Bootstrap js files: jquery-1.11.2.min.js (jquery is a dependency of bootstrap and can be downloaded from jquery.com)angular.min.js, angular-route.min.js and bootstrap.min.js. Inside blogSample/www/css directory we put bootstrap.min.css and bootstrap-theme.min.css files. And the last part here is to link these files in our main file index.html. We put css code in head section:

and near the closing body tag we link the javascript files

Now we have the setup ready and we can start coding the logic. We need three things to define to make it work, we need an angular route config which allows us to navigate from page to page, then we need an angular controller, and a view which will display the user his/her current location.

We start with the app.js file which contains the initialization of the js app. This file also is the place where the initialization events are placed. In our case, it looks like this:

We start by defining our angular app, blogSample (line 1). We initiate it and  define the modules which we need (ngRoute, ui.bootstrap). There are other interesting things happening here. As we are used to use jquery ready function to react when the page is loaded and ready for use, here we have onDeviceReady event which is fired when the app is loaded and we can start using it. Inside this event, we will get the current position of the device through this line of code

The getCurrentPosition function which gets the current latitude and longitude of the device, needs two functions as parameters, first being the function that is called if the current location can be obtained successfully, and the latter for errors. The error function is used to report the unavailability of the location. The success function is used to read the coordinates and bind them to our angular app, blogSample through this function

Now that we have our app setup ready, let us define two views, one about page and the other showing location information. Showing the coordinates inside the view is done using

AngularJS will substitute the values inside curly braces with current coordinates set in onSuccess function. But views do not access application level values. We usually link a controller with a view, and view is limited to the scope of that controller, so we need to define a controller to glue the coordinates to the view. The controller will look like:

and finally we add the router configuration to bind the controller to the view and enable the user moving between pages. The router has this code:

The router part defines one default url and ‘/about’ url. The default url ‘/’ binds to main.html view, and the ‘/about’ url binds to about.html view.

Now that we have all the building pieces in place, we need to add the reference of last created files in index.html and the references will look like this:

Now that everything is on place, we can deploy our app to the phone for testing, or run it in a simulator. Running the application is different depending on the platform. You may use the simulators that can be started from phonegap, by xcode, eclipse, or android studio, but for any serious app development, I would strongly suggest you try your app in a real device. I will not go into details about deployment as it is out of scope of this post, but in the simplest scenario, you may go to platforms folder inside  your phonegap project folder, and open the project of the specific platform and run the project from the respective ide.

The complete source code of this application can be found on GitHub https://github.com/acelina/phonegapWithAngularJs, you may download it and try it on your computer.

Develop mobile applications using web development skills

The need for mobile apps has increased dramatically as their number to. The number of mobile devices in use has passed the first billion more than a year ago and it is still increasing. As mobile use is closing the gap with computer use, the gap of development skills is increasing. Mobile platforms are huge with lot of possibilities and not so easy learning curves. Apple iOS supports Objective-C, C, C++, or Swift programming languages, on the other side, Android supports Java programming language. If you want to target these platforms, you have to be proficient in at least two programming languages, which is not very easy. In addition to that, publishing to both platforms requires you develop and maintain the very same application twice. Cross platform development of hybrid webview applications could be your saviour if your requirements are not graphic or resource intensive. With the performance of the mobile devices of our time, we can easily run mobile web applications packed as native apps with a performance close to native apps (games and resource intensive apps make an exception here). But how do we build such an app?

The answer is, by leveraging our existing web development skills with HTML5, CSS3, and JavaScript and packaging it to a native app. But as we make our mind to use these technologies, we have still many other choices to make. The next one is what framework do we want to use. You can choose to make your UI by yourself, but chances are you will make a not so good feeling UI, or you will use quite a good time with it, so going with a framework is a wise choice here. Some of the choices are:

and this is not the end of the list. There are more choices.

Some of these frameworks offer only a mobile friendly User Interface (UI), and some have UI and packaging features. UI only frameworks are jQuery mobile, AngularJS and Bootstrap combination, Ionic and AngularJS, Kendo UI, and intel XDK. If you choose one of these, you can packaged them to a native mobile app using Apache Cordova or Adobe Phonegap Build. Appcelerator Titanium and Sencha Touch offer their own tools of packaging.

How do you make your choice? I would say your experience and required time to market are most important factors here. Perhaps jQuery mobile can give you the fastest way to put the app together, however, I must say it does not give you a very native user experience. Kendo UI has a good set of UI components but it comes at a price. So, in my opinion. there is no clear line here. The project requirements and available skillset influence the choice.

From my personal experience, I have developed few apps using jQuery mobile, Sencha Touch, and AngularJS with Bootstrap. The latter is my favourite choice, but I am looking forward to expand my horizon and try other frameworks as well. Let’s see what future brings.

What do you do when your code has cancer?

One truth about business software applications is that they evolve together with business requirements. From different reasons, sometimes from lack of experience of developers and sometimes from not having enough time to devise good solutions, the code often tends to create some sort of cancer inside, which progressively grows to unmanageable pieces of software until it breaks the whole system.

What do we do if we find such phenomenon in your code?

In my experience I have seen that dealing with such code is almost inevitable in brown field projects. Ignoring them makes things only worse. You have to face it and treat it as it is a disease which needs to be cured. Whenever I face such a situation, I follow these steps:

1. Isolate

Changing the code without breaking the whole system, or refactoring as is called in software development terminology, is not an easy task. Every change must be validated and tested well to ensure that changes do not break or alter the current functionality. In order to stop the bad code growing, we need to isolate it first. Isolation could be done by aiming abstraction through loose coupling the part which needs to be isolated. The abstraction is done by creating interfaces for every class that needs to be isolated and make dependent classes call to interfaces instead of real classes. This may require introduction of inversion of control (IoC) / Dependency Injection (DI) container. Each isolated part must be supported by quality unit tests which ensure that the abstraction maintains the code logic which was in place. Unit tests will also help us in the second phase.

2. Repair

This phase is quite simple. When you arrive here you have isolated the bad code and protect the functionality with unit tests. Now you can safely start to refactor and change the bad code. As you change, you should continuously run the unit tests to check if changes have any unexpected effects. If the unit test coverage is OK and they are written well, then you can safely proceed as unit tests will spot if you have broken something unintentionally. I would highly recommend Test Driven Development in this phase.

3. Integrate

Integrating the isolated code is the last phase, and most probably the easiest. Now the bad code should be gone and the functionality is unchanged. Often you shall find this phase unnecessary as the integration has been done during the phase 2. However, sometimes you will find some kind of double abstractions resulting from a lot of refactorings and you will see the opportunity of cutting these unnecessary code.

Conclusions

Perhaps this strategy looks very simple, but in my experience, it has been a very effective one. We are not always lucky to land in green field projects and define good code from the beginning. Besides, it is not always easy to maintain the code in good shape when the team has many developers and there is not a good development process in place.  Sometimes you deliberately allow the code to go in bad direction as a compromise to speed or resources.

Web services vs. SOA and pretty URL vs. REST

It has been quite a time since Service Oriented Architecture (SOA) and Representational State Transfer (REST) architectures are around, yet there are some misconceptions about them I hear very often, which I would like to discuss here.

1. Having web services does not mean you have an SOA architecture

This is perhaps one of the biggest misconceptions about SOA architecture I hear very very often. I see many developers thinking that if they have a web service or two in their architecture, they say their architecture is an SOA architecture. I think this comes because of two reasons: 1) “Web service” and “service oriented” resemblance in naming makes people think they are the same thing; 2) As web services are the most common way of implementing an SOA architecture, this pushes people think that when they have created one web service, their architecture is an SOA architecture.

An SOA architecture is characterized of composition of independent services which encapsulate business functionality and expose it as a service, which can be  a web service, a windows service,  or any other form of exposure. Ubiquity of web and advancement of web development technologies which made the creation of web services easier have put web services as a mean of choice for implementation of an SOA architecture, however, the definition of a service within an SOA architecture does not put web services in any special position regarding implementation of SOA architectures. Here is the definition of a service from Open Group:

A service:

Is a logical representation of a repeatable business activity that has a specified outcome (e.g., check customer credit, provide weather data, consolidate drilling reports)
Is self-contained
May be composed of other services
Is a “black box” to consumers of the service

 Web services and SOA make a great pair which power a lot of important and popular service out there, but it should be crystal clear to Software Architects, Developers, and anyone contributing to software developments that having web services does not mean you have an SOA architecture.

2. Having pretty URLs does not mean you have a REST architectural style

REST architectural style is another popular topic lately, and as such, is subject to a lot of misconceptions as well. REST has brought simplicity to implementation of web services and is embraced very popularly from the web development community. It plays well with the HTTP protocol, which we are familiar with ever since the beginning of www era.

One characteristic of REST architectural style is that resources are at the center of the architecture, and they are beautifully represented in URLs. REST has brought us pretty URLs, and therefore people have created a connection between the URLs and REST architecture. Leonard Richardson has developed a maturity model which tells the level of your API or RESTful services to what degree are RESTful. Martin Fowler has a great post about richardson maturity model. The levels are described as in this picture:

richardson's rest levels of maturity for REST

The very first level of the pyramid, level 1 is the implementation of URI or introduction of resources and at this level of implementation resides using the “pretty” URLs to connect URIs to resources. The level 2 refers to using HTTP verbs and the most advanced level, level 3 refers to using hypermedia or following HATEOAS.

In Richardson’s model is clearly seen that pretty URLs are the very basic level of implementing RESTful web services towards a REST architecture and clearly explain that having pretty URLs to access your services does not mean you have a REST architectural style in place.

In my opinion, implementing an SOA architecture and RESTful web services requires to have a clear understanding of these concepts, the constraints which come with them, and what is required to have such an architecture in place. Clear understanding will lead to effective architectures which allow us to reach the promises and benefits of these architectural styles.

Architecture of web applications

I consider software development more art than exact science, and as such, in software development almost always there is not a single way of solving a problem. Although there are defined best practices, it is a matter of problem being solved and the knowledge of the team that influences most the definition of the architecture of web applications and software applications in general.

Recent years has brought to popularity using REST in the architecture of web application solutions. I am a huge fan of REST, I like it a lot mostly because of its consistent way of expressing CRUD operations and brings simplicity to the API implementation. The use of REST has been pushed further with advancement of MV* JavaScript frameworks as they tend to have a natural way of consuming resources from REST APIs.

Lately, I am seeing that most newly built web applications tend to use REST in some way, if not exposing APIs, they do consume one or more of them. In my opinion, REST tends to create a viral effect on developers, as much as you use it, you want more of it. Now after we experience REST, I think there is a question which pops up:

Do we have to expose everything as REST API?

The universal answer “it depends” applies here very well! If you want to use a client side framework such as AngularJS that does not need server-side code and is well suitable to consume REST services, it might be a very good idea to expose the whole business logic as REST API and consume it through AngularJS services. This comes with additional benefit that if you want to have a mobile app of your web application, you do not have to write any additional code on server-side to support your mobile app, just consume the very same REST services and you are good to go. A diagram representation of such layered architecture of web applications could look like this:

Web application architecture with REST API and client side MV*

This is one of the most often used architecture styles I am seeing these days in web applications. However, what if you are not keen to using MV* JavaScript frameworks and want to use a server-side backend and generate your HTML representation using let’s say ASP.NET MVC. Do you still need to expose business logic as REST API?

Exposing business logic as REST API or any other form of service layer, if you do not have multiple types of consumers (web, devices, etc.), in my opinion is waste of resources (time and effort). Exposing and consuming services do introduce a level of complexity (you need to put extra effort on error handling, security, versioning, asynchronous access, etc.)  to the architecture and application code. This complexity is non considerable if you have multiple consumers of your application as it avoids writing multiple times the same functionality, however, if there is only one consumer and it is the web GUI, then in my experience I have seen that it only makes things worse. In such a situation, going with an old style server-side backend is a lot more easier. If you say I have a mobile client as well which consumes part of the functionality, in that case I think it is better to create a small REST API service group exposing only that part of the functionality, is a better choice. This will also allow you to develop your web app and mobile app in different paces (if you have lack of developer resources, you shall come to this requirement). The modified version of our new architecture will look like this:

Web application architecture with server-side backend and rest api

Sometimes we are keen to jump to new technologies and architecture styles just because its presentation looks attractive and we like to get our hands in it and give it a try. Often this pushes us to situations which makes maintenance of our code base difficult in later stages of our application lifespan. It is very important that evaluation of the application architecture to be done as early as possible and be judged from the simplicity and maintainability perspective.

 

Offline availability with AppCache

Offline availability of your web application will give a little extra comfort to your users. If using Local storage an appropriate choice to enable web applications to work offline with dynamic data (see my post on Local storage), Application cache (hereafter AppCache) is a good choice for making the static content of the web application available offline.

About AppCache

AppCache enables developers to specify a set of files which need to be cached by the browser. While cached, the requested resources will be served from the disk and this will make your web application available even when users are offline.

Caching static content has several benefits which you may like to leverage, including:

  • Better site performance, as static content will be served from the disk and not requested from the server
  • Better server performance, as less resources will be served and bandwidth will be preserved
  • Users will have the possibility to access your contents while offline, leading to better user experience and satisfaction
  • Mobile users can use the web app even when they are out of internet coverage
  • Mobile user can bookmark/pin the web application to their phone and use it later as a mobile app (offline)

The cache size limit may vary between browsers, but a cache size of 5MB can be expected from modern browsers, and with users permission, the size can be increased if needed.

How do we tell the browser to cache our site, and most importantly, which files to cache. We can do this using a special file called Manifest file. We tie manifest file to the html root element using manifest attribute. e.g.

<html manifest="webapp.appcache">

It is recommended that the extension of the file is .appcache.

Manifest file structure

Manifest file is a simple text file which should be served with “text/cache-manifest” content type. The very first line of the file should be:

CACHE-MANIFEST

and after that files to be cached are listed one per line.

index.html
css/main.css
css/theme.css
js/lib.js

Folders and wildcard specifiers are also permitted.

The common practice is to follow this structure:

CACHE MANIFEST
#23.10.2014 v1.0.10
/file1.html
/file2.jpg

NETWORK:
posts.php

FALLBACK:
offline.html

On the first line we have put the mandatory declaration of “CACHE MANIFEST”. Then on the second line we put date and version as comment. After version, we start declaring files/folders which are to be cached. The “NETWORK” section shows which files should not be cached as they change frequently, and last, with “FALLBACK” we specify what should be used when a resource is unreachable.

The comment part with version number has a significant importance here. The browser will not ask for the cached files unless one of these two is true:

  • The cache is deleted
  • The manifest file has changed

We best note the change of the manifest file by putting a version number in it. Whenever we do a change in any of the cached files, we simply increment the version number to advise the browsers to re-cache the files.

Specifying the manifest file will make the browsers cache the content specified and make the static content of your web app available offline.

 

There is life beyond jQuery

I am a huge fan of jQuery library. For years, jQuery has been my ultimate tool for client side development, and I have used it in any web project I have undertaken. Few weeks ago, I took a project to develop a simple brochure style web site, which had to display a couple of static data, and I decided it to be a Single Page Application (SPA) for the sake of the simplicity and reuse of the page templates.

At the beginning, my idea was to do the dom manipulation with jQuery and templating using jsRender library, but during the planning phase, I thought I should take into consideration using a SPA framework or library. I did a little research on the web, consulted a friend of mine, and then shortened my list to DurandalJS and AngularJS. After giving a quick try to each of them, I decided to go with AngularJS.

Using HTML templates for pages and binding data to the templates was dead simple in AngularJS. The biggest implementation challenge on the project was the internationalization, as the site is multilingual in four different languages. With the help of Angular translate module I managed to translate the labels very easily, and by extracting the language using route params I made the app to decide on the language of controler. The app worked like a charm.

On overall, I managed to finish the whole project within three working days and the most interesting part for me was that I managed to do it without using jQuery at all. Ever since I have started to use jQuery, this is the first project that I have finished without using jQuery. I still think that jQuery is an amazing library and I will continue using it in the future, but there is one other thing, that certainly, I will start using more and more AngluarJS as well.

Train yourself on ASP.NET web development

I have always been supporter of the formal education as a primary way of one’s intellectual forming. However, there are times you need a quick push on a topic you have no experience, or formal education. If this is your case, then here is my advice.

You need to have a curriculum to support your knowledge development, instead of trying to grasp the topic from blog posts and internet pages. As humans tend to learn visually faster than by reading, starting with video training would be a better choice.

Pluralsight is a video training provider for developer topics with videos prepared by some of the most known authors and industry experts of software development community. From the range of the courses offered, here is a learning path I would suggest, from the range of training provided from Pluralsight.

Lets start progressively, from basics to more advanced topics, so here are the courses in this order:

  1. HTML Fundamentals
  2. HTML5 Fundamentals
  3. Using HTML5 and CSS3
  4. JavaScript Fundamentals
  5. Structuring JavaScript Code
  6. jQuery Fundamentals
  7. A Web developer’s guide to images
  8. ASP.NET MVC4 Fundamentals
  9. Building Applications with ASP.NET MVC 4
  10. Building ASP.NET MVC Apps with EF Code First, HTML5, and jQuery
  11. Web performance
  12. Scrum Fundamentals

This curricula is prepared in a way so you will progressively develop yourself to be a web developer. First, you will start with HTML, then continue with HTML5, the hot topic of our time, and proceed further with mixing HTML5 and CSS3 to create modern sites. After that, the curricula continues with JavaScript, the ultimate language of browsers, to continue with a guide to images,  and then further advance with server side programming using ASP.NET MVC framework. At the end, course finishes with Web performance topic to create optimal fast loading sites, and Scrum fundamentals, to develop a structured software development process. 

If you follow this path, my suggestion is that you allow yourself at least two months, if not more, to go through these courses.

I would like to hear your opinion, especially about the results if you have followed this learning path.